반응형

1.

fatal: unable to access 'https://github.com/azthief/mean-chat.git/': Failed to connect to github.com port 443: Timed out


-> 프록시 설정으로 해결


C:\> git config --global http.proxy http://프록시주소:포트번호




2.

fatal: unable to access 'https://github.com/abcdef/test.git/': SSL certificate problem: unable to get local issuer certificate


-> SSL 인증서 오류건으로, SSL 검증옵션하지 않는 방법으로 해결


C:\> git config --global http.sslVerify false



반응형
반응형

Java 사용자에게 있어서 Scala 를 알아두면 좋다는 이야기를 듣고 공부를 하기 위해 로컬PC 에 설치해서 공부하려고 했다.

요즘 애용하는 Sublime Text 3 에서 사용하고자 세팅을 하였다.

우선 Scala 홈페이지에 가서 Scala 를 다운 받아 설치하고

(Scala Download Link)


shell 창에서는 실행이 잘됨을 확인했다.


그리고 Sublime Text 에서 실행을 하려고 하였으나, Build System 을 수동으로 추가하는 방법을 자세히 몰라서 헤매다가 아래와 같은 코드를 발견해서 Build System 추가를 하니 실행이 잘되었다!


(Build System 추가는 Tools - Build System - New Build System 에서 추가하면 된다)


{

    "cmd": ["scala", "$file"],

    "working_dir": "${project_path:${folder}}",

    "selector": "source.scala",

    "shell": true

}



반응형
반응형

ASP.NET MVC 서버실행시


파일이나 어셈블리 'Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' 또는 여기에 종속되어 있는 파일이나 어셈블리 중 하나를 로드할 수 없습니다. 지정된 파일을 찾을 수 없습니다.


라는 에러메시지가 뜨면서 서버가 시작이 되지 않았다.

그래서 찾아보니 Package 관리자에서


PM> Install-Package Microsoft.Web.Infrastructure


위와 같이 실행하니 해당 패키지가 설치되고 정상작동이 되었다!


Visual Studio 2015 기준으로 도구 ->NuGet 패키지관리자 -> 패키지 관리자 콘솔 을 실행하면

하단에 콘솔창이 활성화되고 위의 명령어를 입력해주면 된다.



반응형
반응형

Sub insertTempCells()

    Dim i As Long, n As Long

    n = Val(InputBox("How many rows insert?", "Number"))

        If n <= 0 Then Exit Sub

    For i = 1 To n

        Dim lastRow As Long, lastCol As Long

        ActiveSheet.UsedRange.Select

        lastRow = Selection.End(xlDown).Row

        

        Range("A" & lastRow & ":AH" & lastRow).Copy

        Cells(lastRow + 1, 1).Select

        ActiveSheet.Paste

        

    Next

End Sub


컬럼사이즈는 어떻게 잡아서 어떻게 처리해야될지 몰라서 일단 하드코딩으로 처리......


엑셀 VB Macro 를 사용해서 마지막행을 찾아서 그 행의 내용은 바로 아래 복사하는데,

몇번 복사할지까지 물어봐서 처리하는 구문인데, 좀 더 폭넓게 사용하기 위해 더 많은 수정이 있어야 겠다 ㅠ


아오 매크로 어렵네

반응형
반응형

다행히도 구글링하니깐 바로 해결책이 나왔다.

리눅스에서 위와 같은 현상이 발생시 쉘에서 아래와 같이 실행해준다.


echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p


아직 리눅스 초짜라 정확하게 저 명령들의 내용은 모르나, 대충 사용자가 감시할 수 있는 파일 갯수를 늘려주는거라는 정도만 알거 같다. (이게 아닐 수도;;;;)

좀 더 공부하고 정확히 알면 글을 보충해야겠다.


아 어려워 ㅠ

반응형
반응형

우분투 15.04 버전을 깔고 apt-get 으로 Nodejs 를 설치하려고 하니 계속 0.10 버전으로 설치가 되는거다.

NPM 은 1.4 대 버전으로....


그래서 폭풍검색을 하고 찾은 결과가 아래...


$ curl --silent --location https://deb.nodesource.com/setup_0.12 | sudo bash -


위의 명령을 쉘에서 입력후 다음을 입력


$ sudo apt-get install --yes nodejs


개발환경 세팅하기 참 귀찮네....

그래도 우분투가 버벅도 안되고 예쁘고 좋긴 하네 :)

반응형
반응형

Node.js 로 홈페이지를 만들려고

Yeoman 으로 환경설정을 하였다.

그런데 서버를 실행하려고


C:\>Grunt Serve


를 실행했으나


Warning: Error: Cannot find where you keep your Bower packages.


라는 에러가 발생하면서 웹서버가 작동을 하지 않는 것이었다.


찾아보니 Bower 가 제대로 설정이 안되어있다고 한다.

이걸 또 깔아주려면 Git 이 깔려있어야되고...

Git 을 안깔면 Bower install 시 아래와 같은 에러가 나타난다.


Bower : ENOGIT git is not installed or not in the PATH


윈도우 환경에서 작업을 하는지라


1. 우선 https://msysgit.github.io/ 에서 Git 을 깔아줬다.

2. 그 다음 Git 이 설치된 경로 중, C:\Program Files (x86)\Git\bin, C:\Program Files (x86)\Git\cmd

  두개의 디렉토리를 PATH 설정을 잡아줬다.

3. 그리고 cmd 콘솔창을 다시 띄워준 뒤 bower install 을 실행한 뒤 Grunt Serve 를 실행하니 정상 작동이 되었다!



반응형
반응형

1. bash reload

source ~/.bashrc


2. Alias

alias [사용할 명령어명] '[사용할 실제 명령어]'

ex) #alias vimt='vim -c "NERDTree" $1'

반응형
반응형

npm 을 설치해서 다른 모듈을 사용해보려고 하는데 이게 작동이 잘 안되는거다.

윈도우라서 그런가?

커맨드창을 관리자로 열고 npm install xxxx 하는데, 설치를 하고

npm list 로 목록을 확인하면

다음과 같이 extraneous 라고, 해당 모듈에 표시가 된다.

이 때 다음과 같이 뒤에  --save 옵션을 추가해주고 설치하니 해당 문제가 해결됨!

c:\>npm install resstler --save


반응형
반응형

실행시 다음과 같은 에러가 발생했다.

원인은 바로 중복된 주소를 사용 하려고 해서 발생한 에러였다..

왜 저런 이상한 형식의 영어로 써져있는지;; 알고나서 보니깐 ADDRESS IN USE 라는 글자가 보이네 허허

반응형
반응형

이벤트 버블링 방지

 var event = window.event;
 event.stopPropagation;
 event.cancelBubble = true;

가장 안 쪽에 있는 이벤트(버블링시 가장 먼저 작동하는 이벤트) 함수의 위쪽에 위와 같이 코드를 넣으니깐 다행히도 버블링이 더 이상 발생하지 않았다.

DOM 에서는 html 태그안에 onclick 식으로 이벤트 적용하지 말라고 하는데,

jstl 태그 라이브러리의 foreach 쓰면서 동적으로 생성되는 html 태그에 대해 각각 매개변수를 onclick 이벤트 추가하는데 적용하는 방법을 몰라 일단 임시적으로 저렇게 코드를 집어넣음.......

아오

 

 

 

반응형
반응형

아오, Calendar 은 써도 써도 모르겠다. 헷갈리네;;

뭔가 버그도 있는거 같고.


해당 소스는 원하는 일자를 입력받아서 그 날짜가 해당한 주의 특정요일의 날짜를 구하는 소스임

시작요일은 일요일부터...


package com.test;

import java.util.Calendar;

public class calender {

    public static void main(String[] args) {
        int tYear = 2013;
        int tMonth = 10;
        int tDate = 1;
        Calendar cal = Calendar.getInstance();
        cal.set(tYear, tMonth-1, tDate);
        System.out.println("입력된 날짜 : " + cal.getTime());
        cal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
        System.out.println("입력된 날짜의 일요일  : " + cal.getTime());
        cal.add(Calendar.DATE, -7);
        cal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
        System.out.println("입력된 날짜의 이전주의 일요일 : " + cal.getTime());
        // 입력된 날의 2주뒤 입력을 위해 14를 add
        cal.add(Calendar.DATE, 14);
        cal.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
        System.out.println("입력된 날짜 다음주의 일요일: " + cal.getTime());       
    }
}


반응형
반응형

간혹 svn(서브버전) 프로젝트를 export 하지 않고 넘겨받는 경우가 있는데요,

이런경우 export 한것처럼 .svn 디렉토리들을 일괄적으로 삭제해주는 배치파일입니다.

해당 배치파일을 정리할 폴더 최상위에 위치시키시고 실행하시면 됩니다.


[배치내용]

@echo off

dir /AD /S /B svn* > del.txt

FOR /F   %%a IN (del.txt) do rmdir /S /Q %%a

이 배치파일을 응요하여서 위의 dir /AD /S /B (삭제하고싶은 디렉토리) > del.txt

식으로 변형하여서 사용할 수도 있습니다.


쓰기 나름나름나름~


del.bat


반응형
반응형

비베스크립트로 작성된 파일 삭제 스크립트

필요하신 분들은 받으셔서 vbs 확장자로 파일 만드시고 윈도우 스케쥴러 같은데 배치잡 거셔서 사용하세요~

내부에 대충 수정하시고 ㅎㅎㅎ

'//파일 삭제 스크립트

Option Explicit
  '// 경로지정
Const strRootPath="D:\Ora_data\archive"

  '// 삭제기준 일자지정
Dim nDays
nDays=90

Dim oFSO
Set oFSO=CreateObject("Scripting.FileSystemObject")

Dim oFolder, oSubFolder
Set oFolder=oFSO.GetFolder(strRootPath)

'//마지막 수정된 날짜 기준으로 파일확인 후 삭제
Dim oFile

  For Each oFile In oFolder.Files
  If Int(Now()-oFile.DateLastModified)>=nDays Then
    oFile.Delete
  End If
Next 

반응형
반응형
한번씩 DB가 맛이 가서 작동 안 할때가 있었다.
처음에는 엄청 당황했으나 여러번 이런 일이 생기니 이젠 금방 뚝딱뚝딱 ㅋㅋ


c:\>sqlplus "/as sysdba"

SQL> startup; ORACLE instance started. Total System Global Area 369098752 bytes Fixed Size 2020864 bytes Variable Size 138414592 bytes Database Buffers 226492416 bytes Redo Buffers 2170880 bytes Database mounted. ORA-00600: internal error code, arguments: [kcratr1_lastbwr], [], [], [], [], [], [], [] SQL> recover database; Media recovery complete. SQL> alter database open; Database altered




반응형
반응형

새로운 유저로 DUMP Import 시킬때 사용자 생성시 지정해준 테이블 스페이스를 이용하기 위해서 지정된 테이블 스페이스 외에 모든 권한을 없애줘야지 기존 Export Export 한 사용자와 같은 TableSpace 에 값이 입력되지 않는다.

 

<테스트용 쿼리>

--덤프 export / import 테스트

--테이블스페이스 생성

 

CREATE TABLESPACE TEST_DATA_IMP

     DATAFILE 'D:\oracle\product\10.2.0\oradata\orcl\test_data_imp.dbf' SIZE 10M

     DEFAULT STORAGE

         (INITIAL    10K

          NEXT      10K

          MINEXTENTS 2

          MAXEXTENTS 50

          PCTINCREASE 50);

 

CREATE TEMPORARY TABLESPACE TEST_DATA_IMP_TEMP

     TEMPFILE 'D:\oracle\product\10.2.0\oradata\orcl\test_data_imp_temp.dbf' SIZE 2M;

    

CREATE TABLESPACE TEST_DATA_EXP

     DATAFILE 'D:\oracle\product\10.2.0\oradata\orcl\test_data_exp.dbf' SIZE 10M

     DEFAULT STORAGE

         (INITIAL    10K

          NEXT      10K

          MINEXTENTS 2

          MAXEXTENTS 50

          PCTINCREASE 50);

 

CREATE TEMPORARY TABLESPACE TEST_DATA_EXP_TEMP

     TEMPFILE 'D:\oracle\product\10.2.0\oradata\orcl\test_data_exp_temp.dbf' SIZE 2M;    

 

 

--유저생성

create user TEST_EXP identified by aaaa

    default tablespace TEST_DATA_EXP

    temporary tablespace TEST_DATA_EXP_TEMP

    quota unlimited on TEST_DATA_EXP;

 

grant connect, resource to TEST_EXP;

 

create user TEST_IMP identified by aaaa

    default tablespace TEST_DATA_IMP

    temporary tablespace TEST_DATA_IMP_TEMP

    quota unlimited on TEST_DATA_IMP;

 

grant connect, resource to TEST_IMP;

revoke unlimited tablespace from TEST_IMP;          -- 유저에게서 모든 TableSpace 권한 뺏기

 

 

--테이블 생성

create table TEST(

    id  integer

,   str VARCHAR2(10)   

);

 

insert into TEST values(1,'my');

insert into TEST values(2,'urs');

insert into TEST values(3,'them');

 

commit;

 

--테이블 스페이스 확인

select tablespace_name,sum(bytes),max(bytes)

from dba_free_space group by tablespace_name;

 


반응형
반응형
원본은 아래 링크로
http://www.codeproject.com/KB/scripting/javascript-gotchas.aspx#plusoperator
코드프로젝트에서 긁어왔음


Introduction

This article is an introduction to the weird side of JavaScript, and it definitely has a weird side! Software developers who usually write code in another language will find a lot of intriguing "features" when they begin to write code in the world's most widely used language. Hopefully even seasoned JavaScript developers will find some new gotchas in this article that they can watch out for. Enjoy!

Contents

Functions and operators

Double-equals

The == operator performs a comparison with type coercion. This means that you can compare objects of two different types and it will attempt to convert them to the same type before performing a comparison. For example:

"1" == 1 //true

However, this is very often misleading, and never needed. In the case above, you can convert the String to a Number and use the type-sensitive triple-equals:

Number("1") === 1; //true

Or, better still, ensure your operands are of the correct type in the first place.

Due to its type-coercing behaviour, double-equals frequently breaks the transitivity rule, which is a little bit scary:

"" == 0 //true - empty string is coerced to Number 0.
0 == "0" //true - Number 0 is coerced to String "0"
"" == "0" //false - operands are both String so no coercion is done.

The above comparisons will all yield false when triple-equals is used.

parseInt doesn't assume base-10

If you omit the second parameter in a call to parseInt, then the base will be determined according to the following rules:

  • By default, assume a radix 10.
  • If the number begins with 0x then assume radix 16.
  • If the number begins with 0 then assume radix 8.

The common mistake is to allow a user-input or suchlike which begins with a 0. Radix 8 (octal) is then used and we see this effect:

parseInt("8"); //8
parseInt("08"); //0

Therefore, always include the second parameter:

parseInt("8", 10); //8
parseInt("08", 10); //8

ECMAScript5 side note: ES5 no longer includes the radix-8 assumption. Additionally, omission of the second parameter helpfully raises a JSLint warning.

String replace

The string replace function only replaces the first match, not all matches as you may expect.

"bob".replace("b", "x"); // "xob"
"bob".replace(/b/, "x"); // "xob" (regular expression version)

To replace all matches, you must use a Regular Expression, and add the global modifier to it:

"bob".replace(/b/g, "x"); // "xox"
"bob".replace(new RegExp("b", "g"), "x"); // "xox" (alternate explicit RegExp)

The global modifier ensures that the replacement does not stop after the first match.

The "+" operator both adds and concatenates

PHP, another loosely typed language, has the '.' operator for string concatenation. JavaScript does not - so "a + b" always results in concatenation when either of the operands is a string. This might catch you out if you're trying to add a number to, say, the contents of an input element (which will be a string), so you need to first cast to Number:

1 + document.getElementById("inputElem").value; // Concatenates
1 + Number(document.getElementById("inputElem").value); // Adds

Note that the subtract operator attempts to convert the operands to Number:

"3" - "1"; // 2

Although if you're trying to subtract one string from another then there's probably something wrong with your logic.

Sometimes people try to convert a Number to a string by concatenating with the empty string:

3 + ""; // "3"

But that's not very nice, so use String(3) instead.

typeof

Returns the type of an instance of a fundamental type. Array is actually not a fundamental type, so the typeof an Array object is Object:

typeof {} === "object" //true
typeof "" === "string" //true
typeof [] === "array"; //false

You will get the same result (typeof = "object") when you use this operator against instances of your own objects.

As a side note, "typeof null" yields "object", which is a bit weird.

instanceof

Returns whether the object (or an object in its prototype chain) was constructed using the specified constructor, which is useful when attempting to check the type of one of your own defined object types. However, it is pretty misleading if you create an instance of one of the built-in types using literal syntax:

"hello" instanceof String; //false
new String("hello") instanceof String; //true

Since Array isn't really one of the built-in types (it just pretends to be - hence typeof doesn't work as expected), instanceof does work as expected:

["item1", "item2"] instanceof Array;  //true
new Array("item1", "item2") instanceof Array;  //true

Phew! So in summary, if you want to test the type of a Boolean, String, Number, or Function, you can use typeof. For anything else, you can use instanceof.

Oh, one more thing. Within a function, there is a predefined variable, "arguments", which gives an array of arguments passed to the function. However, it's not really an array, it's an array-like object with a length property, and properties from 0 - length. Pretty strange...but you can convert it to a real array using this common trick:

var args = Array.prototype.slice.call(arguments, 0);

The same goes for NodeList objects returned by DOM calls such as getElementsByTagName - they can also be converted to proper arrays using the above code.

eval

eval interprets a string as code but its use is generally frowned upon. It's slow - when JavaScript is loaded into the browser, it gets compiled into native code; however, every time an eval statement is reached during execution, the compilation engine has to be started up all over again, and that is quite expensive. It looks quite ugly, too, because in most cases it is misused. Additionally, the code being eval'd is executed in the current scope, so it can modify local variables and add stuff to your scope which may be unintended.

Parsing JSON is a common usage; normally people will use "var obj = eval(jsonText);", however almost all browsers now support the native JSON object which you can use instead: "var obj = JSON.parse(jsonText);". There is also the JSON.stringify function for the opposite use. Even better, you can use the jQuery.parseJSON function which will always work.

The setTimeout and setInterval functions can take a string as its first parameter which will be interpreted, so that shouldn't be done either. Use an actual function as that parameter.

Finally, the Function constructor is much the same as eval - the only difference being that it will be executed in the global context.

with

The with statement gives you a shorthand for accessing the properties of an object, and there are conflicting views on whether it should be used. Douglas Crockford doesn't like it. John Resig finds a number of clever uses for it in his book, but also concedes that it has a performance hit and can be a little confusing. Looking at a with block in isolation, it isn't possible to tell exactly what is happening. For example:

with (obj) {
    bob = "mmm";
    eric = 123;
}

Did I just modify a local variable called "bob", or did I set obj.bob? Well, if obj.bob is already defined, then it is reset to "mmm". Otherwise, if there is another bob variable in scope, it is changed. Otherwise the global variable bob is set. In the end, it is just clearer to write exactly what you mean to do.

obj.bob = "mmm";
obj.eric = 123;

ECMAScript5 side note: ES5 strict mode will not support the with statement.

Types and constructors

Constructing built-in types with the 'new' keyword

JavaScript has the types Object, Array, Boolean, Number, String, and Function. Each have their own literal syntax and so the explicit constructor is never required.

Explicit (bad) Literal (good)
var a = new Object();
a.greet = "hello";
var a = { greet: "hello" };
var b = new Boolean(true); var b = true;
var c = new Array("one", "two"); var c = ["one", "two"];
var d = new String("hello"); var d = "hello"
var e = new Function("greeting", "alert(greeting);"); var e = function(greeting) { alert(greeting); };

However, if you use the new keyword to construct one of these types, what you actually get is an object of type Object that inherits the prototype of the type you want to construct (the exception is Function). So although you can construct a Number using the new keyword, it'll be of type Object;

typeof new Number(123); // "object"
typeof Number(123); // "number"
typeof 123; // "number"

The third option, the literal syntax, should always be used when constructing one of these types to avoid any confusion.

Constructing anything else without the 'new' keyword

If you write your own constructor function and forget to include the new keyword, then bad things happen:

var Car = function(colour) {
    this.colour = colour;
};

var aCar = new Car("blue");
console.log(aCar.colour); // "blue"

var bCar = Car("blue");
console.log(bCar.colour); // error
console.log(window.colour); //"blue"

Calling a function with the new keyword creates a new object and then calls the function with that new object as its context. The object is then returned. Conversely, invoking a function without 'new' will result in the context being the global object if that function is not invoked on an object (which it won't be anyway if it's used as a constructor!)

The danger in accidentally forgetting to include 'new' means that a number of alternative object-constructing patterns have emerged that completely remove the requirement for this keyword, although that's beyond the scope of this article, so I suggest some further reading!

There is no Integer

Numerical calculations are comparatively slow because there is no Integer type, only Number - and Number is an IEEE floating point double-precision (64 bit) type. This means that Number exhibits the floating point rounding error:

0.1 + 0.2 === 0.3 //false

Since there's no distinction between integers and floats, unlike C# or Java, this is true:

0.0 === 0; //true

Finally a Number puzzle. How can you achieve the following?

a === b; //true
1/a === 1/b; //false

The answer is that the specification of Number allows for both positive and negative zero values. Positive zero equals negative zero, but positive infinity does not equal negative infinity:

var a = 0 * 1; // This simple sum gives 0
var b = 0 * -1; // This simple sum gives -0 (you could also just
                // do "b = -0" but why would you do that?)
a === b; //true: 0 equals -0
1/a === 1/b; //false: Infinity does not equal -Infinity

Scope

No block scope

As you may have noticed in the previous point, there is no concept of block scoping, only functional scoping. Try the following piece of code:

for(var i=0; i<10; i++) {
    console.log(i);
}
var i;
console.log(i); // 10

When i is declared in the for loop, it remains in scope after the loop exits. So the final call to console.log will output 10. There is a JSLint warning which aims to avoid this confusion: forcing all variables to be declared at the start of a function so that it is obvious what is happening.

It is possible to create a scope by writing an immediately-executing function:

(function (){
    for(var i=0; i<10; i++) {
        console.log(i);
    }
}());
var i;
console.log(i); // undefined

There is another twist which becomes apparent when you declare a var before the inner function, and re-declare it within that function. Look at this example:

var x = 3;
(function (){
    console.log(x + 2); // 5
    x = 0; //No var declaration
}());

However, if you re-declare x as a var in the inner function, there is strange behaviour:

var x = 3;
(function (){
    console.log(x + 2); //NaN - x is not defined
    var x = 0; //var declaration
}());

This is because "x" is redefined inside the function. This means that the interpreter moves the var statements to the top of the function and we end up executing this:

var x = 3;
(function (){
    var x;
    console.log(x + 2); //NaN - x is not defined
    x = 0;
}());

Which makes perfect sense!

Global variables

JavaScript has a global scope which you should use sparingly by namespacing your code. Global variables add a performance hit to your application, since when you access them, the runtime has to step up through each scope until it finds them. They can be accessed and modified either intentionally or by accident by your own code and other libraries. This leads to another, more serious issue - cross-site scripting. If a bad person figures out how to execute some code on your page, then they can also easily interfere with your application itself by modifying global variables. Inexperienced developers constantly add variables to the global scope by accident, and there are a few examples of how that happens throughout this article.

I have seen the following code which attempts to declare two local variables with the same value:

var a = b = 3;

This correctly results in a = 3 and b = 3, however a is in local scope and b is in global scope. "b = 3" is executed first, and the result of that global operation, 3, is then assigned to the local var a.

This code has the desired effect of declaring two local variables with value 3:

var a = 3,
b = a;

'this' and inner functions

The 'this' keyword always refers to the object on which the current function was called. However, if the function is not invoked on an object, such as is the case with inner functions, then 'this' is set to the global object (window).

var obj = {
    doSomething: function () {
        var a = "bob";
        console.log(this); // obj
        (function () {
            console.log(this); // window - "this" is reset
            console.log(a); // "bob" - still in scope
        }());
    }
};
obj.doSomething();

However, we have closures in JavaScript so we can just take a reference to 'this' if we want to refer to it in the inner function.

ECMAScript5 side note: ES5 strict mode introduces a change to this functionality whereby 'this' will be undefined instead of being set to the global object.

Miscellaneous

The absence of data: 'null' and 'undefined'

There are two object states that represent the lack of a value, null and undefined. This is pretty confusing for a programmer coming from another language like C#. You might expect the following to be true:

var a;
a === null; //false 
a === undefined; //true

'a' is in fact undefined (although if you do a double-equals comparison with null then it will be true, but that is just another mistake that results in the code "seeming" to work).

If you want to check that a variable actually has a value, and also follow the rule of never using double-equals, you need to do the following:

if(a !== null && a !== undefined) {
    ...
}

"Aha!", you might say. null and undefined are both falsy (i.e., coerced to false) so you can do this:

if(a) {
    ...
}

But, of course, zero is also falsy, and so is the empty string. If one of those is a valid value for 'a', then you will have to use the former, more verbose option. The shorter option can always be used for objects, arrays, and booleans.

Redefining undefined

That's right, you can redefine undefined, as it isn't a reserved word:

undefined = "surprise!";

However, you can get it back by assigning an undefined variable or using the "void" operator (which is otherwise pretty useless):

undefined = void 0;

...and that's why the first line of the jQuery library is:

(function ( window, undefined ) {
    ... // jQuery library!
}(window));

That function is called with a single parameter ensuring that the second parameter, undefined, is in fact undefined.

By the way, you can't redefine null - but you can redefine NaN, Infinity, and the constructor functions for the built-in types. Try this:

Array = function (){ alert("hello!"); }
var a = new Array();

Of course, you should be using the literal syntax to declare an Array anyway.

Optional semicolons

Semicolons are optional so that it's easier for beginners to write, but it's pretty yucky to leave them out and doesn't really make anything easier for anyone. The result is that when the interpreter gets an error, it backtracks and tries to guess where the semicolon is supposed to go.

Here is a classic example, courtesy of Douglas Crockford:

return
{
    a: "hello"
};

The above code does not return an object, it returns undefined - and no error is thrown. A semicolon is automatically inserted immediately after the return statement. The remainder of the code is perfectly valid, even if it does not do anything, and this should be evidence enough that in JavaScript, an opening curly brace should go at the end of the current line instead of a new line. It isn't just a matter of style! This code returns an object with a single property "a":

return {
    a: "hello"
};

NaN

The type of NaN (Not a Number) is... Number.

typeof NaN === "number" //true

Additionally, NaN compared to anything is false:

NaN === NaN; // false

Since you can't do a NaN comparison, the only way to test whether a number is equal to NaN is with the helper function isNaN.

As a side note, we also have the helper function isFinite, which returns false when one of the operands is NaN or Infinity.

The 'arguments' object

Within a function, you can reference the arguments object to retrieve the list of arguments. The first gotcha is that this object is not an Array but an array-like object (which is an object with a length property, and a value at [length-1]). To convert to a proper array, you can use the array splice function to create an array from the properties in arguments:

(function(){
console.log(arguments instanceof Array); // false 
var argsArray = Array.prototype.slice.call(arguments);
console.log(argsArray instanceof Array); // true 
}());

The second gotcha is that when a function has explicit arguments in its signature, they can be reassigned and the arguments object will also be changed. This indicates that the arguments object points to the variables themselves as opposed to their values; you can't rely on arguments to give you their original values.

(function(a){
    alert(arguments[0]); //1
    a = 2;
    alert(arguments[0]); //2
}(1));

In ES5 strict mode, arguments will definitely point to the original input argument values, as opposed to their current values.

The end!

So that concludes my list of gotchas. I am sure there are more, and I look forward to seeing lots of insightful comments!

PS - I do actually like JavaScript.





덤) 일단 원본 그대로 긁어왔는데 상당히 유용한 정보인거 같다. 차후에 천천히 한글화 해봐야지
반응형
반응형
오라클에서 DB 접속시 위와 같은 에러가 뜨는 경우를 볼것이다.

다양한 원인이 있겠으나, 나의 경우에는

TNS(tnsnames.ora)에서 접속 식별자의 띄워쓰기가 잘못되어서 일어나는 현상이었다.

예를 들어

   ORACLR_CONNECTION_DATA = 

  (DESCRIPTION = 

    (ADDRESS_LIST = 

      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) 

    ) 

    (CONNECT_DATA = 

      (SID = CLRExtProc) 

      (PRESENTATION = RO) 

    ) 

  ) 

 
위와 같이 ORACLR_CONNECTION_DATA(접속식별자) 앞에 공백이 있으면 인식을 하지 못한다.

그래서 저 공백을 업애주고 

  ORACLR_CONNECTION_DATA = 

  (DESCRIPTION = 

    (ADDRESS_LIST = 

      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC_FOR_XE)) 

    ) 

    (CONNECT_DATA = 

      (SID = CLRExtProc) 

      (PRESENTATION = RO) 

    ) 

  ) 

 
다음과 같이 해주면 문제없이 잘 돌아간다.

 
반응형
반응형
SQL Server 2005 Management Studio Express 를 설치하는 도중 중간에 에러가 나면서 설치가 안되는 경우가 있습니다.

이것은 비스타나 윈도우 7 에서의 보안강화 때문에 관리자권한이 아니라서 생기는 에러로

설치시 탐색기에서 우클릭을 하여 윈도우 탐색기를 [관리자 권한으로 실행]한 상태에서 설치를 진행하면

무사히 설치를 완료할 수 있습니다.

다들 단디 설치 해보세요~~~~
반응형
반응형
// CTRL+G 키를 눌러서 오늘날짜 입력
function inputToday(v,e){
   var key = (document.all) ? e.keyCode : e.which;

   //71은 g 의 키코드값     
   if(e.ctrlKey&& event.keyCode == '71'){

      var r=window.event.srcElement.createTextRange();

   if (v.createTextRange) v.currentPos = document.selection.createRange().duplicate();

      var d = new Date();
      var v_month=d.getMonth()+1;
      var v_date=d.getDate();
      if(v_month<10)
          v_month='0'+d.getMonth().toString();
      if(v_date<10)
          v_date='0'+d.getDate().toString();
      var today=d.getFullYear()+'-'+v_month+'-'+v_date;

   if (v.createTextRange && v.currentPos) {
       var currentPos = v.currentPos;
       currentPos.text = currentPos.text.charAt(currentPos.text.length - 1) == ' ' ? today + ' ' : today;
   }

   return false;
   }
}


커서가 위치한 곳에서 CTRL+G 키를 누르면 오늘 날짜가 입력되는 함수입니다.
사용시 자바스크립트 이벤트 onkeydown="inputToday(this,event);"   만 입력해 주시면 사용가능합니다.

다른단축키값을 이용하려고도 하였으나 다른건 이미 브라우저에서 단축키로 사용되고 있는 녀석들이라 그나마 예약되어있지 않은 CTRL+G 를 사용....
반응형
반응형
변수 이름 '@custName'이(가) 이미 선언되었습니다. 변수 이름은 쿼리 일괄 처리 또는 저장 프로시저 내에서 고유해야 합니다.

dataset에 불어온 자료들을 DB 에 집어넣으려고 하는데 위와 같은 에러가 발생했다.
알고보니 for 문을 이용하여 순차적으로 insert 명령을 사용하여 값들을 DB에 넣게 코딩하였는데
SqlCommand 객체에서 paremeter가 이미 선언되었는데 paremters 들을 해제해주지 않고 다시 insert 하려니깐 생긴에러..

cmd.Parameters.Clear();

위와 같이 파라미터를 초기화해주고 파라미터를 선언해주자!


반응형
반응형
1. 파이어폭스에서 alert(); 는 작동 안한다 alert('aa'); 처럼 매개변수가 있어야 작동한다.

2. css 속성 줄때, 특정 아이디 안에 있는 클래스를 찾을 경우 띄워쓰기를 해주야된다
ex) #myhome.cover a <- 작동안함
     #myhome .cover a <- 이렇게 속성별로 다 띄워줘야한다.
반응형
반응형
11자리로 된 숫자들이 있는 컬럼이 있는데 이 컬럼이 float 형이었다
그런데 이 녀석을 문자열이랑 더하려고 하니깐 계속 문제가 생기는거다

float를 varchar 형으로 컨버팅해서 하니 원하는 값은 나오지 않고
그래서 결국 편법을 사용해서 성공!!!

그냥 float를 numeric 으로 바꾸고 varchar 형으로 바꾸니 아름답게 결과가 나왔다

걍 아래는 예제

select '0'+cast(cast(휴대폰 as numeric(11,0)) as varchar(11)) from 고객목록



반응형
반응형
종종 프로그래밍을 하다가 버튼이벤트를 특정조건에서 실행해야되는 경우가 생긴다
이럴때 버튼이벤트 내에 함수를 집어넣지 말고
다음과 같이 비하인드 코드에 집어넣어주면 끝


버튼이벤트명(null, null)
예) btn_start_Click(null, null)

버튼 이벤트 외에 다른 이벤트들에서도 물론 동작은 잘된다

아직까지 이상은 없었음
반응형
반응형
우편번호 데이터들이 엑셀형식으로 저장되어 있으므로 MS-SQL에서는 간단하게 데이터 가져오기를 사용하여 테이블에 입력을 할 수 있었다.

하지만 MY SQL에서는 약간 이래저래 수정도 해주면서 작업을 해야되었다.
그래서 간단한 작업절차를 써보도록 하겠다


1. 하단에 명시된 페이지로 이동하여 원하는 DB 정보를 다운받는다.




2. 다운받은 엑셀파일을 csv 형식으로 변형시킨다.
 다른이름으로 저장 -> 다른형식 -> csv 형식선택

저장을 하면 각 필드들은 쉼표(,) 로 구분이 된다.


3. 해당 주소체계에 맞는 형식의 테이블을 생성한다


4. my sql 입력 커맨드창에서 다음의 명령어를 실행한다

load data infile [해당 csv 파일명] into table [db명].[테이블명] fields terminated by ',' optionally enclosed by '"' lines terminated by '\n';

예) load data infile 'c:\\download\\zipcode.csv' into table db1.tb_zipcode fields terminated by ',' optionally enclosed by '"' lines terminated by '\n';

* 해당명령어에 대한 자세한 설명은 다음 링크 참고
http://radiocom.kunsan.ac.kr/lecture/mysql/prototype/prototype_load_data_infile.html

5. 아름답게 저장된 주소DB들을 보며 흐뭇해한다.

반응형
반응형
인터넷에 올릴 플래시 파일을 캠타시아로 제작하였다.

플래시파일만 실행시켰을때 잘되던 파일이 웹서버에서 작동시키면 재생이 되지 않는것이었다

무엇이 문제일까? 싶어서 조사해본 결과!!

웹서버에서 mp4 확장자를 인식하지 못해서 그랬던것!!

mp4 확장자 인식을 위해 MIME 형식을 지정해주니 잘 작동한다!!

IIS 의 경우

MIME 추가를 아래와 같이 하면 OK

확장명: .mp4
MIME형식:video/mp4

반응형
반응형
나는 파이어폭스를 선호한다
그래서 홈페이지 제작을 해도 파폭으로 테스트를 하는 편이다

그런데, 어느날 홈페이지를 만들다 테스트를 하는데, 경고창이 뜨지 않는것이다.

어? 코드가 잘못됐나? 싶어서 코드 여기저기를 만져보았지만 아무이상은 없고...
브라우저 문제인가? 싶어서 IE에서 돌리니 alert 가 매우 잘 나오는것이다.

분명 파폭에서 자바스크립트 사용 상태로 해놓았는데....

일단 만능 디버거인 파이어버그를 열어놓고 디버깅을 해보았다
그랬더니!!


uncaught exception: [Exception... "Not enough arguments [nsIDOMWindowInternal.alert]" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: http://localhost/bul/menu.asp# :: onclick :: line 1" data: no]

위와 같은 에러가 뜨는것이다...역시 스크립트에 문제가 있구나 싶어서

alert();

인 코드에 alert('aa'); 식으로 변수를 넣어줬더니
작동이 매우 잘되는것이다!!!!

파폭에서 자바스크립트가 이정도로 섬세하다니....

아무튼 삽질을 참 오래하였다.

다른 분들은 헷갈리지 마시고

파폭에서 자바스크립트 alert 를 사용할때 꼭!!!!!!!!!!!!!!! 매개변수를 넣어주시길!!! (빈값이면 걍 alert(''); 식으로라도)
반응형
반응형
-- Create products table.
CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))
GO
-- Inserting values into products table.
INSERT INTO products (product) VALUES ('screwdriver')
INSERT INTO products (product) VALUES ('hammer')
INSERT INTO products (product) VALUES ('saw')
INSERT INTO products (product) VALUES ('shovel')
GO

-- Create a gap in the identity values.
DELETE products
WHERE product = 'saw'
GO

SELECT *
FROM products
GO

-- Attempt to insert an explicit ID value of 3;
-- should return a warning.
INSERT INTO products (id, product) VALUES(3, 'garden shovel')
GO
-- SET IDENTITY_INSERT to ON.                    <--  이녀석이 on 이 되어야지만 실행이된다. 안그러면 에러가뜸
SET IDENTITY_INSERT products ON
GO

-- Attempt to insert an explicit ID value of 3
INSERT INTO products (id, product) VALUES(3, 'garden shovel')
GO

SELECT *
FROM products
GO
-- Drop products table.
DROP TABLE products
GO


반응형
반응형
javascript를 이용한 Ajax 웹페이지 제작시

-1072896748 번 에러가 뜨는 경우가 있습니다.

원인은 문자셋때문으로 한글로 결과값을 넘기는 경우가 생기는걸로 보이네요..

그런고로 페이지에 한글속성을 넣어주면 됩니다

asp.net 에서는 최상단에
<%@ page language="c#" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR" %>

asp 에서는 페이지내에
<%
Response.CharSet = "euc-kr"
%>


를 추가하시면 정상적으로 작동됩니다






반응형
반응형
Function getReserDate(reserYear,reserWeek,reserWeekDay)
    yearFirstDay = CDate(reserYear & "-01-01")        '해당년의 첫번째 일
    firstDayWeek=Weekday(yearFirstDay,2)-1   
    addDay = (reserWeek-1)*7+reserWeekDay-firstDayWeek    '첫번째 일에서 더할 날 수
    If reserWeekDay=6 Then addDay=addDay-7        '일요일의 경우 7을 빼줘야 값이 나옴

    getReserDate=DateAdd("d",addDay,yearFirstDay)        '해당예약일 값 반환
End Function


에휴~ 나쁜머리로 짜니라 고생했네-_-;

주랑 요일 값만 있을경우 날짜 계산하는 함수입니다.
필요하신분 가져가시구, 혹시 좀 더 아름다운 소스를 가지고 계신분은 제보 부탁드려요~~~~~
반응형

+ Recent posts