问:
Adding fonts to rails
I'm trying to add a custom font to rails and no matter what I do it doesn't seem to work, I've read a few other questions on github about this issue but I cant get it to work for myself.

I have put the font file into

```<code>app/assets/fonts
</code>```

the name of the file is called "above.tff" and I have declared it in my CSS like this

```<code>@font-face {
  font-family: 'above';
  src: url(/assets/above.tff) format('truetype');
}
</code>```

Which is how the top answer in this question says to do so Official way of adding custom fonts to Rails 4?

And then I apply it to the element using

```<code>font-family: 'above';
</code>```

And it doesn't work and I get this error on my console.

ActionController::RoutingError (No route matches [GET] "/assets/above.tff"):

actionpack (5.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:63:in `call'
web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.5.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.1.4) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.1.4) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.1.4) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:11:in `block in call'
activesupport (5.1.4) lib/active_support/logger_silence.rb:20:in `silence'
activesupport (5.1.4) lib/active_support/logger.rb:63:in `block (3 levels) in broadcast'
activesupport (5.1.4) lib/active_support/logger_silence.rb:20:in `silence'
activesupport (5.1.4) lib/active_support/logger.rb:61:in `block (2 levels) in broadcast'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:11:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/request_id.rb:25:in `call'
rack (2.0.3) lib/rack/method_override.rb:22:in `call'
rack (2.0.3) lib/rack/runtime.rb:22:in `call'
activesupport (5.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/static.rb:125:in `call'
rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
railties (5.1.4) lib/rails/engine.rb:522:in `call'
puma (3.11.0) lib/puma/configuration.rb:225:in `call'
puma (3.11.0) lib/puma/server.rb:624:in `handle_request'
puma (3.11.0) lib/puma/server.rb:438:in `process_client'
puma (3.11.0) lib/puma/server.rb:302:in `block in run'
puma (3.11.0) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
```

答:
Try this font-url method is available which correctly routes and checks the assets/fonts directory

```<code>@font-face {
  font-family: 'above';
  src: font-url('above.tff') format('truetype');
}
</code>```

A couple of things,

I really doubt the filename would be above.tff haven't see tff extension for fonts before, could be a typo, but i think it should be ttf

after changing to the above code, rename your css file to have an extension of scss

ContentLicense: CC BY-SA 4.0

Title: Adding fonts to rails

Body:
I'm trying to add a custom font to rails and no matter what I do it doesn't seem to work, I've read a few other questions on github about this issue but I cant get it to work for myself.

I have put the font file into

app/assets/fonts

the name of the file is called "above.tff" and I have declared it in my CSS like this

@font-face {
  font-family: 'above';
  src: url(/assets/above.tff) format('truetype');
}

Which is how the top answer in this question says to do so Official way of adding custom fonts to Rails 4?

And then I apply it to the element using

font-family: 'above';

And it doesn't work and I get this error on my console.

ActionController::RoutingError (No route matches [GET] "/assets/above.tff"):

actionpack (5.1.4) lib/action_dispatch/middleware/debug_exceptions.rb:63:in `call'
web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.5.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.1.4) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.1.4) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.1.4) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.1.4) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:11:in `block in call'
activesupport (5.1.4) lib/active_support/logger_silence.rb:20:in `silence'
activesupport (5.1.4) lib/active_support/logger.rb:63:in `block (3 levels) in broadcast'
activesupport (5.1.4) lib/active_support/logger_silence.rb:20:in `silence'
activesupport (5.1.4) lib/active_support/logger.rb:61:in `block (2 levels) in broadcast'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:11:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/request_id.rb:25:in `call'
rack (2.0.3) lib/rack/method_override.rb:22:in `call'
rack (2.0.3) lib/rack/runtime.rb:22:in `call'
activesupport (5.1.4) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.4) lib/action_dispatch/middleware/static.rb:125:in `call'
rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
railties (5.1.4) lib/rails/engine.rb:522:in `call'
puma (3.11.0) lib/puma/configuration.rb:225:in `call'
puma (3.11.0) lib/puma/server.rb:624:in `handle_request'
puma (3.11.0) lib/puma/server.rb:438:in `process_client'
puma (3.11.0) lib/puma/server.rb:302:in `block in run'
puma (3.11.0) lib/puma/thread_pool.rb:120:in `block in spawn_thread'

Body:
Try this font-url method is available which correctly routes and checks the assets/fonts directory

@font-face {
  font-family: 'above';
  src: font-url('above.tff') format('truetype');
}

A couple of things,

I really doubt the filename would be above.tff haven't see tff extension for fonts before, could be a typo, but i think it should be ttf

after changing to the above code, rename your css file to have an extension of scss


来源: stackexchange

问:
Detect event when any html link is clicked on WebBrowser
I am developing a logging system that detects when the hyperlinks stored in an html webpage (in turn, stored into a C# WebBrowser object) are clicked.

I am using the NewWindow event, but in order for the event to be logged, the window must be closed (ie: I can't log more than one click for the same hyperlink). I would like to record every single click, regardless of the fact that the window the hyperlinks refer to is open or not.

Any ideas about how to do it?

Cheers

答:
Do you absolutely need to track the click itself, or can you track the result of the click?

You can use the Navigating and Navigated events to detect when the user navigates to another page.

That gap between that and your question is that these events a) don't capture when a link is clicked that doesn't result in navigation, and b) do capture navigation that wasn't caused by clicking a link.

If you're using the control to display your own website, which you can modify, then you can raise events from within your page using Javascript that can be monitored by the application hosting the control. Here's an answer providing more detail on that.

In that scenario you're adding JavaScript event handlers to the click event of your links. Those event handlers in turn call window.external.SomeMethod(args), and the browser control invokes your C# method and passes the arguments to it.

ContentLicense: CC BY-SA 3.0


问:
Correct syntax for a async/await function?
I've defined a resolversMap and I need to use async/await for that as I'm doing a DB request. I'm failing with the correct syntax:

```<code>const resolvers = {
  Mutation: {
    signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = Users.findOne({ username: username })
    }
  }
}
</code>```

I tried this:

```<code>const resolvers = {
  Mutation: {
    async signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}
</code>```

Update

It's working if I define the function like this:

```<code>async signinUser (obj, args) {}
</code>```

But what is the difference between this and signinUser: (obj, args) => {}?

答:
You must define the function with async signinUser (obj, args) => {} because it is no longer a normal function. An async function returns a promise, while a normal function returns what you returned.

If it is not set to async, javascript disables async xyz() in it.

Body:
I've defined a resolversMap and I need to use async/await for that as I'm doing a DB request. I'm failing with the correct syntax:

const resolvers = {
  Mutation: {
    signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = Users.findOne({ username: username })
    }
  }
}

I tried this:

const resolvers = {
  Mutation: {
    async signinUser: (root, { username, password }) => {
      const db = DB.getDB()
      const Users = db.collection('users')
      const user = await Users.findOne({ username: username })
    }
  }
}

Update

It's working if I define the function like this:

async signinUser (obj, args) {}

But what is the difference between this and signinUser: (obj, args) => {}?


问:
Taylor Series of ln(x) in Matlab
I am trying to compute the taylor series of ln(x) for any value of x.

What I have so far is:

```<code> clear
 clc
 n = input('Enter number of iiterations (n): ' );
 x = input('enter value of x (x): ');
 y = zeros(1,n);
 for i = 0:n
  y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end
</code>```

But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?

答:
This is a one liner in addition to the for-loop answer provided by @farbiondriven

For 0<x<1 :

```<code>sumLn = @(x, n)(sum(((-1).^(0:n-1)).*((x-1).^(1:n))./(1:n)));
sumLn(0.5,10)

ans =

   -0.6931

>> log(0.5)

ans =

   -0.6931
</code>```

For x>0.5 :

```<code>sumLn = @(x, n)(sum( ((x-1)/x).^(1:n) ./ (1:n) ));
sumLn(2,10)

ans =

    0.6931

log(2) =

    0.6931
</code>```

Note: The variable x in this formula is bounded as mentioned in this link.

Title: Taylor Series of ln(x) in Matlab

Body:
I am trying to compute the taylor series of ln(x) for any value of x.

What I have so far is:

 clear
 clc
 n = input('Enter number of iiterations (n): ' );
 x = input('enter value of x (x): ');
 y = zeros(1,n);
 for i = 0:n
  y(i+1)=sum + (-1)^(n+1)*(x-1)^n/n;
end

But this code seems to be broken and I can't figure out why. Any suggestions on how to improve?

Body:
This is a one liner in addition to the for-loop answer provided by @farbiondriven

For 0<x<1 :

sumLn = @(x, n)(sum(((-1).^(0:n-1)).*((x-1).^(1:n))./(1:n)));
sumLn(0.5,10)

ans =

   -0.6931

>> log(0.5)

ans =

   -0.6931

For x>0.5 :

sumLn = @(x, n)(sum( ((x-1)/x).^(1:n) ./ (1:n) ));
sumLn(2,10)

ans =

    0.6931

log(2) =

    0.6931

Note: The variable x in this formula is bounded as mentioned in this link.


问:
python: TypeError: list indices must be integers or slices, not str
I was trying almost everything, and all the time I have the same problem :< </p>

```<code>from flask import Flask, request

app = Flask(__name__)

users =[]

@app.route("/user/<username>/set-password", methods=["POST"])
def set_password(username):
     data=request.get_json()
     new_password = data["password"]
     users[username] = new_password
     return "Set password of {} to '()' "\
         .format(username, new_password)

app.run(debug=True)
</code>```

答:
It looks like "users" is a list, and "username" is probably a string. You likely want "users" to be a dict:</p>

```<code>users = {}
</code>```

Body:
I was trying almost everything, and all the time I have the same problem :<

from flask import Flask, request

app = Flask(__name__)

users =[]

@app.route("/user/<username>/set-password", methods=["POST"])
def set_password(username):
     data=request.get_json()
     new_password = data["password"]
     users[username] = new_password
     return "Set password of {} to '()' "\
         .format(username, new_password)

app.run(debug=True)

Body:
It looks like "users" is a list, and "username" is probably a string. You likely want "users" to be a dict:

users = {}


问:
SWIFT 4 nested JSON Struct - Codable
I'm having issues creating a struct to parse JSON in Swift 4. I'm able to parse small JSONs and JSONDecoder seems to work fine. Just need help to create a struct to parse JSON like that:

```<code>{
    "main": {
        "solutions": [
                    {
                    "exersises": [
                                     {
                                     "book_title": "test",
                                     "release_date": "2015-01-12T11:00",
                                     "price": 100,
                                     "additional": [
                                                   {
                                                   "item1": "test",
                                                   "item2": "test",
                                                   "number": 1
                                                   },
                                                   {
                                                    "item1": "test2",
                                                    "item2": "test2",
                                                    "number": 2
                                                   }
                                                   ],
                                     "availability": "Yes",
                                     "item_id": 43534
                                     }
                                     ]

                    }

                    ]
    }
}
</code>```

What kind of struct do I need to get to value of book_title for example?

答:
i prefer to give a general solution not only for this condition

it is very simple just download and run this MACOS APP from GITHUB
run it in your mac by XCODE and but your JSON in it,

it will make Models for any complex JSON

notes

1 if JSON keys have a capital character in the first it will be small
, so after copying model you need to change it like the JSON

2 if two JSON objects have the same structure and the same key names it will be only one model

Title: SWIFT 4 nested JSON Struct - Codable

Body:
I'm having issues creating a struct to parse JSON in Swift 4. I'm able to parse small JSONs and JSONDecoder seems to work fine. Just need help to create a struct to parse JSON like that:

{
    "main": {
        "solutions": [
                    {
                    "exersises": [
                                     {
                                     "book_title": "test",
                                     "release_date": "2015-01-12T11:00",
                                     "price": 100,
                                     "additional": [
                                                   {
                                                   "item1": "test",
                                                   "item2": "test",
                                                   "number": 1
                                                   },
                                                   {
                                                    "item1": "test2",
                                                    "item2": "test2",
                                                    "number": 2
                                                   }
                                                   ],
                                     "availability": "Yes",
                                     "item_id": 43534
                                     }
                                     ]

                    }

                    ]
    }
}

What kind of struct do I need to get to value of book_title for example?


问:
Solving 3 non linear equations using fsolve
I want to find the valuews of a,b,c. It gives me error:

```<code>from scipy.optimize import fsolve
def equations(p):
    a,b,c = p
    return (a*np.log10([-b])+c, a*np.log10([100-b])+c-100, a*np.log10([80-b])+c-20)

a,b,c =  fsolve(equations, (1, 1, 1))

print(a,b,c)
> print(a,b,c)
</code>```

TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (3,) but it is (3, 1).

答:
You cannot use square brackets [] in your equations. They have special meaning in Python. You should use round brackets for enforcing sequence of mathematical operations. The following code gets rid of the error but you need to work some more on the math because fsolve is not converging to a solution for your system. You are giving initial guess for b as 1 but then you do log10(-b). Logs of negative numbers are not defined.

```<code>import numpy as np
from scipy.optimize import fsolve
def equations(p):
    a,b,c = p
    return ( a*np.log10(-b)+c, a*np.log10(100-b)+c-100,
        a*np.log10(80-b)+c-20 )

a,b,c =  fsolve(equations, ( 1, 1, 1 ))

print(a,b,c)
</code>```

If we write down your system on paper you have the following 3 equations.

Substituting the first equation in the second and third, you are left with

The above two equations cannot be simultaneously true. So your system has no answer.

Body:
I want to find the valuews of a,b,c. It gives me error:

from scipy.optimize import fsolve
def equations(p):
    a,b,c = p
    return (a*np.log10([-b])+c, a*np.log10([100-b])+c-100, a*np.log10([80-b])+c-20)

a,b,c =  fsolve(equations, (1, 1, 1))

print(a,b,c)
> print(a,b,c)

TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (3,) but it is (3, 1).

Body:
You cannot use square brackets [] in your equations. They have special meaning in Python. You should use round brackets for enforcing sequence of mathematical operations. The following code gets rid of the error but you need to work some more on the math because fsolve is not converging to a solution for your system. You are giving initial guess for b as 1 but then you do log10(-b). Logs of negative numbers are not defined.

import numpy as np
from scipy.optimize import fsolve
def equations(p):
    a,b,c = p
    return ( a*np.log10(-b)+c, a*np.log10(100-b)+c-100,
        a*np.log10(80-b)+c-20 )

a,b,c =  fsolve(equations, ( 1, 1, 1 ))

print(a,b,c)

If we write down your system on paper you have the following 3 equations.

Substituting the first equation in the second and third, you are left with

The above two equations cannot be simultaneously true. So your system has no answer.


问:
Bitwise operators won't translate from JavaScript to PHP
I'm trying to translate this segment of code which makes use of bitwise operators in a loop, from JavaScript to PHP.  Here is the JavaScript code:

```<code>for( var k = 0, iTop = str.length; k < iTop; k++ )
{
    crc = (crc >> 8) ^ ("0x" + table.substr(((crc ^ str.charCodeAt(k) ) & 0x000000FF) * 9, 8));
    document.write(crc);
}
</code>```

Here is the same code translated into PHP

```<code>for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
{
    $crc = ($crc >> 8) ^ ("0x" . substr($table, (($crc ^ ord($str[$k]) ) & 0x000000FF) * 9, 8));
    echo $crc;
}
</code>```

These two segments give different values for the crc variable.  All the variables going into both of them are identical.

Am I making a silly error, or will this code not translate because of some difficulty with translating bitwise operators?

Here is the complete code for both:

Javascript:

```<code><html><head><meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="-1"/>
<meta http-equiv="CacheControl" content="no-cache"/>
<script type="text/javascript">function test(){var table = "00000000 77073096 EE0E612C     990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
var c = 1750271245;
var slt = "2qGU4Lt1";
var s1 = 'v';
var s2 = 'z';
var n = 4;
var start = s1.charCodeAt(0);
var end   = s2.charCodeAt(0);
var arr = new Array(n);
var m = Math.pow(((end - start) + 1),n);
for (var i=0; i<n; i++)
    arr[i] = s1;
for (var i=0; i<m-1; i++){
    for(var j=n-1; j>=0;--j) {
        var t = arr[j].charCodeAt(0);
        t++; arr[j] = String.fromCharCode(t);
        if (arr[j].charCodeAt(0)<=end) {
            break;
        } else {
            arr[j] = s1 ;
        }
    }
    var chlg = arr.join(""); var str = chlg + slt;
    var crc = 0;
    var crc = crc ^ (-1);

    for( var k = 0, iTop = str.length; k < iTop; k++ )
    {
        document.write((((crc ^ str.charCodeAt(k) ) & 0x000000FF) * 9) + "\n");
        crc = (crc >> 8) ^ ("0x" + table.substr(((crc ^ str.charCodeAt(k) ) & 0x000000FF) * 9, 8));
    }
    crc =  crc ^ (-1);
    crc = Math.abs(crc);
    if (crc == parseInt(c)){
        break;
    }
}
document.cookie ="TS884e96_75=" + "8643a82fd76d477a904aa3267724056d:" + chlg + ":" + slt + ":" + crc + ";Max-Age=3600;path=/";}</script></head><body onload="test()">
</body></html>
</code>```

PHP

```<code><?php

ini_set("display_errors","1");

$table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";

$c = 1750271245; //we'd get this from reading the script
$slt = "2qGU4Lt1"; //we'd get this from reading the script

$s1 = 'v'; //we'd get this from reading the script
$s2 = 'z'; //we'd get this from reading the script
$n = 4; //we'd get this from reading the script, just to be safe
$start = ord($s1);
$end = ord($s2);
$arr = array();
$m = pow(($end - $start + 1 ), $n);
for ($i=0; $i<$n; $i++)
{
    $arr[$i] = $s1;
}
for ($i=0; $i<$m-1; $i++)
{
    for ($j = $n-1; $j>=0; $j--)
    {
        $t = ord($arr[$j]);
        $t++;
        $arr[$j] = chr($t);
        if (ord($arr[$j]) <= $end)
        {
        break;
        }
        else
        {
        $arr[$j] = $s1;
        }
}
$chlg = implode('', $arr);
$str = $chlg . $slt;
$crc = 0;
$crc = $crc ^ (-1);
//ord($str[$k]) Is correct
//

    for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
    {
        $crc = ($crc >> 8) ^ ("0x" . substr($table, (($crc ^ ord($str[$k]) ) & 0x000000FF) * 9, 8));
    }
    $crc =  $crc ^ (-1);
    $crc = abs($crc);
    if ($crc == intval($c))
    {
        break;
    }
}

echo $chlg;
?>
</code>```

UPDATE:  It's definitely a 32 bit issue.  I know because echo (int) -1 ^ (int) 2489596804; gives -2489596805 instead of 1805370491.  What should I do?

GMP CODE:

```<code>for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
{
    $crc = gmp_xor(
                    (gmp_intval($crc) >> 8),
                    hexdec(substr(
                        $table,
                        gmp_intval(gmp_mul(
                            gmp_and(gmp_xor($crc, ord($str[$k])), 0x000000FF),
                            9)),
                        8))
                ); //we use gmp because we're on 32 bit and bitwise operator cant work for that.
    echo gmp_strval($crc) . "\n";
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to translate this segment of code which makes use of bitwise operators in a loop, from JavaScript to PHP.  Here is the JavaScript code:

for( var k = 0, iTop = str.length; k < iTop; k++ )
{
    crc = (crc >> 8) ^ ("0x" + table.substr(((crc ^ str.charCodeAt(k) ) & 0x000000FF) * 9, 8));
    document.write(crc);
}

Here is the same code translated into PHP

for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
{
    $crc = ($crc >> 8) ^ ("0x" . substr($table, (($crc ^ ord($str[$k]) ) & 0x000000FF) * 9, 8));
    echo $crc;
}

These two segments give different values for the crc variable.  All the variables going into both of them are identical.

Am I making a silly error, or will this code not translate because of some difficulty with translating bitwise operators?

Here is the complete code for both:

Javascript:

<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="-1"/>
<meta http-equiv="CacheControl" content="no-cache"/>

PHP

<?php

ini_set("display_errors","1");

$table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";

$c = 1750271245; //we'd get this from reading the script
$slt = "2qGU4Lt1"; //we'd get this from reading the script

$s1 = 'v'; //we'd get this from reading the script
$s2 = 'z'; //we'd get this from reading the script
$n = 4; //we'd get this from reading the script, just to be safe
$start = ord($s1);
$end = ord($s2);
$arr = array();
$m = pow(($end - $start + 1 ), $n);
for ($i=0; $i<$n; $i++)
{
    $arr[$i] = $s1;
}
for ($i=0; $i<$m-1; $i++)
{
    for ($j = $n-1; $j>=0; $j--)
    {
        $t = ord($arr[$j]);
        $t++;
        $arr[$j] = chr($t);
        if (ord($arr[$j]) <= $end)
        {
        break;
        }
        else
        {
        $arr[$j] = $s1;
        }
}
$chlg = implode('', $arr);
$str = $chlg . $slt;
$crc = 0;
$crc = $crc ^ (-1);
//ord($str[$k]) Is correct
//

    for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
    {
        $crc = ($crc >> 8) ^ ("0x" . substr($table, (($crc ^ ord($str[$k]) ) & 0x000000FF) * 9, 8));
    }
    $crc =  $crc ^ (-1);
    $crc = abs($crc);
    if ($crc == intval($c))
    {
        break;
    }
}

echo $chlg;
?>

UPDATE:  It's definitely a 32 bit issue.  I know because echo (int) -1 ^ (int) 2489596804; gives -2489596805 instead of 1805370491.  What should I do?

GMP CODE:

for($k = 0, $iTop = strlen($str); $k < $iTop; $k++ )
{
    $crc = gmp_xor(
                    (gmp_intval($crc) >> 8),
                    hexdec(substr(
                        $table,
                        gmp_intval(gmp_mul(
                            gmp_and(gmp_xor($crc, ord($str[$k])), 0x000000FF),
                            9)),
                        8))
                ); //we use gmp because we're on 32 bit and bitwise operator cant work for that.
    echo gmp_strval($crc) . "\n";
}

Body:
If the raw PHP hex notation works, then try using this converted list:

$table = array(
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
);

This simplifies the code to:

$crc = ($crc >> 8) ^ $table[($crc ^ ord($str[$k])) & 0x000000FF];

Again I'm not sure it works with PHP on a 32 bit machine.


问:
Python getting Data from Coinmarketcap Website API
I would like to only get the "price_usd" value of e.g. Bitcoin from https://coinmarketcap.com/api/
I've tried this code below, but I can't figure out how to only get this one value.. I am using Python 3.5.3. I'd be glad for every help!</p>

```<code>import json
import requests

r = requests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
for coin in r.json():
    print(coin)
</code>```

答:
Try this:

```<code>import json
import requests

r = requests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
for coin in r.json():
    print(coin["price_usd"])
</code>```

You can also use the get method to lookup values from a dictionary. It allows you to provide a default value if the key is missing:

```<code>for coin in r.json():
    print(coin.get("price_usd", "U$S Price not provided"))
</code>```

Body:
I would like to only get the "price_usd" value of e.g. Bitcoin from https://coinmarketcap.com/api/
I've tried this code below, but I can't figure out how to only get this one value.. I am using Python 3.5.3. I'd be glad for every help!

import json
import requests

r = requests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
for coin in r.json():
    print(coin)

Body:
Try this:

import json
import requests

r = requests.get('https://api.coinmarketcap.com/v1/ticker/bitcoin/')
for coin in r.json():
    print(coin["price_usd"])

You can also use the get method to lookup values from a dictionary. It allows you to provide a default value if the key is missing:

for coin in r.json():
    print(coin.get("price_usd", "U$S Price not provided"))


答: At your signinUser: (obj, args) => {} you will have the same context, see =>, search for arrow function

Title: Correct syntax for a async/await function?


问:
How to serve an angular2 app in a node.js server
I'm building a web app using Angular2, to create the project I'm using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to that, I need to create a REST API running on node.js

How can I serve both of Angular2 app and REST API using node.js server

答:
Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.

Here's the summary from beginning:

npm install -g @angular/cli

ng new PROJECT_NAME

cd PROJECT_NAME

npm install nodemon express cookie-parser body-parser morgan method-override --save

5.Create app.js:

```<code>var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();

console.log('——————————- Run on port '+ port);

/****************************** Router ***************************/
router.get('*', function(req, res){
    res.sendFile('index.html', { root: __dirname + '/' });
});

/****************************** /Router ***************************/

//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder

app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*

app.listen(port);
</code>```

Edit package.json file:

```<code>{
   ...
    "scripts": {
        "start": "ng build; cp app.js dist/app.js; node dist/app.js",
    }
   ...
}
</code>```

Run npm start

This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.

Body:
Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.

Here's the summary from beginning:

npm install -g @angular/cli

ng new PROJECT_NAME

cd PROJECT_NAME

npm install nodemon express cookie-parser body-parser morgan method-override --save

5.Create app.js:

var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();

console.log('——————————- Run on port '+ port);

/****************************** Router ***************************/
router.get('*', function(req, res){
    res.sendFile('index.html', { root: __dirname + '/' });
});

/****************************** /Router ***************************/

//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder

app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*

app.listen(port);

Edit package.json file:

{
   ...
    "scripts": {
        "start": "ng build; cp app.js dist/app.js; node dist/app.js",
    }
   ...
}

Run npm start

This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.


问:
Replace misspelled words from dictionary
I am trying to finish this algorithm that is supposed to replace a misspelled word in a txt file with a replacement word. As you can see the algorithm is described by the comments above and I have the first two parts done but am stuck on the for each line number where it appears:  part. I am having issues trying to figure out how to set up the loop. If anyone could help me towards the direction of finishing this method I would greatly appreciate it!

```<code>private void replace(String misspelled, String replacement){
    //TODO: Algorithm:
    //If wrongWords contains the misspelled word:
    //   get ALL the lineNumbers on where the misspelled word appears
    //   for each line number where it appears:
    //        in fileLines[line] replace misspelled with replacement
    //        (Hint: use one of the available methods in the String class to do the replacement)
    if(wrongWords.containsKey(misspelled))
       wrongWords.get(misspelled);

}
</code>```

Other notable code that you may find useful includes:

```<code>private void correctionMode(){
  for(String line: fileLine)
    for(String w: line.split("//s"))
       if(wrongWords.containsKey(w)){
           System.out.println(wrongWords.get(w));
           System.out.println("replace all? (y or n): ");
           String r = scan.nextLine();
           if(r.equals("y")){
               System.out.println("Enter replacement: ");
               String r2 = scan.nextLine();
               replace(w, r2);
           }
           wrongWords.remove(w);
       }
}
</code>```

This methods asks the user for corrections and then goes to the replacement method, the one i am having issues with, if the user wants to make a change.

```<code>private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;

\\constructor
public SpellChecker(){
  scan = new Scanner(System.in);
  dictionary = new HashSet<String>();
  wrongWords = new HashMap<String, ArrayList<Integer>>(); //array is line numbers where misspelled word appears
  fileLine = new ArrayList<String>(); //each line is as separate element in the arraylist
}
</code>```

The class variables and constructor may also be helpful.

答:
You don't need to put for loop in both the methods for every line.

```<code> //   for each line number where it appears:
</code>```

and

```<code>for(String line: fileLine)
</code>```

Put it in either one of it:

```<code>private void replace(String misspelled, String replacement){
         int i = 0;
         for(String line: fileLine) {
            if(line.contains(misspelled)) {
                line.replaceAll(misspelled, replacement);
                System.out.println("replaced word" + misspelled  + "in line number" + i );
                i++;
            }else i++;
         }
    }
</code>```

Body:
I am trying to finish this algorithm that is supposed to replace a misspelled word in a txt file with a replacement word. As you can see the algorithm is described by the comments above and I have the first two parts done but am stuck on the for each line number where it appears:  part. I am having issues trying to figure out how to set up the loop. If anyone could help me towards the direction of finishing this method I would greatly appreciate it!

private void replace(String misspelled, String replacement){
    //TODO: Algorithm:
    //If wrongWords contains the misspelled word:
    //   get ALL the lineNumbers on where the misspelled word appears
    //   for each line number where it appears:
    //        in fileLines[line] replace misspelled with replacement
    //        (Hint: use one of the available methods in the String class to do the replacement)
    if(wrongWords.containsKey(misspelled))
       wrongWords.get(misspelled);

}

Other notable code that you may find useful includes:

private void correctionMode(){
  for(String line: fileLine)
    for(String w: line.split("//s"))
       if(wrongWords.containsKey(w)){
           System.out.println(wrongWords.get(w));
           System.out.println("replace all? (y or n): ");
           String r = scan.nextLine();
           if(r.equals("y")){
               System.out.println("Enter replacement: ");
               String r2 = scan.nextLine();
               replace(w, r2);
           }
           wrongWords.remove(w);
       }
}

This methods asks the user for corrections and then goes to the replacement method, the one i am having issues with, if the user wants to make a change.

private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;

\\constructor
public SpellChecker(){
  scan = new Scanner(System.in);
  dictionary = new HashSet<String>();
  wrongWords = new HashMap<String, ArrayList<Integer>>(); //array is line numbers where misspelled word appears
  fileLine = new ArrayList<String>(); //each line is as separate element in the arraylist
}

The class variables and constructor may also be helpful.

Body:
You don't need to put for loop in both the methods for every line.

 //   for each line number where it appears:

and

for(String line: fileLine)

Put it in either one of it:

private void replace(String misspelled, String replacement){
         int i = 0;
         for(String line: fileLine) {
            if(line.contains(misspelled)) {
                line.replaceAll(misspelled, replacement);
                System.out.println("replaced word" + misspelled  + "in line number" + i );
                i++;
            }else i++;
         }
    }


问:
tensorflow: how create an const tensor the same shape as a placeholder
I have a place holder for input:

```<code>Y = tf.placeholder(dtype=tf.float32, shape=(None, n_outputs))
</code>```

Now I want to create a constant the same shape the Y:

```<code>w = Y.get_shape()
zero = tf.constant(np.zeros(w), dtype=tf.float32)
</code>```

Error return:

```<code>__index__ returned non-int (type NoneType)
</code>```

答:
Found the answer in another post
tensorflow-constant-with-variable-size</p>

```<code>zero = tf.fill(tf.shape(Y), 0.0)
</code>```

Body:
I have a place holder for input:

Y = tf.placeholder(dtype=tf.float32, shape=(None, n_outputs))

Now I want to create a constant the same shape the Y:

w = Y.get_shape()
zero = tf.constant(np.zeros(w), dtype=tf.float32)

Error return:

__index__ returned non-int (type NoneType)

Body:
Found the answer in another post
tensorflow-constant-with-variable-size

zero = tf.fill(tf.shape(Y), 0.0)


问:
how to save bitmap to android gallery
unfortunately the solutions I've found didn't work on android 5.1.1.
I have a bitmap called source. I need to save it directly to my phone's gallery. My manifest contains  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Can you give me a working method to do this?

答:
Do it in One Line
MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(), IMAGE ,"nameofimage" , "description");

Title: how to save bitmap to android gallery


问:
jquery return value of input to var
I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.

```<code>$('#max_char').keyup(function () {
    var max_char = $(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

var count_options = {
    'maxCharacterSize': max_char,
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

$('#textinput').textareaCount(count_options);
});
</code>```

HTML

```<code><textarea cols="68" rows="21" name="textinput" id="textinput"></textarea><br/>
    <input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters <br/>
</code>```

Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options

Title: jquery return value of input to var

Body:
I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.

$('#max_char').keyup(function () {
    var max_char = $(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

var count_options = {
    'maxCharacterSize': max_char,
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

$('#textinput').textareaCount(count_options);
});

HTML

<textarea cols="68" rows="21" name="textinput" id="textinput"></textarea>

    <input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters

Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options


问:
pari gp return function store in variable
I'm new to pari gp, and just trying out, playing with it.
i have an inverse function that goes like this.

```<code>inverse (a,n) =
{
  negative = false;

  if (a < 0, negative = true);
  if (a < 0, a= a*-1);

  i = n;
  v = 0;
  d = 1;

  while (a>0,t=i/a; x =a;
        a = i % x;
        i = x;
        x = d;
        d = v - t*x;
        v = x);
    v %= n;

  if (v < 0, v = (v+n)%n);

  if (negative == true, return (-v));

  return (v);
};
</code>```

so i have sort of a main function, which consist of something like this.

```<code>while (i<n,i++;
    while(j<n,j++;
      // some other codes
      temp1 = inverse(temp,modulus)));
</code>```

I got an error that says incorrect type in &[] 0Ccompo1ptr [not a vector] (t_INT)
i am quite sure that the rest of the code is work fine, since the error only occurred when i place

```<code>temp1 = inverse (temp,modulus)
</code>```

in.

答: Part of the problem here is that you are not scoping variables in the function. In particular you are using i both inside the function and out. None of this is explained well in the PARI user manual. To make a variable local you need to do something like my(i=n); Some variables are automatically scoped such as arguments to functions and sum(i=1,10,i); vector(10,i,i^2); for(i=1,10,...) etc, but not simple assignments like i=n. Also note PARI does not have boolean constants true and false. Your code works in this case because you are doing negative==true which is just comparing polynomials with the indeterminants of true of and false.

Body:
I'm new to pari gp, and just trying out, playing with it.
i have an inverse function that goes like this.

inverse (a,n) =
{
  negative = false;

  if (a < 0, negative = true);
  if (a < 0, a= a*-1);

  i = n;
  v = 0;
  d = 1;

  while (a>0,t=i/a; x =a;
        a = i % x;
        i = x;
        x = d;
        d = v - t*x;
        v = x);
    v %= n;

  if (v < 0, v = (v+n)%n);

  if (negative == true, return (-v));

  return (v);
};

so i have sort of a main function, which consist of something like this.

while (i<n,i++;
    while(j<n,j++;
      // some other codes
      temp1 = inverse(temp,modulus)));

I got an error that says incorrect type in &[] 0Ccompo1ptr [not a vector] (t_INT)
i am quite sure that the rest of the code is work fine, since the error only occurred when i place

temp1 = inverse (temp,modulus)

in.


问:
sequelize foreign key target vs source
I have been using sequelize for a little bit, but never bother to really understand how foreignKey actually works. In their doc they state:

The target key is the column on the target model that the foreign key column on the source model points to.

So in the following cases, which is the target?

```<code>    Route.belongsTo(models.Subarea, {
      foreignKey: 'subareaId',
      as: 'subarea',
    });

    Route.belongsToMany(models.Book, {
      through: models.BookRoute,
      foreignKey: 'routeId',
      as: 'books',
    });
</code>```

My confusion is on why in first case I put foreignKey on SubareaId, but for second case I put it as routeId. Should it not be routeId for both cases, if foreignKey should be the sourceId?

答:
I suggest reasoning in following steps:

Determine source and target model. This is just convention: the source is the model on which the method is invoked, so basically 'the one on the left' in the notation. The target is the other model, so 'the one on the right'.

Know where various methods put the foreign key: hasOne and hasMany put fk on target; belongsTo puts fk on source; belongsToMany puts fk on the through model.

Understand that the foreign key (as the name implies) will refer to 'the other model' (so not the one under 2). So for hasOne and hasMany will be a reference to the source model; for belongsTo a reference to the target model; for belongsToMany a reference to the source model (and you can reference the target model with otherKey:).

belongsToMany is a special case since a third model is introduced: the through model (or join table) on which both the foreign keys to the source and the target are stored. This changes 'the perspective' for the foreign key somewhat and therefor you can not compare it fully with belongsTo in respect of foreign key referencing.

So answering your questions:

Which is the target?: Subarea, and Book respectively.

Which foreign key to use?: your foreign keys are in line with above
explanation. belongsToMany is exceptional as foreign keys
are stored on neither source nor target, but on the through model.

Title: sequelize foreign key target vs source

Body:
I have been using sequelize for a little bit, but never bother to really understand how foreignKey actually works. In their doc they state:

The target key is the column on the target model that the foreign key column on the source model points to.

So in the following cases, which is the target?

    Route.belongsTo(models.Subarea, {
      foreignKey: 'subareaId',
      as: 'subarea',
    });

    Route.belongsToMany(models.Book, {
      through: models.BookRoute,
      foreignKey: 'routeId',
      as: 'books',
    });

My confusion is on why in first case I put foreignKey on SubareaId, but for second case I put it as routeId. Should it not be routeId for both cases, if foreignKey should be the sourceId?


问:
Compare/Diff Multiple (>Millions) Arrays
I'm not sure if this is possible; but I have millions of "lists" in a MySQL database, and would like develop a system where I take one of the lists; and compare it against all of the other lists in the database and return:

1.) Lists that closely resemble the primary list (some sort of % would be great)

2.) Given a certain items in a list; it would return a list of of items that are included in the majority of all the other lists (ie. autocomplete a list based on popular options).

I would've intially thought this would've been possible if I could create some sort of 'loose hash' that I can compare lists mathematically, but I haven't been able to find a solution that scales (since this is exponential when tackled head-on).

Any new ideas/solutions would be greatly appreciated. Thanks!

答:
If you're saying there are millions of lists, itnis really not an option to load them all into a php script.
You could get the values of the list you are comparing the others to, and then run an SQL query similar to this:

```<code>SELECT list_id, COUNT(value) as c FROM lists WHERE value IN (a,b,c) GROUP BY list_id
ORDER BY c DESC
</code>```

I'm not sure the sql is correct, but the idea is to select the ids of the lists that have the same members in them and then sort the output by the number of list items that intersect with the original list. The percenage of item correspondence is easily obtained in this case.

Body:
If you're saying there are millions of lists, itnis really not an option to load them all into a php script.
You could get the values of the list you are comparing the others to, and then run an SQL query similar to this:

SELECT list_id, COUNT(value) as c FROM lists WHERE value IN (a,b,c) GROUP BY list_id
ORDER BY c DESC

I'm not sure the sql is correct, but the idea is to select the ids of the lists that have the same members in them and then sort the output by the number of list items that intersect with the original list. The percenage of item correspondence is easily obtained in this case.


问:
Command to get list of files that are edited but not "opened" in perforce
Is there a command in Perforce to get a list of files that have been edited?
It seems the only way to do that is to open them using "p4 open " and do a "p4 diff".
I come from git where the easiest way to do that would be "git status".
Sometimes I don't want to "open" files but I still want to edit them.

Thanks.

答:
```<code>p4 reconcile
</code>```

...will do that for you.

or, duh,

```<code>p4 status
</code>```

...will do the same, but give you more clear info.

Body:
p4 reconcile

...will do that for you.

or, duh,

p4 status

...will do the same, but give you more clear info.


问:
installing OpenCV on mac osx 10.10.5
I would like to use OpenCV on python and I am using the command lines on the terminal:

To get homebrew ...

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

I believe this works ok.

Then I try to install the dependency gtk+
brew install gtk+

This seems to be ok.

The problem occurs when I install opencv
brew install opencv

I get the return error.... and I just noticed that it is for python2 ... (that could be the issue), but if it is not it seems to be that I have an old mac OS ... is there a way around this?

```<code>1 error generated.
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

Do not report this issue to Homebrew/brew or Homebrew/core!

Error: You are using macOS 10.10.
We (and Apple) do not provide support for this old version.
You may encounter build failures or other breakages.
Please create pull-requests instead of filing issues.
</code>```

答:
According the the Apple website you can upgrade for FREE! Upgrading you macOS version should help with this problem.

https://www.apple.com/macos/how-to-upgrade/

Title: installing OpenCV on mac osx 10.10.5

Body:
I would like to use OpenCV on python and I am using the command lines on the terminal:

To get homebrew ...

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I believe this works ok.

Then I try to install the dependency gtk+
brew install gtk+

This seems to be ok.

The problem occurs when I install opencv
brew install opencv

I get the return error.... and I just noticed that it is for python2 ... (that could be the issue), but if it is not it seems to be that I have an old mac OS ... is there a way around this?

1 error generated.
make[2]: *** [modules/python2/CMakeFiles/opencv_python2.dir/__/src2/cv2.cpp.o] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

Do not report this issue to Homebrew/brew or Homebrew/core!

Error: You are using macOS 10.10.
We (and Apple) do not provide support for this old version.
You may encounter build failures or other breakages.
Please create pull-requests instead of filing issues.


问:
two styles change within one if condition in javascript
I am new to web design . I am trying to achieve this code but only one style works Please help me correct this code. How am I supposed to achieve these two styles?</p>

```<code>// Get the sign_up model winow
var modal = document.getElementById('id01');

// Get the contents from the container
var content = document.getElementById('container');

// When the user clicks anywhere outside of the modal, close the model and set the container contents blur to "0"
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
        content.style.filter = "blur(0)";
    }
}
</code>```

答:
Your solution 100% works. I believe, your only problem is, that blur(0) actually removes your blur (is this what you really want to achieve?).

I tried it and it works ... look also into DOM on console. You will see, that the style is applied propertly.

In my fiddle, I added positive value to blur() to actually see the effect

https://jsfiddle.net/9tqfcyf6/

Body:
I am new to web design . I am trying to achieve this code but only one style works Please help me correct this code. How am I supposed to achieve these two styles?

// Get the sign_up model winow
var modal = document.getElementById('id01');

// Get the contents from the container
var content = document.getElementById('container');

// When the user clicks anywhere outside of the modal, close the model and set the container contents blur to "0"
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
        content.style.filter = "blur(0)";
    }
}


问:
HashSet.contains is returning false while it should not
I'm trying to learn Java, and I reached the HashSet part, Long story short I'm testing the contain method.

```<code>public static void main(String[] args) {
    HashSet<Integer> firstSet = new HashSet<>();
    firstSet.add(3);

    HashSet<Integer> secondSet = new HashSet<>();
    secondSet.add(3);

    boolean var = firstSet.contains(secondSet);

    System.out.println(var);

}
</code>```

I believe this piece of  code should return true, while it is returning false. Any help!

答:
```<code>boolean var = firstSet.contains(secondSet);
</code>```

This line is causing the problem, because you don't check presence of specific element from secondSet, you check if your firstSet stores entire secondSet in itself, which is obviously false.

You should have checked, for example, if it . contains(secondSet.get(0)) or .contains(3).

If your intention was to check if firstSet contains all elements that are present in the secondSet, you could use firstSet.containsAll(secondSet).

Body:
I'm trying to learn Java, and I reached the HashSet part, Long story short I'm testing the contain method.

public static void main(String[] args) {
    HashSet<Integer> firstSet = new HashSet<>();
    firstSet.add(3);

    HashSet<Integer> secondSet = new HashSet<>();
    secondSet.add(3);

    boolean var = firstSet.contains(secondSet);

    System.out.println(var);

}

I believe this piece of  code should return true, while it is returning false. Any help!

Body:
boolean var = firstSet.contains(secondSet);

This line is causing the problem, because you don't check presence of specific element from secondSet, you check if your firstSet stores entire secondSet in itself, which is obviously false.

You should have checked, for example, if it . contains(secondSet.get(0)) or .contains(3).

If your intention was to check if firstSet contains all elements that are present in the secondSet, you could use firstSet.containsAll(secondSet).


问:
Celery worker not reconnecting on network change/IP Change
I deployed celery for some tasks that need to be performed at my workplace. These tasks are huge and I bought a few high-spec machines for performing these. Before I detail my issue, let me brief about what all I've deployed:

RabbitMQ broker on a remote server

Producer that pushes tasks on another remote server

Workers at 3 machines deployed at my workplace

Now, when I started the whole process was as smooth as I tested and everything process just great!

The problem

Unfortunately, I forgot to consult my network guy about a fixed IP address, and as per our location, we do not have a fixed IP address from our ISP. So my celery workers upon network disconnect freeze and do nothing. Even when the network is running, because the IP Address changed, and the connection to the broker is not being recreated or worker is not retrying connection. I have tried configuration like BROKER_CONNECTION_MAX_RETRIES = 0 and BROKER_HEARTBEAT = 10. But I had no option but to post it out here and look for experts on this matter!

PS: I cannot restart the workers manually everytime the network changes the IP address by kill -9

答:
Restarting the app using:

```<code>sudo rabbitmqctl stop_app
sudo rabbitmqctl start_app
</code>```

solved the issue for me.
Also, since I had virtual host setup, I needed to get that reset too.
Not sure why was that needed. Or in fact any of the above was needed, but it did solve the problem for me.

Body:
Restarting the app using:

sudo rabbitmqctl stop_app
sudo rabbitmqctl start_app

solved the issue for me.
Also, since I had virtual host setup, I needed to get that reset too.
Not sure why was that needed. Or in fact any of the above was needed, but it did solve the problem for me.


问:
Shade distance away from a road network that is within a slope threshold
I started a project that is trying to find how far I can drive off a road assuming I am limited by roads, slope, and vegetation. I tried approaching the problem sequentially, but I am running into more problems than I can solve so I'll add everything in this post.

My vehicle can't drive at a more than a 5 degree slope, so my first attempt was to find all the terrain that is <= 5 degrees.

Thanks to @Christopher-Stephan, I have the following picture.

I cannot seem to find prior work or a post that addresses what I am trying to do so I'll describe it.

Given an area when I am on a road in a car, in this case Palawan, I'm trying to see how far I can drive off-road before the slope is steeper than 5 degrees (very important) or I run into a jungle (less important).

I am thinking now that I have the slope within 5 degrees, I plot the roads and somehow shade an adjacent box that is less than 5 degrees. Once the slope is more than 5, shade it a different color. (the output being this graphic).

Then I would just need to find the proportion of the area that is within each shaded region (assuming you find p, the other is 1-p).

The code for the picture is below

```<code>library(raster)
library(rasterVis)
elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)
levelplot(rc, margin = F,  col.regions = c("wheat", "gray"),  colorkey = list(at = c(0, 1, 2), labels = list(at = c(0.5, 1.5), labels = c("<= 5", "> 5"))))
</code>```

Thanks

答:
You can get the road network as a shapefile from http://philgis.org/country-basemaps/roads and add it to the levelplot. From there I do not understand exactly what your expected result would be.

```<code>library(raster)
library(rasterVis)
library(rgdal)

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
plot(gewataSub$slope, 1)

m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)

roads = readOGR("/Users/christopherstephan/Downloads", layer = "roads")

levelplot(
  rc,
  margin = F,
  col.regions = c("wheat", "gray"),
  colorkey = list(at = c(0, 1, 2), labels = list(
    at = c(0.5, 1.5), labels = c("<= 5", "> 5")
  ))
) + layer(sp.polygons(roads))
</code>```

Body:
I started a project that is trying to find how far I can drive off a road assuming I am limited by roads, slope, and vegetation. I tried approaching the problem sequentially, but I am running into more problems than I can solve so I'll add everything in this post.

My vehicle can't drive at a more than a 5 degree slope, so my first attempt was to find all the terrain that is <= 5 degrees.

Thanks to @Christopher-Stephan, I have the following picture.

I cannot seem to find prior work or a post that addresses what I am trying to do so I'll describe it.

Given an area when I am on a road in a car, in this case Palawan, I'm trying to see how far I can drive off-road before the slope is steeper than 5 degrees (very important) or I run into a jungle (less important).

I am thinking now that I have the slope within 5 degrees, I plot the roads and somehow shade an adjacent box that is less than 5 degrees. Once the slope is more than 5, shade it a different color. (the output being this graphic).

Then I would just need to find the proportion of the area that is within each shaded region (assuming you find p, the other is 1-p).

The code for the picture is below

library(raster)
library(rasterVis)
elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)
levelplot(rc, margin = F,  col.regions = c("wheat", "gray"),  colorkey = list(at = c(0, 1, 2), labels = list(at = c(0.5, 1.5), labels = c("<= 5", "> 5"))))

Thanks

Body:
You can get the road network as a shapefile from http://philgis.org/country-basemaps/roads and add it to the levelplot. From there I do not understand exactly what your expected result would be.

library(raster)
library(rasterVis)
library(rgdal)

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
plot(gewataSub$slope, 1)

m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)

roads = readOGR("/Users/christopherstephan/Downloads", layer = "roads")

levelplot(
  rc,
  margin = F,
  col.regions = c("wheat", "gray"),
  colorkey = list(at = c(0, 1, 2), labels = list(
    at = c(0.5, 1.5), labels = c("<= 5", "> 5")
  ))
) + layer(sp.polygons(roads))


答:
All you need to do is declare max_char in a higher scope, i.e. outside of the keyup function:

```<code>var max_char;

$('#max_char').keyup(function () {
    max_char = +$(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});
</code>```

Also note that I put a + in front of $(this).val() to convert it from a string into a number, since "1" + 1 == "11".

Update:

The reason the textareaCount plugin isn't working is because it is initialised once, on document ready. At this time, max_char is nothing because the user hasn't typed anything yet.

You'd have to either reconfigure or re-initialise the plugin on every keyup to get the effect you're after. Unfortunately the plugin doesn't document an easy way to do this. After digging through the plugin's source code, I think there are only 3 events it binds that you need to revert, before you can simply re-initialize it again. Try this out:

```<code>var count_options = {
    'maxCharacterSize': 100, // Just some default value
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

// Initialise the plugin on document ready
$('#textinput').textareaCount(count_options);

$('#max_char').keyup(function () {
    var max_char = +$(this).val();
    count_options.maxCharacterSize = max_char;

    // Unbind the 3 events the plugin uses before initialising it
    $('#textinput')
        .next('.charleft').remove().end()
        .unbind('keyup').unbind('mouseover').unbind('paste')
        .textareaCount(count_options);
});
</code>```

Title: jquery return value of input to var

Body:
All you need to do is declare max_char in a higher scope, i.e. outside of the keyup function:

var max_char;

$('#max_char').keyup(function () {
    max_char = +$(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

Also note that I put a + in front of $(this).val() to convert it from a string into a number, since "1" + 1 == "11".

Update:

The reason the textareaCount plugin isn't working is because it is initialised once, on document ready. At this time, max_char is nothing because the user hasn't typed anything yet.

You'd have to either reconfigure or re-initialise the plugin on every keyup to get the effect you're after. Unfortunately the plugin doesn't document an easy way to do this. After digging through the plugin's source code, I think there are only 3 events it binds that you need to revert, before you can simply re-initialize it again. Try this out:

var count_options = {
    'maxCharacterSize': 100, // Just some default value
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

// Initialise the plugin on document ready
$('#textinput').textareaCount(count_options);

$('#max_char').keyup(function () {
    var max_char = +$(this).val();
    count_options.maxCharacterSize = max_char;

    // Unbind the 3 events the plugin uses before initialising it
    $('#textinput')
        .next('.charleft').remove().end()
        .unbind('keyup').unbind('mouseover').unbind('paste')
        .textareaCount(count_options);
});


问:
How to read properties file in Unix script where key is in another user input variable
I have below property file in same directory.

cancellation.properties

Content:

```<code>TestData=My Name
</code>```

My unix script is abc.sh

Content:

```<code>#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data
</code>```

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

答:
```<code>#!/bin/bash

. <(awk -F '=' '{print $1 "=\""$2"\""}' file)

echo  "Please enter data to read"
read data
echo "${!data}"
</code>```

Output:

```
My Name
```

Body:
I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

Body:
#!/bin/bash

. <(awk -F '=' '{print $1 "=\""$2"\""}' file)

echo  "Please enter data to read"
read data
echo "${!data}"

Output:

My Name


问:
MIPS Snippets to determine clear, set and value of bit k
```<code>  A:ori $t1, $zero, 1
    sra $t1, k
    andi $t0, $t0, $t1

  B:ori $t1, $zero, 1
    srl $t0, k
    and $t0, $t0, $t1

  C:ori $t1, $zero, 1
    sll $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

  D:ori $t1, $zero, 1
    srl $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

  E:ori $t1, $zero, 1
    sll $t1, k
    ori $t0, $t0, $t1
</code>```

What code is for clearing bit k in t0?

Which code is for setting bit k in t0?

Which code is for the value of bit k in t0?

From what I was able to do i got:
1: C
2: D
3: B

Choices A and E are ommited as andi does not add by an immediate and ori has the same issue. Are my answers correct? Either way can you give me a explanation of how each snippets works as I am having confusion with assembly.

Thanks in advance,

答:
```<code> A:ori $t1, $zero, 1
    sra $t1, k
    andi $t0, $t0, $t1
</code>```

A in C would be equivalent to:

```<code>int tmp1 = 0x00000000 | 0x00000001; // tmp1 = 1;
tmp1 >>= k;
tmp2 &= k;
</code>```

Assuming k is >= 1, any right shift is going to make tmp1 into just all zeros.  If you & with all zeros you get back all zeros, so this basically just clears the value of tmp2, setting it to 0.

```<code>  B:ori $t1, $zero, 1
    srl $t0, k
    and $t0, $t0, $t1
</code>```

Again we set tmp1 equal to 0x00000001.  Then this time we shift it right logically by k digits.  The MSB is 0 so this is actually just equivalent to sra (shift right arithmetic) in this case.  Finally, we and tmp0 with tmp1, which is all zeros, so again all we did was clear the value (so now $t0, or as I call it tmp0, is just 0x00000000).

```<code>  C:ori $t1, $zero, 1
    sll $t1, k
    not $t1, $t1
    and $t0, $t0, $t1
</code>```

Same start as before, tmp1 is set by the ori to 0x00000001.
This time we shift left logically by k, so we get a number of the form [32 - k many 0s][1 in kth bit][k - 1 many 0s] in binary.  Then we not it, which gives us the inverse ([32 - k many 1s ][0][k - 1 many 1s] in binary).  Then we and that with $t0, clearing k'th bit of t0.

```<code>  D:ori $t1, $zero, 1
    srl $t1, k
    not $t1, $t1
    and $t0, $t0, $t1
</code>```

Ok, same as before, tmp1 is just the number 1 (0x00000001).  Then we shift right logically, which so long as k is ≥ 1 means we get tmp1 to be just zeros.  We not it with itself, so it's all 1s (assuming k was ≥ 1) (0xffffffff).  Then we and it with tmp0.  Anding something with a bunch of ones won't change it's value, so the value we get back from the ori is the value of tmp1.  We store that in $t0, so I guess this is just a convoluted way of not changing the value of $t0.

```<code>  E:ori $t1, $zero, 1
    sll $t1, k
    ori $t0, $t0, $t1
</code>```

Here tmp1 is as before set to 1.  sll will make us with a 1 in the k'th bit in LSB order, so if we or that mask with tmp0 we should get tmp0 with a 1 in that bit (regardless of weather there was or was not a 1 in that bit in tmp0 in the first place).  So this effectively sets the kth LSB to 1 in tmp0.

I may have made a mistake somewhere in there; if so feel free to comment or write your own answer accordingly.  I'm deliberately laying out the logic of the code without answering the explicit question because it sounds like a homework question, so I'd like to help you understand the problem without necessarily giving away the solution.  Hope this helps.

Body:
  A:ori $t1, $zero, 1
    sra $t1, k
    andi $t0, $t0, $t1

  B:ori $t1, $zero, 1
    srl $t0, k
    and $t0, $t0, $t1

  C:ori $t1, $zero, 1
    sll $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

  D:ori $t1, $zero, 1
    srl $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

  E:ori $t1, $zero, 1
    sll $t1, k
    ori $t0, $t0, $t1

What code is for clearing bit k in t0?

Which code is for setting bit k in t0?

Which code is for the value of bit k in t0?

From what I was able to do i got:
1: C
2: D
3: B

Choices A and E are ommited as andi does not add by an immediate and ori has the same issue. Are my answers correct? Either way can you give me a explanation of how each snippets works as I am having confusion with assembly.

Thanks in advance,

Body:
 A:ori $t1, $zero, 1
    sra $t1, k
    andi $t0, $t0, $t1

A in C would be equivalent to:

int tmp1 = 0x00000000 | 0x00000001; // tmp1 = 1;
tmp1 >>= k;
tmp2 &= k;

Assuming k is >= 1, any right shift is going to make tmp1 into just all zeros.  If you & with all zeros you get back all zeros, so this basically just clears the value of tmp2, setting it to 0.

  B:ori $t1, $zero, 1
    srl $t0, k
    and $t0, $t0, $t1

Again we set tmp1 equal to 0x00000001.  Then this time we shift it right logically by k digits.  The MSB is 0 so this is actually just equivalent to sra (shift right arithmetic) in this case.  Finally, we and tmp0 with tmp1, which is all zeros, so again all we did was clear the value (so now $t0, or as I call it tmp0, is just 0x00000000).

  C:ori $t1, $zero, 1
    sll $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

Same start as before, tmp1 is set by the ori to 0x00000001.
This time we shift left logically by k, so we get a number of the form [32 - k many 0s][1 in kth bit][k - 1 many 0s] in binary.  Then we not it, which gives us the inverse ([32 - k many 1s ][0][k - 1 many 1s] in binary).  Then we and that with $t0, clearing k'th bit of t0.

  D:ori $t1, $zero, 1
    srl $t1, k
    not $t1, $t1
    and $t0, $t0, $t1

Ok, same as before, tmp1 is just the number 1 (0x00000001).  Then we shift right logically, which so long as k is ≥ 1 means we get tmp1 to be just zeros.  We not it with itself, so it's all 1s (assuming k was ≥ 1) (0xffffffff).  Then we and it with tmp0.  Anding something with a bunch of ones won't change it's value, so the value we get back from the ori is the value of tmp1.  We store that in $t0, so I guess this is just a convoluted way of not changing the value of $t0.

  E:ori $t1, $zero, 1
    sll $t1, k
    ori $t0, $t0, $t1

Here tmp1 is as before set to 1.  sll will make us with a 1 in the k'th bit in LSB order, so if we or that mask with tmp0 we should get tmp0 with a 1 in that bit (regardless of weather there was or was not a 1 in that bit in tmp0 in the first place).  So this effectively sets the kth LSB to 1 in tmp0.

I may have made a mistake somewhere in there; if so feel free to comment or write your own answer accordingly.  I'm deliberately laying out the logic of the code without answering the explicit question because it sounds like a homework question, so I'd like to help you understand the problem without necessarily giving away the solution.  Hope this helps.


问:
Aren't all errors caught during compilation regardless of typing (static vs. dynamic) in a compiled language?
Below is an answer explaining Dynamic vs. Static Typing.

I'm confused why this demonstrates Dynamic vs. Static typing as I thought all errors for compiled languages are caught during compilation anyway so it wouldn't matter whether it's statically or dynamically typed.

Maybe this is demonstrating that statically typed languages always raise errors before running and dynamic typing will always raise errors during execution regardless of it being compiled or interpreted?

Can someone explain this more in depth?

Here is an example contrasting how Python (dynamically typed) and Go
  (statically typed) handle a type error:

```<code>def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'
</code>```

Python does type checking at run time, and therefore:

```<code>silly(2)
</code>```

Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

```<code>silly(-1)
</code>```

Produces

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

because the relevant line was actually executed.

Go on the other hand does type-checking at compile time:

```<code>package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}
</code>```

The above will not compile, with the following error:

```<code>invalid operation: "3" + 5 (mismatched types string and int)
</code>```

答:
No. Type errors are not caught in compilation unless the language is statically typed.

Note that compilation WILL catch syntax errors regardless of typing.

The example is confusing as it couples "Static & Compiled" with "Dynamic & Interpreted" which obscures the effects of the different type systems.

Go example WOULD NOT throw an error if it was dynamically typed, despite being compiled!

Python example WOULD throw an error if it was statically typed, even though that line would never be interpreted!

Type-checking has nothing to do with the language being compiled or interpreted!

I'll review the basic concepts, then delve deeper into the example.

Compiled vs. Interpreted

"When source code is translated"

Source Code: Original code (usually typed by a human into a computer)

Translation: Converting source code into something a computer can read (i.e. machine code)

Run-Time: Period when program is executing commands (after compilation, if compiled)

Compiled Language: Code translated before run-time

Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts, such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

Static: Types checked before run-time

Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.

Python Example

Dynamic, Interpreted

```<code>def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)
</code>```

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.

Go Example

Static, Compiled

```<code>package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}
</code>```

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.

Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.

More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

```<code>num = 2
num = '3' // ERROR
</code>```

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.

Body:
Below is an answer explaining Dynamic vs. Static Typing.

I'm confused why this demonstrates Dynamic vs. Static typing as I thought all errors for compiled languages are caught during compilation anyway so it wouldn't matter whether it's statically or dynamically typed.

Maybe this is demonstrating that statically typed languages always raise errors before running and dynamic typing will always raise errors during execution regardless of it being compiled or interpreted?

Can someone explain this more in depth?

Here is an example contrasting how Python (dynamically typed) and Go
  (statically typed) handle a type error:

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

Python does type checking at run time, and therefore:

silly(2)

Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

silly(-1)

Produces

TypeError: unsupported operand type(s) for +: 'int' and 'str'

because the relevant line was actually executed.

Go on the other hand does type-checking at compile time:

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The above will not compile, with the following error:

invalid operation: "3" + 5 (mismatched types string and int)

Body:
No. Type errors are not caught in compilation unless the language is statically typed.

Note that compilation WILL catch syntax errors regardless of typing.

The example is confusing as it couples "Static & Compiled" with "Dynamic & Interpreted" which obscures the effects of the different type systems.

Go example WOULD NOT throw an error if it was dynamically typed, despite being compiled!

Python example WOULD throw an error if it was statically typed, even though that line would never be interpreted!

Type-checking has nothing to do with the language being compiled or interpreted!

I'll review the basic concepts, then delve deeper into the example.

Compiled vs. Interpreted

"When source code is translated"

Source Code: Original code (usually typed by a human into a computer)

Translation: Converting source code into something a computer can read (i.e. machine code)

Run-Time: Period when program is executing commands (after compilation, if compiled)

Compiled Language: Code translated before run-time

Interpreted Language: Code translated on the fly, during execution

Typing

"When types are checked"

5 + '3' is an example of a type error in strongly typed languages such as Go and Python, because they don't allow for "type coercion" -> the ability for a value to change type in certain contexts, such as merging two types. Weakly typed languages, such as JavaScript, won't throw a type error (results in '53').

Static: Types checked before run-time

Dynamic: Types checked on the fly, during execution

The definitions of "Static & Compiled" and "Dynamic & Interpreted" are quite similar...but remember it's "when types are checked" vs. "when source code is translated".

You'll get the same type errors irrespective of whether the language is compiled or interpreted! You need to separate these terms conceptually.

Python Example

Dynamic, Interpreted

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

silly(2)

Because Python is both interpreted and dynamically typed, it only translates and type-checks code it's executing on. The else block never executes, so 5 + '3' is never even looked at!

What if it was statically typed?

A type error would be thrown before the code is even run. It still performs type-checking before run-time even though it is interpreted.

What if it was compiled?

The else block would be translated/looked at before run-time, but because it's dynamically typed it wouldn't throw an error! Dynamically typed languages don't check types until execution, and that line never executes.

Go Example

Static, Compiled

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The types are checked before running (static) and the type error is immediately caught! The types would still be checked before run-time if it was interpreted, having the same result. If it was dynamic, it wouldn't throw any errors even though the code would be looked at during compilation.

Performance

A compiled language will have better performance at run-time if it's statically typed (vs. dynamically); knowledge of types allows for machine code optimization.

Statically typed languages have better performance at run-time intrinsically due to not needing to check types dynamically while executing (it checks before running).

Similarly, compiled languages are faster at run time as the code has already been translated instead of needing to "interpret"/translate it on the fly.

Note that both compiled and statically typed languages will have a delay before running for translation and type-checking, respectively.

More Differences

Static typing catches errors early, instead of finding them during execution (especially useful for long programs). It's more "strict" in that it won't allow for type errors anywhere in your program and often prevents variables from changing types, which further defends against unintended errors.

num = 2
num = '3' // ERROR

Dynamic typing is more flexible, which some appreciate. It typically allows for variables to change types, which can result in unexpected errors.


问:
How to set timeout for headless chrome
I try:

chrome --timeout 15000 .....

And if chrome doesn't finish in 15 seconds it should finish immediately.

But when i run

chrome --headless --disable-gpu --timeout 30000 --dump-dom http://example.com

I get

[1110/120048.838007:ERROR:headless_shell.cc(603)] Open multiple tabs
  is only supported when remote debugging is enabled.

It works w/o --timeout flag

Chrome Canary v64
OSX

Update at 2019 Nov.

I noticed this question gets a consistent flow of views and still
  provides no to little value. I wanted to update that now I use
  puppeteer, which is project from Google itself to use headless Chrome
  with NodeJs and it's really easy and straight forward API. If you are
  OK to use NodeJs - check it.

https://github.com/GoogleChrome/puppeteer

答: Try to use chrome --headless --disable-gpu —-timeout=30000 --dump-dom http://example.com

Title: How to set timeout for headless chrome


问:
how can i optimize this pseudo code
i am new user in python... i know that question very primitive but my project have lots of sets and i need effective and fast code

i want to generate a matrix with if condition.
for example:
          M=Matrix(m[i,j] if Condition1 and Condition2 and ...)

how can i optimize following pseudo code?

```<code>import networkx as nx
import numpy as np
#G=nx.graph()
#G.neighbors(node)
def seidel_matrix(G):
    n=nx.number_of_nodes(G)
    x=np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            if i==j:
                x[i][j]=0
            elif i in G.neighbors(j):
                x[i][j]=-1
            else:
                x[i][j]=1
    return x
</code>```

答:
There are probably multiple ways to do this.  Right now, you're looping over every possible edge.  If there are lots of non-edges this is a poor choice.  It would be faster to just loop over every edge that actually exists.

```<code>x = np.ones((n,n))  #default entry is 1.
for u, v in G.edges():   #get edges right
    x[u][v] = -1
    x[v][u] = -1 #assuming undirected network
for u in G.nodes():  #get diagonal right.
    x[u][u] = 0
</code>```

Note that this assumes that the nodes are labeled 0, 1, ..., n-1

Title: how can i optimize this pseudo code

Body:
i am new user in python... i know that question very primitive but my project have lots of sets and i need effective and fast code

i want to generate a matrix with if condition.
for example:
          M=Matrix(m[i,j] if Condition1 and Condition2 and ...)

how can i optimize following pseudo code?

import networkx as nx
import numpy as np
#G=nx.graph()
#G.neighbors(node)
def seidel_matrix(G):
    n=nx.number_of_nodes(G)
    x=np.zeros((n,n))
    for i in range(n):
        for j in range(n):
            if i==j:
                x[i][j]=0
            elif i in G.neighbors(j):
                x[i][j]=-1
            else:
                x[i][j]=1
    return x

Body:
There are probably multiple ways to do this.  Right now, you're looping over every possible edge.  If there are lots of non-edges this is a poor choice.  It would be faster to just loop over every edge that actually exists.

x = np.ones((n,n))  #default entry is 1.
for u, v in G.edges():   #get edges right
    x[u][v] = -1
    x[v][u] = -1 #assuming undirected network
for u in G.nodes():  #get diagonal right.
    x[u][u] = 0

Note that this assumes that the nodes are labeled 0, 1, ..., n-1