问:
icon rotation in leaflet package
I'm learning to program in R with the leaflet package.
I want to give an angle to the icons, and am trying it with this code:

```<code>m <- leaflet()
m <- addTiles(m,urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png")
m = m %>% setView(127.074167,34.456806, zoom = 9)
arrowIcon <- makeIcon(
  iconUrl = "arrow.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY =25
)
arrowIcon <- makeIcon(
  iconUrl = "ARROW_B2.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY = 25
)
offset = 0.00 # zoom 10-> 0.03, 9->0.06, 8 -> 0.12, 7 -> 0.24
m_lat = 34.45 + offset
m_lon = 127.07 - offset
m <- addMarkers(m,  lng=m_lon, lat= m_lat
            , options = c( markerOptions(), iconAngle= 0)
            ,icon= arrowIcon)
m <- addCircles(m, lng=127.07, lat=34.45 , weight = 10,radius = 100)
m
</code>```

However, it does not work.

答:
For your first point, I've found that you can load your image if it's stored in a directory named www.

```<code>|
|- app.R
|- www
    |- icon_plane.pg
</code>```

Then you'll be able to load it with this piece of code

```<code>onRender("function(el, x) {
          var planeIcon = L.icon({iconUrl: 'icon_plane.png', iconAnchor:[16, 16]});
          var pathPattern = L.marker([34.45, 127.07], {icon: planeIcon, rotationAngle: 90}).addTo(this);
          }")
</code>```

Becareful of loading correctly your js file. I spent a lot of time looking why my image wasn't showing and finally it was only because my script wasn't in the correct place.

Title: icon rotation in leaflet package

Body:
I'm learning to program in R with the leaflet package.
I want to give an angle to the icons, and am trying it with this code:

m <- leaflet()
m <- addTiles(m,urlTemplate = "http://xdworld.vworld.kr:8080/2d/Base/201310/{z}/{x}/{y}.png")
m = m %>% setView(127.074167,34.456806, zoom = 9)
arrowIcon <- makeIcon(
  iconUrl = "arrow.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY =25
)
arrowIcon <- makeIcon(
  iconUrl = "ARROW_B2.png"
  ,iconWidth = 100, iconHeight = 100
  ,iconAnchorX = 25, iconAnchorY = 25
)
offset = 0.00 # zoom 10-> 0.03, 9->0.06, 8 -> 0.12, 7 -> 0.24
m_lat = 34.45 + offset
m_lon = 127.07 - offset
m <- addMarkers(m,  lng=m_lon, lat= m_lat
            , options = c( markerOptions(), iconAngle= 0)
            ,icon= arrowIcon)
m <- addCircles(m, lng=127.07, lat=34.45 , weight = 10,radius = 100)
m

However, it does not work.

Body:
For your first point, I've found that you can load your image if it's stored in a directory named www.

|
|- app.R
|- www
    |- icon_plane.pg

Then you'll be able to load it with this piece of code

onRender("function(el, x) {
          var planeIcon = L.icon({iconUrl: 'icon_plane.png', iconAnchor:[16, 16]});
          var pathPattern = L.marker([34.45, 127.07], {icon: planeIcon, rotationAngle: 90}).addTo(this);
          }")

Becareful of loading correctly your js file. I spent a lot of time looking why my image wasn't showing and finally it was only because my script wasn't in the correct place.


来源: stackexchange

问:
how to find if a string has multiple phrases but in different order and cannot have more phrases or less and can have spaces in between
say for example I have a the following strings

```<code>$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";
</code>```

All i want to find is if my string is having "a", "b", "c", "d", "e", "f", "r", "t" where the string must not have anything other than the specified strings and the string must have all the specified strings in it may can separated by spaces.

maybe something like say compare($a, [ "a", "b", "c", "d", "e", "f", "r", "t" ]; should give me the output as follows.

```<code>$map = [ "a", "b", "c", "d", "e", "f", "r", "t" ];;
compare($a, $map); // false
compare($b, $map); // false
compare($c, $map); // false
compare($d, $map); // false
compare($e, $map); // false
compare($f, $map); // true
compare($g, $map); // false
</code>```

Can anyone help me out to solve this?

答:
```<code><?php

$a = "c d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e f g";
$g = "aabc d e f";

$array=[ "a", "b", "c", "d", "e", "f" ];

$length=strlen(str_replace(' ','',$e));

$flag=0;

foreach($array as $data){
    if (strpos($e, $data) !== false) {
        $flag=$flag+1;
    }
}

if($flag<>$length){
    echo "problem";
}
else{
    echo "working";
}
</code>```

Here is a sample code for what you ask. If you change the strings in here $length=strlen(str_replace(' ','',$e));

and in here

```<code>if (strpos($e, $data) !== false) {
</code>```

you will check by yourself it is working. I propose that you put those strings in an array and parse it more dynamic but that's up to you and your input.

ContentLicense: CC BY-SA 3.0

Body:
say for example I have a the following strings

$a = "crt d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e r f t";
$g = "aabc d e f";

All i want to find is if my string is having "a", "b", "c", "d", "e", "f", "r", "t" where the string must not have anything other than the specified strings and the string must have all the specified strings in it may can separated by spaces.

maybe something like say compare($a, [ "a", "b", "c", "d", "e", "f", "r", "t" ]; should give me the output as follows.

$map = [ "a", "b", "c", "d", "e", "f", "r", "t" ];;
compare($a, $map); // false
compare($b, $map); // false
compare($c, $map); // false
compare($d, $map); // false
compare($e, $map); // false
compare($f, $map); // true
compare($g, $map); // false

Can anyone help me out to solve this?

Body:
<?php

$a = "c d a e f b";
$b = "b e a d c f";
$c = "a b c d g e";
$d = "a b c";
$e = "abcdef";
$f = "a b c d e f g";
$g = "aabc d e f";

$array=[ "a", "b", "c", "d", "e", "f" ];

$length=strlen(str_replace(' ','',$e));

$flag=0;

foreach($array as $data){
    if (strpos($e, $data) !== false) {
        $flag=$flag+1;
    }
}

if($flag<>$length){
    echo "problem";
}
else{
    echo "working";
}

Here is a sample code for what you ask. If you change the strings in here $length=strlen(str_replace(' ','',$e));

and in here

if (strpos($e, $data) !== false) {

you will check by yourself it is working. I propose that you put those strings in an array and parse it more dynamic but that's up to you and your input.


问:
How to execute a java script with jshell?
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

```<code>#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit
</code>```

However that gives:

```<code>⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World
</code>```

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?

答:
Inspired by steiny answer, I came up with a more generic solution

https://gist.github.com/ffissore/012d7e32a096fde5266f49038c93dcaf

In essence: jshell-wrapper will strip the first line of the script (which is supposed to be the shebang) and will add a /exit at the end of the script

Body:
Given that Java 9 is upon us and we can finally have a java REPL with jshell I was hoping there was a way to add a shebang to a script and have jshell interpret it.

I tried creating test.jsh:

#!/usr/bin/env jshell -s
System.out.println("Hello World")
/exit

However that gives:

⚡ ./test.jsh
|  Error:
|  illegal character: '#'
|  #!/usr/bin/env jshell -s
|  ^
|  Error:
|  illegal start of expression
|  #!/usr/bin/env jshell -s
|    ^
Hello World

It turns out there is an enhancement request for this in OpenJDK https://bugs.openjdk.java.net/browse/JDK-8167440.

Is there any other way to do this?


问:
System.loadLibrary(...) couldn't find native library in my case
I want to use a existing native library from another Android project, so I just copied the NDK built library (libcalculate.so) to my new Android project. In my new Android project I created a folder libs/armeabi/ and put libcalculate.so there. There is no jni/ folder. My testing device has ARM architecture.

In my java code I load the library by:

```<code>  static{
    System.loadLibrary("calculate");
  }
</code>```

When I run my new android project, I got error:

```<code>java.lang.UnsatisfiedLinkError:  ...
nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libcalculate.so"
</code>```

So, as error says, the copied native library is not in /verdor/lib or /system/lib , how to resolve this problem in my case?

(I unziped the apk package, under lib/ there is libcalculate.so)

====UPDATE=====

I also tried to create a jni/ folder under project root, and add an Android.mk file under jni/. The content of Android.mk is:

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)
</code>```

Then, under project root, I executed ndk-build . After that, the armeabi/ and armeabi-v7a/ directories are generated by ndk-build (with libcalculate.so inside the folder).

Then I run my maven build the project successfully. In the final apk package, there are:

```<code>lib/armeabi/libcalculate.so
lib/armeabi-v7a/libcalculate.so
</code>```

But when I run my app, the same error throw:

```<code>java.lang.UnsatisfiedLinkError:  ...
nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libcalculate.so"
</code>```

答:
This is an Android 8 update.

In earlier version of Android, to LoadLibrary native shared libraries (for access via JNI for example) I hard-wired my native code to iterate through a range of potential directory paths for the lib folder, based on the various apk installation/upgrade algorithms:

```<code>/data/data/<PackageName>/lib
/data/app-lib/<PackageName>-1/lib
/data/app-lib/<PackageName>-2/lib
/data/app/<PackageName>-1/lib
/data/app/<PackageName>-2/lib
</code>```

This approach is hokey and will not work for Android 8; from https://developer.android.com/about/versions/oreo/android-8.0-changes.html
you'll see that as part of their "Security" changes you now need to use sourceDir:

"You can no longer assume that APKs reside in directories whose names end in -1 or -2. Apps should use sourceDir to get the directory, and not rely on the directory format directly."

Correction, sourceDir is not the way to find your native shared libraries; use something like. Tested for Android 4.4.4 --> 8.0

```<code>// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
    ApplicationInfo appInfo = context.getApplicationInfo();
    return appInfo.nativeLibraryDir;
}
</code>```

Body:
I want to use a existing native library from another Android project, so I just copied the NDK built library (libcalculate.so) to my new Android project. In my new Android project I created a folder libs/armeabi/ and put libcalculate.so there. There is no jni/ folder. My testing device has ARM architecture.

In my java code I load the library by:

  static{
    System.loadLibrary("calculate");
  }

When I run my new android project, I got error:

java.lang.UnsatisfiedLinkError:  ...
nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libcalculate.so"

So, as error says, the copied native library is not in /verdor/lib or /system/lib , how to resolve this problem in my case?

(I unziped the apk package, under lib/ there is libcalculate.so)

====UPDATE=====

I also tried to create a jni/ folder under project root, and add an Android.mk file under jni/. The content of Android.mk is:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)

Then, under project root, I executed ndk-build . After that, the armeabi/ and armeabi-v7a/ directories are generated by ndk-build (with libcalculate.so inside the folder).

Then I run my maven build the project successfully. In the final apk package, there are:

lib/armeabi/libcalculate.so
lib/armeabi-v7a/libcalculate.so

But when I run my app, the same error throw:

java.lang.UnsatisfiedLinkError:  ...
nativeLibraryDirectories=[/vendor/lib, /system/lib]]] couldn't find "libcalculate.so"

Body:
This is an Android 8 update.

In earlier version of Android, to LoadLibrary native shared libraries (for access via JNI for example) I hard-wired my native code to iterate through a range of potential directory paths for the lib folder, based on the various apk installation/upgrade algorithms:

/data/data/<PackageName>/lib
/data/app-lib/<PackageName>-1/lib
/data/app-lib/<PackageName>-2/lib
/data/app/<PackageName>-1/lib
/data/app/<PackageName>-2/lib

This approach is hokey and will not work for Android 8; from https://developer.android.com/about/versions/oreo/android-8.0-changes.html
you'll see that as part of their "Security" changes you now need to use sourceDir:

"You can no longer assume that APKs reside in directories whose names end in -1 or -2. Apps should use sourceDir to get the directory, and not rely on the directory format directly."

Correction, sourceDir is not the way to find your native shared libraries; use something like. Tested for Android 4.4.4 --> 8.0

// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
    ApplicationInfo appInfo = context.getApplicationInfo();
    return appInfo.nativeLibraryDir;
}


问:
Validate form within ngDialog openConfirm before closing
I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.

Here is a simplified version of my code:

```<code>someFunction() {
    let newScope = $scope.$new();
    newScope.vm = vm;
    ngDialog.openConfirm({
        scope: newScope,
        template: 'componentDescription.html'
    })
}
</code>```

And my html:

```<code><form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
</code>```

I would like for the Dialog to only be submitted if the form is valid.

I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.

Any ideas?

UPDATE:
I've changed my html like so:

```<code><form role="form" name="subForm" novalidate ng-submit="confirm(0)">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="submit">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>
</code>```

This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.

答:
Simply you can add ng-disabled option with your form name

```<code><button type="button" ng-disabled="subForm.$invalid" ng-click="confirm(0)">Submit</button>
</code>```

Body:
I have a button that opens an ngDialog.openConfirm. Within that dialog I have a form, which includes a textarea which is required and needs to be a minimum 20 characters.

Here is a simplified version of my code:

someFunction() {
    let newScope = $scope.$new();
    newScope.vm = vm;
    ngDialog.openConfirm({
        scope: newScope,
        template: 'componentDescription.html'
    })
}

And my html:

<form role="form" name="subForm">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="button" ng-click="confirm(0)">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

I would like for the Dialog to only be submitted if the form is valid.

I tried to do this by creating a function in my controller , but that has trouble accessing the form/closing the dialog.

Any ideas?

UPDATE:
I've changed my html like so:

<form role="form" name="subForm" novalidate ng-submit="confirm(0)">
   <textarea name="compDesc"
             required="true"
             ng-minlength="20"
             ng-model="vm.compDesc">
   </textarea>
   <button type="submit">Submit</button>
   <button type="button" ng-click="closeThisDialog(0)">Cancel</button>
</form>

This works on the first click, which brings up my error messages, but on the second click it submits the form even though it's invalid. Seems that whenever the error messages are displayed the submit button ignores the validation.

Body:
Simply you can add ng-disabled option with your form name

<button type="button" ng-disabled="subForm.$invalid" ng-click="confirm(0)">Submit</button>


问:
Python joint enumerate with multiple variables
So I would like to iterate over two lists simultaneously and I also need the index as done with the following code. Both are straightforward to me, but is it possible two use enumerate in the second case as well? Of course, assuming both var arrays are of the same length.</p>

```<code>import numpy as np

def _eqn(y, variables, sign=-1.0):
    f = 0
    for i,x in enumerate(variables):
        f += x/(1+0.06)**(i+1)
    return float(sign*(y + f))

_eqn(1,np.array([1,1]))

def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    n = len(vars1)
    for x,y,i in zip(vars1, vars2, range(n)):
        f += (x+y)/(1+0.06)**(i+1)
    return float(sign*(y + f))

_eqn2(1,np.array([1,1]),np.array([1,1]))
</code>```

答:
Yes, it is possible... although with a slight change

```<code>def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    for i, (v1,v2) in enumerate(zip(vars1, vars2)):
        f += (v1+v2)/(1+0.06)**(i+1)
    return float(sign*(y + f))
</code>```

You enumerate tuples of the zip of your vars.

Although since you're working with numpy arrays, I'm sure that there is a better way to achieve this same goal without using a python for loop.

Also took the liberty of changing the names of variables since you were usign y in two different contexts and could be confusing.

Body:
So I would like to iterate over two lists simultaneously and I also need the index as done with the following code. Both are straightforward to me, but is it possible two use enumerate in the second case as well? Of course, assuming both var arrays are of the same length.

import numpy as np

def _eqn(y, variables, sign=-1.0):
    f = 0
    for i,x in enumerate(variables):
        f += x/(1+0.06)**(i+1)
    return float(sign*(y + f))

_eqn(1,np.array([1,1]))

def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    n = len(vars1)
    for x,y,i in zip(vars1, vars2, range(n)):
        f += (x+y)/(1+0.06)**(i+1)
    return float(sign*(y + f))

_eqn2(1,np.array([1,1]),np.array([1,1]))

Body:
Yes, it is possible... although with a slight change

def _eqn2(y, vars1, vars2, sign=-1.0):
    f = 0
    for i, (v1,v2) in enumerate(zip(vars1, vars2)):
        f += (v1+v2)/(1+0.06)**(i+1)
    return float(sign*(y + f))

You enumerate tuples of the zip of your vars.

Although since you're working with numpy arrays, I'm sure that there is a better way to achieve this same goal without using a python for loop.

Also took the liberty of changing the names of variables since you were usign y in two different contexts and could be confusing.


问:
Can't push my changes to a branch
I hope someone can help me with this issue. I've been working on this specific project for a while now and only recently have I been getting this issue every time I try to push my changes to the remote branch.

It seems like it needs all other branches to be updated before I can push my latest changes on the current branch.

答:
You are not able to push changes because your remote branch's commit is ahead  than what you are trying to push currently from local. If you squashed commits and try to push changes it will reject commits like that. You can do a safe  force push to that branch</p>

```<code>git push <upstream name> +<branch name>
</code>```

Title: Can't push my changes to a branch

Body:
You are not able to push changes because your remote branch's commit is ahead  than what you are trying to push currently from local. If you squashed commits and try to push changes it will reject commits like that. You can do a safe  force push to that branch

git push <upstream name> +<branch name>


问:
Overhead of std::optional<T>?
Now that std::experimental::optional has been accepted (or is about to be accepted), I wonder what is the overhead and the consequences on the assembly generated when the inner value is get by the following operators :

```<code>->
*
value
value_or
</code>```

compared to the case without std::optional. It could be particularly important for computationaly intensive programs.

For example, what would be order of magnitude of the overhead on operations on a std::vector<std::experimental::optional<double>> compared to a std::vector<double> ?

答:
Besides the other answer, you should also consider that std::optional requires additional memory.

Often it's not just an extra byte, but (at least for "small" types) a 2x space overhead due to padding .

Maybe RAM isn't a problem but that also means fewer values available in the cache.

A sentinel value, if specific knowledge allows to use it, could be a better choice (probably in the form of markable to keep type safety).

An interesting reading is: Boost optional - Performance considerations

Title: Overhead of std::optional<T>?

Body:
Now that std::experimental::optional has been accepted (or is about to be accepted), I wonder what is the overhead and the consequences on the assembly generated when the inner value is get by the following operators :

->
*
value
value_or

compared to the case without std::optional. It could be particularly important for computationaly intensive programs.

For example, what would be order of magnitude of the overhead on operations on a std::vector<std::experimental::optional<double>> compared to a std::vector<double> ?

ContentLicense: CC BY-SA 4.0


问:
Automatic service loading inside Controller using FOSElasticaBundle and Symfony 3.3
Here's my autowiring configuration in app/config/services.yml :

My controller :

Problem is when I use the new feature in Symfony 3.3 to automatically load service "fos_elastica.index.app.cv" in my bundle :
,
the container can no longer find the service inside the  app/config/elastica.yml.

Can you guys help me out to solve this problem, or if you have any clue on how can I read the service "app/config/elastica.yml" ?

答:
Struggled yesterday over the same problem while refactoring my controllers to services with autowire and injecting services in my controllers. 'fos_elstica.index.app.cv' can not autowired, so inject your dependency via constructor in your controller and configure your argument in service.yml. Place this at top of your controller:

```<code>private $finder;

/**
 * constructor.
 *
 * @param PaginatedFinderInterface $finder
 *
 */
public function __construct(PaginatedFinderInterface $finder)
{
    $this->finder = $finder;
}
</code>```

In your services.yml:

```<code>AppBundle\Controller\MyContgroller:
    arguments:
        $finder: '@fos_elstica.index.app.cv'
</code>```

Finaly use your finder in your action method via $this->finder.

Body:
Struggled yesterday over the same problem while refactoring my controllers to services with autowire and injecting services in my controllers. 'fos_elstica.index.app.cv' can not autowired, so inject your dependency via constructor in your controller and configure your argument in service.yml. Place this at top of your controller:

private $finder;

/**
 * constructor.
 *
 * @param PaginatedFinderInterface $finder
 *
 */
public function __construct(PaginatedFinderInterface $finder)
{
    $this->finder = $finder;
}

In your services.yml:

AppBundle\Controller\MyContgroller:
    arguments:
        $finder: '@fos_elstica.index.app.cv'

Finaly use your finder in your action method via $this->finder.


问:
How to implement google maps in my iPhone application
I am totally confused with google maps and maps of iPhone...

i have read that iPhone uses google maps.....and also spent some time on it....

But it never display the items like  location pictures, balloons etc.

EDIT

THIS is photo for of browser

and following is same place for iPhone maps

second one did not show the annotation added by people.....
(this is what i was asking for ballons or other pictures which people adds to location  on oogle maps)

I want to display all those in my application....

what should i do...

if you suggests implement Google maps API, then please suggest a working link...or provide some sample code if possible.....if anybody has done it...then please mail me at yogeshkumau@gmail.com

waiting for answer......

答: Points of Interests(location, pictures and baloons) that you are talking about can be shown in your maps, if you acquire the license for Google maps premier api. In that case you'd have to use dynamic maps by using google's web services. However if you want to implement it using MapKit framework on iOS devices, you'd have to draw your custom POIs using core graphics.</p>

ContentLicense: CC BY-SA 2.5


问:
Dealing with Promises
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

```<code>my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js
</code>```

Each file at the moment looks like

```<code>## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})
</code>```

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.

答:
I've done some minor changes in your files . You are neither resolving anything in FileDownload nor are you returning anything in getCSVData . Hence the final console will print nothing .Please try the code below</p>

```<code>## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');
module.exports = function(url, target) {
 return new Promise(function(resolve,reject){
     fetch(url)
    .then(function(res) {
       var dest = fs.createWriteStream(target);
       res.body.pipe(dest)
       .on('finish', function(data){
        console.log(`File saved at ${target}`)
        resolve(data)
       })
      .on('error', function(){
           reject();
      })        // ** Reject on error

    })

 })
 }

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  return  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})
</code>```

Title: Dealing with Promises

Body:
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js

Each file at the moment looks like

## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.

Body:
I've done some minor changes in your files . You are neither resolving anything in FileDownload nor are you returning anything in getCSVData . Hence the final console will print nothing .Please try the code below

## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');
module.exports = function(url, target) {
 return new Promise(function(resolve,reject){
     fetch(url)
    .then(function(res) {
       var dest = fs.createWriteStream(target);
       res.body.pipe(dest)
       .on('finish', function(data){
        console.log(`File saved at ${target}`)
        resolve(data)
       })
      .on('error', function(){
           reject();
      })        // ** Reject on error

    })

 })
 }

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  return  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})


问:
linq: left join in linq with different type of conditions
I've two tables like promotionalOffers and PromotionalOffersUsed

I'm getting the matching records using joins now i wanted to include different conditions like PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

I've written query in sql using left join working expected but I'm unable to write same query in linq

here my sql query

```<code>SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null
</code>```

my linq query is

```<code>(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId
 where s.ISVCSPId == iSVCSPData.Id
 select s).ToListAsync();
</code>```

I'm unable to include left join here

答:
Apparently you have a one-to-many relation between PromotionalOffers
and PromotionalOffersUsed: Every PromotionalOffer has zero or more PromotionalOffersUsed, and every PromotionalOffersUsed belongs to exactly one PromotionalOffer.

If you follow the entity framework conventions to design this one-to-many relation, you would not need to do a join, nor a left-outerjoin, you would use the ICollection classes instead:

```<code>class PromotionalOffer
{
    public int Id {set; set;}
    // a PromotionalOffer has zero or more PromotionalOfferUsed
    public virtual ICollection<PromotionalOfferUsed> PromitionalOffersUsed {get; set;}
    ...
}
class PromotionalOfferUsed
{
    public int Id {set; set;}
    // every PromotionalOffersUsed belongs to exactly one PromotionalOffer
    // using foreign key:
    public int PromotionalOfferId {get; set;}
    public PromotionalOffer PromotionalOffer {get; set;}
    ...
}
class MyDbContext: DbContext
{
    public DbSet<PromotionalOffer> PromotionalOffers {get; set;}
    public DbSet<PromotionalOfferUsed> PromotionalOffersUsed {get; set;
}
</code>```

Normally this would have been enough for entity framework to know that you designed a one-to-many relation.

The only reason we need some fluent API is because of the strange plurals:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // PromotionalOffersUsed are stored in a table with name PromotionOffersUsed:
    modelBuilder.Entity<PromotionalOfferUsed>().ToTable("PromotionalOffersUdsed");

    // Every PromotionalOffer has zero or more PromotionalOfferUsed
    // every PromotionalOfferUsed belongs to exactly one (required) PromotionalOffer
    // using foreign key PromtionalOfferId
    modelBuilder.Entity<PromotionalOffer>
        .HasMany(promotionalOffer => promotionalOffer.PromotionalOffersUsed)
        .WithRequired(promotionalOfferUsed => promotionOfferUsed.PromotionalOffer)
         .HasForeignKey(post => post.BlogId);

    base.OnModelCreating(modelBuilder);
}
</code>```

Once again, if you had standard singulars and plurals (Person/Persons; Account/Accounts, Order/Orders), this fluent API was not needed.

Now your query: think in Collections, not in Joins.

Give me all PromotionalOffers that have ISVCSPId equal to 10, together
  with all their PromotionalOffersUsed that have OfferId equal to null

```<code>using (var dbContext = new MyDbContext())
{
    var result = dbContext.PromotionalOffers
        .Where(promotionalOffer => promotionalOffer.ISVCSPID == 10)
        .Select(promotionalOffer => new
        {   // select only the properties you will be using:
            ISVCSPID = promotionalOffers.ISVSPID,
            ... // other properties from promotionalOffers

            PromotionalOffersUsed = promotionalOffers.PromtionalOffersUsed
                .Where(promotionalOffersUsed => promotionalOffersUsed.OfferId == null)
                .Select(promotionalOffersUsed => new
                {
                     // again: select only the properties of PromotionalOffersUsed
                     // that you will be using
                     Id = promotionalOffersUsed.Id,
                     ... // other properties
                })
                .ToList();
        }
}
</code>```

Because entity framework knows that there is a one-to-many with a foreign key, it will do the proper left outer join for you.

Body:
I've two tables like promotionalOffers and PromotionalOffersUsed

I'm getting the matching records using joins now i wanted to include different conditions like PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

I've written query in sql using left join working expected but I'm unable to write same query in linq

here my sql query

SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

my linq query is

(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId
 where s.ISVCSPId == iSVCSPData.Id
 select s).ToListAsync();

I'm unable to include left join here

Body:
Apparently you have a one-to-many relation between PromotionalOffers
and PromotionalOffersUsed: Every PromotionalOffer has zero or more PromotionalOffersUsed, and every PromotionalOffersUsed belongs to exactly one PromotionalOffer.

If you follow the entity framework conventions to design this one-to-many relation, you would not need to do a join, nor a left-outerjoin, you would use the ICollection classes instead:

class PromotionalOffer
{
    public int Id {set; set;}
    // a PromotionalOffer has zero or more PromotionalOfferUsed
    public virtual ICollection<PromotionalOfferUsed> PromitionalOffersUsed {get; set;}
    ...
}
class PromotionalOfferUsed
{
    public int Id {set; set;}
    // every PromotionalOffersUsed belongs to exactly one PromotionalOffer
    // using foreign key:
    public int PromotionalOfferId {get; set;}
    public PromotionalOffer PromotionalOffer {get; set;}
    ...
}
class MyDbContext: DbContext
{
    public DbSet<PromotionalOffer> PromotionalOffers {get; set;}
    public DbSet<PromotionalOfferUsed> PromotionalOffersUsed {get; set;
}

Normally this would have been enough for entity framework to know that you designed a one-to-many relation.

The only reason we need some fluent API is because of the strange plurals:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // PromotionalOffersUsed are stored in a table with name PromotionOffersUsed:
    modelBuilder.Entity<PromotionalOfferUsed>().ToTable("PromotionalOffersUdsed");

    // Every PromotionalOffer has zero or more PromotionalOfferUsed
    // every PromotionalOfferUsed belongs to exactly one (required) PromotionalOffer
    // using foreign key PromtionalOfferId
    modelBuilder.Entity<PromotionalOffer>
        .HasMany(promotionalOffer => promotionalOffer.PromotionalOffersUsed)
        .WithRequired(promotionalOfferUsed => promotionOfferUsed.PromotionalOffer)
         .HasForeignKey(post => post.BlogId);

    base.OnModelCreating(modelBuilder);
}

Once again, if you had standard singulars and plurals (Person/Persons; Account/Accounts, Order/Orders), this fluent API was not needed.

Now your query: think in Collections, not in Joins.

Give me all PromotionalOffers that have ISVCSPId equal to 10, together
  with all their PromotionalOffersUsed that have OfferId equal to null

using (var dbContext = new MyDbContext())
{
    var result = dbContext.PromotionalOffers
        .Where(promotionalOffer => promotionalOffer.ISVCSPID == 10)
        .Select(promotionalOffer => new
        {   // select only the properties you will be using:
            ISVCSPID = promotionalOffers.ISVSPID,
            ... // other properties from promotionalOffers

            PromotionalOffersUsed = promotionalOffers.PromtionalOffersUsed
                .Where(promotionalOffersUsed => promotionalOffersUsed.OfferId == null)
                .Select(promotionalOffersUsed => new
                {
                     // again: select only the properties of PromotionalOffersUsed
                     // that you will be using
                     Id = promotionalOffersUsed.Id,
                     ... // other properties
                })
                .ToList();
        }
}

Because entity framework knows that there is a one-to-many with a foreign key, it will do the proper left outer join for you.


问:
Hi already running wordpress website

Warning:
  require(/home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-includes/load.php):
  failed to open stream: No such file or directory in
  /home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-settings.php
  on line 23

Fatal error: require(): Failed opening required
  '/home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-includes/load.php'
  (include_path='.:/usr/lib/php:/usr/local/lib/php') in
  /home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-settings.php
  on line 23

答:
Looks like the file load.php doesn't exist or having bad permissions :

```<code>/home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-includes/load.php
</code>```

first check if file exists, if yes try do change permission less restricted

hope it helps

Title: Hi already running wordpress website

Body:
Looks like the file load.php doesn't exist or having bad permissions :

/home/hitechinstitute/public_html/phonerepairingcourse/blog/wp-includes/load.php

first check if file exists, if yes try do change permission less restricted

hope it helps


问:
jQuery children selector
I have the following markup:

```<code><div class="form-fields">
  <div class="row">
    <span class="info">Info</span>
  </div>
</div>
</code>```

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

答:
.children() will only grab immediate child nodes. You need to invoke .find().

```<code>$('.form-fields').find('.row .info')
</code>```

or even

```<code>$('.form-fields').find('.row').find('.info');
</code>```

just by selector

```<code>$('.form-fields .info')
</code>```

Reference: .children(), .find()

Title: jQuery children selector

Body:
I have the following markup:

    Info

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

Body:
.children() will only grab immediate child nodes. You need to invoke .find().

$('.form-fields').find('.row .info')

or even

$('.form-fields').find('.row').find('.info');

just by selector

$('.form-fields .info')

Reference: .children(), .find()


问:
How to send HTML email using linux command line
I need to send email with html format. I have only linux command line and command "mail".

Currently have used:

```<code>echo "To: address@example.com" > /var/www/report.csv
echo "Subject: Subject" >> /var/www/report.csv
echo "Content-Type: text/html; charset=\"us-ascii\"" >> /var/www/report.csv

echo "<html>" >> /var/www/report.csv
mysql -u ***** -p***** -H -e "select * from users LIMIT 20" dev >> /var/www/report.csv
echo "</html>" >> /var/www/report.csv

mail -s "Built notification" address@example.com < /var/www/report.csv
</code>```

But in my mail-agent i get only plain/text.

答:
I found a really easy solution: add to the mail command the modifier -aContent-Type:text/html.

In your case would be:

```<code>mail -aContent-Type:text/html -s "Built notification" address@example.com < /var/www/report.csv
</code>```

Body:
I need to send email with html format. I have only linux command line and command "mail".

Currently have used:

echo "To: address@example.com" > /var/www/report.csv
echo "Subject: Subject" >> /var/www/report.csv
echo "Content-Type: text/html; charset=\"us-ascii\"" >> /var/www/report.csv

echo "" >> /var/www/report.csv
mysql -u ***** -p***** -H -e "select * from users LIMIT 20" dev >> /var/www/report.csv
echo "" >> /var/www/report.csv

mail -s "Built notification" address@example.com < /var/www/report.csv

But in my mail-agent i get only plain/text.

Body:
I found a really easy solution: add to the mail command the modifier -aContent-Type:text/html.

In your case would be:

mail -aContent-Type:text/html -s "Built notification" address@example.com < /var/www/report.csv


问:
How to send a mail with mention?
When I get mails:

```<code>GET /beta/me/messages
</code>```

I can check this to see if someone mentioned me.

```<code>mentionsPreview: {
  isMentioned: true
}
</code>```

How can I send out a mail and mention someone or some people in the mail?

I didn't find any info in the document.

UPDATE 1:
I can successfully add mentions when create a new mail and send out by

```<code>POST /beta/me/sendMail

{
  // ...
  "mentions":[{
    "mentioned": {
      "name": "Jack",
      "address": "jack@example.com"
     },
    "createdBy": {
      "name": "Me",
      "address": "me@example.com"
    }
  }]
}
</code>```

However, I failed to add mentions when reply a mail. I create a draft first by

```<code>POST /beta/me/messages/{messageId}/createReplyAll
</code>```

Then I update it by (this step failed to add mentions)

```<code>PATCH /beta/me/messages/{messageId}

{
  "body": {
    "contentType": "html",
    "content": "hi"
  },
  "mentions":[{
    "mentioned": {
      "name": "Jack",
      "address": "jack@example.com"
     },
    "createdBy": {
      "name": "Me",
      "address": "me@example.com"
    }
  }]
}
</code>```

I send it out by

```<code>POST /beta/me/messages/{messageId}/send
</code>```

In the mail Jack got, the content successfully updated. But mentionsPreview is still null.

UPDATE 2:

Thanks Jason's help.

Further test, I succeed add mention by

```<code>POST /beta/me/messages/{messageId}/mentions

{
  "mentioned": {
    "address": "jack@example.com"
  }
}
</code>```

But I failed to add mentions using array

```<code>POST /beta/me/messages/{messageId}/mentions

{
  "mentions":[{
    "mentioned": {
      "address": "jack@example.com"
    }
  }]
}
</code>```

which means I have to POST mentions one by one at least for now.

答:
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/mention

When creating a message, an app can create a mention in the same POST request by including the mention in the mentions property.

UPDATE

On your new question about doing this on a reply, the problem is you cannot PATCH in mentions like that. You can only include mentions inline with the rest of the message if you do it at message creation. Since you've already created the message (via the createReplyAll method), to update mentions you need to POST new mentions to the /mentions relationship on the message, like:

```<code>POST /me/messages/{messageId}/mentions

{
  "mentioned": {
    "name": "Jack",
    "address": "jack@example.com"
  },
  "createdBy": {
    "name": "Me",
    "address": "me@example.com"
  }
}
</code>```

As an interesting side note, you CANNOT currently include mentions inline using the replyAll method. It seems that you can only do this when creating a brand new message or when sending a new message. For all other cases, you need to do a POST to the /mentions relationship as above.

Title: How to send a mail with mention?

Body:
When I get mails:

GET /beta/me/messages

I can check this to see if someone mentioned me.

mentionsPreview: {
  isMentioned: true
}

How can I send out a mail and mention someone or some people in the mail?

I didn't find any info in the document.

UPDATE 1:
I can successfully add mentions when create a new mail and send out by

POST /beta/me/sendMail

{
  // ...
  "mentions":[{
    "mentioned": {
      "name": "Jack",
      "address": "jack@example.com"
     },
    "createdBy": {
      "name": "Me",
      "address": "me@example.com"
    }
  }]
}

However, I failed to add mentions when reply a mail. I create a draft first by

POST /beta/me/messages/{messageId}/createReplyAll

Then I update it by (this step failed to add mentions)

PATCH /beta/me/messages/{messageId}

{
  "body": {
    "contentType": "html",
    "content": "hi"
  },
  "mentions":[{
    "mentioned": {
      "name": "Jack",
      "address": "jack@example.com"
     },
    "createdBy": {
      "name": "Me",
      "address": "me@example.com"
    }
  }]
}

I send it out by

POST /beta/me/messages/{messageId}/send

In the mail Jack got, the content successfully updated. But mentionsPreview is still null.

UPDATE 2:

Thanks Jason's help.

Further test, I succeed add mention by

POST /beta/me/messages/{messageId}/mentions

{
  "mentioned": {
    "address": "jack@example.com"
  }
}

But I failed to add mentions using array

POST /beta/me/messages/{messageId}/mentions

{
  "mentions":[{
    "mentioned": {
      "address": "jack@example.com"
    }
  }]
}

which means I have to POST mentions one by one at least for now.

Body:
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/resources/mention

When creating a message, an app can create a mention in the same POST request by including the mention in the mentions property.

UPDATE

On your new question about doing this on a reply, the problem is you cannot PATCH in mentions like that. You can only include mentions inline with the rest of the message if you do it at message creation. Since you've already created the message (via the createReplyAll method), to update mentions you need to POST new mentions to the /mentions relationship on the message, like:

POST /me/messages/{messageId}/mentions

{
  "mentioned": {
    "name": "Jack",
    "address": "jack@example.com"
  },
  "createdBy": {
    "name": "Me",
    "address": "me@example.com"
  }
}

As an interesting side note, you CANNOT currently include mentions inline using the replyAll method. It seems that you can only do this when creating a brand new message or when sending a new message. For all other cases, you need to do a POST to the /mentions relationship as above.


问:
C# Websocket server not receiving messages from HTML5 client
I'm attempting to create a bare bones websocket chat room server. My client is able to connect to the server, but it is unable to send messages to the server, despite the server being in a listening state.

When the client connects, a bunch of what looks like header information gets written to the console. But when WebSocket.send() gets executed in Javascript, nothing occurs server side.

HTML:

```<code><button id="closeSocket">disconnect</button><br />
<input id = "inputField" /><button id="sendMessage">send</button>
<div id = "output"></div>

<script type = 'text/javascript' src = 'websockets.js'></script>
</code>```

Javascript:

```<code>websocket = new WebSocket("ws://127.0.0.1:80");

document.getElementById("closeSocket").onclick = closeSocket;
document.getElementById("sendMessage").onclick = sendMessage;

websocket.onopen = function(){
  output("connected");
}

function sendMessage(){
    output("sent: " + document.getElementById('inputField').value);
  websocket.send(document.getElementById('inputField').value);
}

websocket.onmessage = function(e){
  output("got response: " + e.data);
}

function closeSocket(){
    websocket.close();
}

websocket.onclose = function(){
    output("disconnected");
}

function output(t){
    document.getElementById("output").innerHTML += t + "<br />";
}
</code>```

C# server:

```<code>using System;
using System.Net;
using System.Net.Sockets;

namespace WebSocketsTutorial {
    class Program {
        static void Main(string[] args) {
            TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
            TcpClient client = default(TcpClient);

            server.Start();
            Console.WriteLine("server started");

            while (true) {
                client = server.AcceptTcpClient();

                byte[] receivedBuffer = new byte[100];
                NetworkStream stream = client.GetStream();

                stream.Read(receivedBuffer, 0, receivedBuffer.Length);

                foreach (byte b in receivedBuffer) {
                    Console.Write(Convert.ToChar(b).ToString());
                }
            }
        }
    }
}
</code>```

This is what is output on the console when the client connects:

What I'm mainly looking to do is to allow an arbitrary number of connections and ultimately have the server echo a user's submission to all connected clients.

答:
First of all, a WebSocket is not just a regular socket. It defines a connection handshake using HTTP and its own framing protocol that you need to use.

https://en.wikipedia.org/wiki/WebSocket

https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

https://hpbn.co/websocket/

Second, you are reading just the first 100 bytes of the request. You should read until the Read operation returns 0.

There is a myriad of components you can use to create a WebSocket server, including the default one: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets

Body:
I'm attempting to create a bare bones websocket chat room server. My client is able to connect to the server, but it is unable to send messages to the server, despite the server being in a listening state.

When the client connects, a bunch of what looks like header information gets written to the console. But when WebSocket.send() gets executed in Javascript, nothing occurs server side.

HTML:

<button id="closeSocket">disconnect</button>

<input id = "inputField" /><button id="sendMessage">send</button>

Javascript:

websocket = new WebSocket("ws://127.0.0.1:80");

document.getElementById("closeSocket").onclick = closeSocket;
document.getElementById("sendMessage").onclick = sendMessage;

websocket.onopen = function(){
  output("connected");
}

function sendMessage(){
    output("sent: " + document.getElementById('inputField').value);
  websocket.send(document.getElementById('inputField').value);
}

websocket.onmessage = function(e){
  output("got response: " + e.data);
}

function closeSocket(){
    websocket.close();
}

websocket.onclose = function(){
    output("disconnected");
}

function output(t){
    document.getElementById("output").innerHTML += t + "
";
}

C# server:

using System;
using System.Net;
using System.Net.Sockets;

namespace WebSocketsTutorial {
    class Program {
        static void Main(string[] args) {
            TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
            TcpClient client = default(TcpClient);

            server.Start();
            Console.WriteLine("server started");

            while (true) {
                client = server.AcceptTcpClient();

                byte[] receivedBuffer = new byte[100];
                NetworkStream stream = client.GetStream();

                stream.Read(receivedBuffer, 0, receivedBuffer.Length);

                foreach (byte b in receivedBuffer) {
                    Console.Write(Convert.ToChar(b).ToString());
                }
            }
        }
    }
}

This is what is output on the console when the client connects:

What I'm mainly looking to do is to allow an arbitrary number of connections and ultimately have the server echo a user's submission to all connected clients.


问:
Unit testing for exceptions that were catched
```<code>public void methodToBeTested() {
    try {
       //Some logic that throws an exception
    }
    catch(Exception e) {
      //Logic dealing with an exception
    }
}
</code>```

<p>Well, with ExpectedException we can check if the method under test has thrown any exception, but how to check it the exception has occurred when method in not throwing, but catching it? </p>

答:
(If you cannot verify the logic dealing with the exception, for example it's some log) In your test:

mock the "Some logic that throws an exception" to throw some exception

call the methodToBeTested

test is OK if no exception is thrown during the call (and if there's one the test will fail automatically if using junit)

verify the mocked "logic" [optional]

Body:
public void methodToBeTested() {
    try {
       //Some logic that throws an exception
    }
    catch(Exception e) {
      //Logic dealing with an exception
    }
}

Well, with ExpectedException we can check if the method under test has thrown any exception, but how to check it the exception has occurred when method in not throwing, but catching it?


问:
Connecting to WMI Remotely with C# to a non-domain PC not working
I use the  Microsoft.Management.Infrastructure namespace to connect to remote computers to get WMI information and it works. But when I try to connect to a non-domain PC it does not work. Can anyone pinpoint what I am doing wrong.
Here is the code:

```<code>string computer = "Computer_B";
string domain = "WORKGROUP";
string username = ".\\LocalAdminUserName";
string plaintextpassword;

Console.WriteLine("Enter password:");
plaintextpassword = Console.ReadLine();

SecureString securepassword = new SecureString();
foreach (char c in plaintextpassword)
{
    securepassword.AppendChar(c);
}

CimCredential Credentials = new
CimCredential(PasswordAuthenticationMechanism.Default, domain,
username,securepassword);

WSManSessionOptions SessionOptions = new WSManSessionOptions();
SessionOptions.AddDestinationCredentials(Credentials);

CimSession Session = CimSession.Create(computer, SessionOptions);

var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_LogicalDisk");

 // Loop through all volumes
 foreach (CimInstance oneVolume in allVolumes)
 {
       Console.Writeline(oneVolume.CimInstanceProperties["SystemName"].Value.ToString());
 }
</code>```

I am not sure what to take as paramaters for domain and username for a local computer. I have already done/tryed the following:

run winrm quickconfig on the remote local computer

use PasswordAuthenticationMechanism.Negotiate cause I have read Kerberos only

works for domain users and password

added the computer I run the code on to the TrustedHosts on the local computer with winrm config. Also tryed adding * to the TrustedHosts

Used for username="computer_B\LocalAdminUserName". I have also tryed with domain=""

Any suggestions what I am doing wrong?

The error I keep getting is: WinRM cannot process the request. The following error with error code 0x8009030e occurred while using Negotiate authentication: A specified logon session does not exist. It may already have been terminated.

 This can occur if the provided credentials are not valid on the target server, or if the server identity could not be verified.  If you trust the server identity, add the server name to the TrustedHosts list, and then retry the request. Use winrm.cmd to view or edit the TrustedHosts list. Note that computers in the TrustedHosts list might not be authenticated. For more information about how to edit the TrustedHosts list, run the following command: winrm help config.

答:
Try out the code below, this is working on impersonation logic.</p>

```<code>ConnectionOptions cOption = new ConnectionOptions();
                ManagementScope scope = null;
                Boolean isLocalConnection = isLocalhost(machine);

                if (isLocalConnection)
                {
                    scope = new ManagementScope(nameSpaceRoot + "\\" + managementScope, cOption);
                }
                else
                {
                    scope = new ManagementScope("\\\\" + machine + "\\" + nameSpaceRoot + "\\" + managementScope, cOption);
                }

                if (!String.IsNullOrEmpty(ACTIVE_DIRECTORY_USERNAME) && !String.IsNullOrEmpty(ACTIVE_DIRECTORY_PASSWORD) && !isLocalConnection)
                {
                    scope.Options.Username = ACTIVE_DIRECTORY_USERNAME;
                    scope.Options.Password = ACTIVE_DIRECTORY_PASSWORD;
                }
                scope.Options.EnablePrivileges = true;
                scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
                scope.Options.Impersonation = ImpersonationLevel.Impersonate;
                scope.Connect();
</code>```

Body:
I use the  Microsoft.Management.Infrastructure namespace to connect to remote computers to get WMI information and it works. But when I try to connect to a non-domain PC it does not work. Can anyone pinpoint what I am doing wrong.
Here is the code:

string computer = "Computer_B";
string domain = "WORKGROUP";
string username = ".\\LocalAdminUserName";
string plaintextpassword;

Console.WriteLine("Enter password:");
plaintextpassword = Console.ReadLine();

SecureString securepassword = new SecureString();
foreach (char c in plaintextpassword)
{
    securepassword.AppendChar(c);
}

CimCredential Credentials = new
CimCredential(PasswordAuthenticationMechanism.Default, domain,
username,securepassword);

WSManSessionOptions SessionOptions = new WSManSessionOptions();
SessionOptions.AddDestinationCredentials(Credentials);

CimSession Session = CimSession.Create(computer, SessionOptions);

var allVolumes = Session.QueryInstances(@"root\cimv2", "WQL", "SELECT * FROM Win32_LogicalDisk");

 // Loop through all volumes
 foreach (CimInstance oneVolume in allVolumes)
 {
       Console.Writeline(oneVolume.CimInstanceProperties["SystemName"].Value.ToString());
 }

I am not sure what to take as paramaters for domain and username for a local computer. I have already done/tryed the following:

run winrm quickconfig on the remote local computer

use PasswordAuthenticationMechanism.Negotiate cause I have read Kerberos only

works for domain users and password

added the computer I run the code on to the TrustedHosts on the local computer with winrm config. Also tryed adding * to the TrustedHosts

Used for username="computer_B\LocalAdminUserName". I have also tryed with domain=""

Any suggestions what I am doing wrong?

The error I keep getting is: WinRM cannot process the request. The following error with error code 0x8009030e occurred while using Negotiate authentication: A specified logon session does not exist. It may already have been terminated.

 This can occur if the provided credentials are not valid on the target server, or if the server identity could not be verified.  If you trust the server identity, add the server name to the TrustedHosts list, and then retry the request. Use winrm.cmd to view or edit the TrustedHosts list. Note that computers in the TrustedHosts list might not be authenticated. For more information about how to edit the TrustedHosts list, run the following command: winrm help config.

Body:
Try out the code below, this is working on impersonation logic.

ConnectionOptions cOption = new ConnectionOptions();
                ManagementScope scope = null;
                Boolean isLocalConnection = isLocalhost(machine);

                if (isLocalConnection)
                {
                    scope = new ManagementScope(nameSpaceRoot + "\\" + managementScope, cOption);
                }
                else
                {
                    scope = new ManagementScope("\\\\" + machine + "\\" + nameSpaceRoot + "\\" + managementScope, cOption);
                }

                if (!String.IsNullOrEmpty(ACTIVE_DIRECTORY_USERNAME) && !String.IsNullOrEmpty(ACTIVE_DIRECTORY_PASSWORD) && !isLocalConnection)
                {
                    scope.Options.Username = ACTIVE_DIRECTORY_USERNAME;
                    scope.Options.Password = ACTIVE_DIRECTORY_PASSWORD;
                }
                scope.Options.EnablePrivileges = true;
                scope.Options.Authentication = AuthenticationLevel.PacketPrivacy;
                scope.Options.Impersonation = ImpersonationLevel.Impersonate;
                scope.Connect();


问:
C - Null Terminating char doesnt stop printing
in this part of code:

```<code>char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);
</code>```

it's printing:

```<code>Data: 260130128
</code>```

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?

答:
There are 2 crucial problems with your code.

Firstly, data isn't initialised. It's just pointing at some random point in memory. You should either allocate some memory to store it using malloc like

```<code>char *data=malloc(200);
</code>```

or just declare it as an array like you've done with num.

```<code>char data[200];
</code>```

Secondly, when you first strcat into data, it's not NUL terminated so you're appending potentially into random garbage data. You can either replace that first strcat with a strcpy (which makes the most sense)

```<code>strcpy(data, num);
</code>```

or make sure that data[0] equals \0

```<code>data[0]='\0';
strcat(data,num);
</code>```

You don't need to do strcat(data, "\0"); as strcat and strcpy will ensure that data is correctly NUL terminated.

Body:
in this part of code:

char* data;
char num[10];

sprintf(num, "%d", 260);
strcat(data, num);
strcat(data, "\0");

sprintf(num, "%d", 130);
strcat(data, num);

sprintf(num, "%d", 128);
strcat(data, num);

printf("Data: %s", data);

it's printing:

Data: 260130128

Why does this happen? The null terminator character shouldnt terminate the printing?

Thank you

Edits:

The data has been initialized before, I am getting it from a function.

Why does not print only 260? How can I do it?

Body:
There are 2 crucial problems with your code.

Firstly, data isn't initialised. It's just pointing at some random point in memory. You should either allocate some memory to store it using malloc like

char *data=malloc(200);

or just declare it as an array like you've done with num.

char data[200];

Secondly, when you first strcat into data, it's not NUL terminated so you're appending potentially into random garbage data. You can either replace that first strcat with a strcpy (which makes the most sense)

strcpy(data, num);

or make sure that data[0] equals \0

data[0]='\0';
strcat(data,num);

You don't need to do strcat(data, "\0"); as strcat and strcpy will ensure that data is correctly NUL terminated.


问:
Path.Combine for URLs?
Path.Combine is handy, but is there a similar function in the .NET framework for URLs?

I'm looking for syntax like this:

```<code>Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")
</code>```

which would return:

"http://MyUrl.com/Images/Image.jpg"

答:
Why not just use the following.</p>

```<code>System.IO.Path.Combine(rootUrl, subPath).Replace(@"\", "/")
</code>```

OwnerDisplayName: Brian MacKay

Title: Path.Combine for URLs?

Body:
Path.Combine is handy, but is there a similar function in the .NET framework for URLs?

I'm looking for syntax like this:

Url.Combine("http://MyUrl.com/", "/Images/Image.jpg")

which would return:

"http://MyUrl.com/Images/Image.jpg"

LastEditorDisplayName: Ryan

Body:
Why not just use the following.

System.IO.Path.Combine(rootUrl, subPath).Replace(@"\", "/")


问:
Ansible create postgresql user with access to all tables?
This should be very simple. I want to make an Ansible statement to create a Postgres user that has connection privileges to a specific database and select/insert/update/delete privileges to all tables within that specific database. I tried the following:

```<code>  - name: Create postgres user for my app
    become: yes
    become_user: postgres
    postgresql_user:
      db: "mydatabase"
      name: "myappuser"
      password: "supersecretpassword"
      priv: CONNECT/ALL:SELECT,INSERT,UPDATE,DELETE
</code>```

I get relation \"ALL\" does not exist

If I remove ALL:, I get Invalid privs specified for database: INSERT UPDATE SELECT DELETE

答:
What I had to do was first create the user and then grant the privileges separately. It's working like a charm.</p>

```<code> - name: Create postgres user for my app
    become: yes
    become_user: postgres
    postgresql_user:
      name: "myappuser"
      password: "supersecretpassword"

  - name: Ensure we have access from the new user
    become: yes
    become_user: postgres
    postgresql_privs:
      db: mydatabase
      role: myappuser
      objs: ALL_IN_SCHEMA
      privs: SELECT,INSERT,UPDATE,DELETE
</code>```

Body:
This should be very simple. I want to make an Ansible statement to create a Postgres user that has connection privileges to a specific database and select/insert/update/delete privileges to all tables within that specific database. I tried the following:

  - name: Create postgres user for my app
    become: yes
    become_user: postgres
    postgresql_user:
      db: "mydatabase"
      name: "myappuser"
      password: "supersecretpassword"
      priv: CONNECT/ALL:SELECT,INSERT,UPDATE,DELETE

I get relation \"ALL\" does not exist

If I remove ALL:, I get Invalid privs specified for database: INSERT UPDATE SELECT DELETE

Body:
What I had to do was first create the user and then grant the privileges separately. It's working like a charm.

 - name: Create postgres user for my app
    become: yes
    become_user: postgres
    postgresql_user:
      name: "myappuser"
      password: "supersecretpassword"

  - name: Ensure we have access from the new user
    become: yes
    become_user: postgres
    postgresql_privs:
      db: mydatabase
      role: myappuser
      objs: ALL_IN_SCHEMA
      privs: SELECT,INSERT,UPDATE,DELETE


问:
Mouse dragger on keyboard in android
I need to create a keyboard .when i drag over keyboard,a highlighted  pointer should move according to its position on keys.How could i do that?Coding is much better for me.Thanks.</p>

答:
http://organicandroid.blogspot.com/2010/08/starting-to-play-with-graphics.html

this link will tell you how to refresh a view or 2d moving drawing using canvas , thread and all

Title: Mouse dragger on keyboard in android


问:
Builded electron application load node module on runtime
I have a problem with an app based on electron. When I build my electron app with electron-builder it produces a appname.exe file which has probably the html/js/css sources in the exe file or another one in the produced directory. When I try to require a node_module from the developer console in the builded app, the module is not getting found :(.

The app is looking in a file called electron.asar liked it seems for the module. I don't really understand this because over modules are getting found, otherwise, the app would not be able to start anyhow.

Maybe one of you guy's have already faced that problem?

答: yes, the module needs to be listed in the dependencies section in the package.json to be found in the built electron app.</p>


问:
How can I get the foreign field's name in queryset?
I have a Disk model, which has three ForeignKey:

```<code>class Disk(models.Model):
    diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks')  #  "SAS", "SSD" 等
    diskOsType = models.ForeignKey(to=DiskOSType, related_name='disks') # "系统盘" "数据盘" 两种选择
    hostType = models.ForeignKey(to=HostType, related_name='disks', on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 单价

    def __str__(self):
        return self.diskEssenceType.name + "-" + self.hostType.name
    def __unicode__(self):
        return self.diskEssenceType.name + "-" + self.hostType.name
</code>```

I use queryset :

```<code>qs = Disk.objects.filter(hostType=obj)
</code>```

Its queryset data is like bellow, after use model_to_dict convert:

```<code>{
   "price": 5.0,
   "diskOsType": 1,
   "hostType": 6,
   "diskEssenceType": 1,
   "id": 4
   },
</code>```

But I want to get the diskEssenceType's name, and the diskOsType's name, not its id, how to do with that?

This is the reason why I use the model_to_dict:

<Disk: > is not JSON serializable

My model have unicode method:

```<code>class DiskEssenceType(models.Model):
    name = models.CharField(unique=True, max_length=8, default="SSD")  # "SAS", "SSD" 等
    profile = models.CharField(max_length=256)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name
</code>```

答:
You need in your models to define :

```<code>def __unicode__(self):
        return unicode(self.<you return>)
</code>```

then you need in your model hostType to define that:

```<code>class hostType(models.Model):
     name = models.CharField(max_length=10, blank=True, null=True, default="myname")

     def __unicode__(self):
          return unicode(self.name)
</code>```

then when you make queryset you get this:

```<code>qs = Disk.objects.filter(hostType=obj)

{
   "price": 5.0,
   "diskOsType": 1,
   "hostType": "my name",
   "diskEssenceType": 1,
   "id": 4
   },
</code>```

Body:
I have a Disk model, which has three ForeignKey:

class Disk(models.Model):
    diskEssenceType = models.ForeignKey(to=DiskEssenceType, related_name='disks')  #  "SAS", "SSD" 等
    diskOsType = models.ForeignKey(to=DiskOSType, related_name='disks') # "系统盘" "数据盘" 两种选择
    hostType = models.ForeignKey(to=HostType, related_name='disks', on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 单价

    def __str__(self):
        return self.diskEssenceType.name + "-" + self.hostType.name
    def __unicode__(self):
        return self.diskEssenceType.name + "-" + self.hostType.name

I use queryset :

qs = Disk.objects.filter(hostType=obj)

Its queryset data is like bellow, after use model_to_dict convert:

{
   "price": 5.0,
   "diskOsType": 1,
   "hostType": 6,
   "diskEssenceType": 1,
   "id": 4
   },

But I want to get the diskEssenceType's name, and the diskOsType's name, not its id, how to do with that?

This is the reason why I use the model_to_dict:

<Disk: > is not JSON serializable

My model have unicode method:

class DiskEssenceType(models.Model):
    name = models.CharField(unique=True, max_length=8, default="SSD")  # "SAS", "SSD" 等
    profile = models.CharField(max_length=256)

    def __str__(self):
        return self.name
    def __unicode__(self):
        return self.name

Body:
You need in your models to define :

def __unicode__(self):
        return unicode(self.<you return>)

then you need in your model hostType to define that:

class hostType(models.Model):
     name = models.CharField(max_length=10, blank=True, null=True, default="myname")

     def __unicode__(self):
          return unicode(self.name)

then when you make queryset you get this:

qs = Disk.objects.filter(hostType=obj)

{
   "price": 5.0,
   "diskOsType": 1,
   "hostType": "my name",
   "diskEssenceType": 1,
   "id": 4
   },


问:
cakephp3 admin prefix for webroot directory
I have cakephp3 application and i created a prefix named admin

so as cakephp doc said i created a directory in Template and Controller .

now i want to do the same thing for css and images in webroot but as soon as move the files in Admin directory in webroot cakephp don't recognise them.

my (css , js ) files for admin panel and main site are completely different and i want them apart.

how can i move the files (css , js , etc ) for admin prefix in Admin directory

update

Adding ../Admin/css/ before the style name (for css ) is the only way i found working but it isn't clean . I appriciate any idea's thanks

答:
I think you are looking for this! try the below code</p>

```<code><?php echo $this->Html->css('/admin',null,array('inline' => false)); ?>
</code>```

Body:
I think you are looking for this! try the below code

<?php echo $this->Html->css('/admin',null,array('inline' => false)); ?>


问:
ASP.Net MVC 3 Razor: how to create and pass info to a dynamic layout
In other languages (PHP/Python), I am used to creating a class which represents a given HTML page layout.  These classes can have an unlimited number of attributes and dynamic features, such as Navigation (multi level), error messages, info messages, footer text, etc... Most of these items have defaults, but may be overridden on a per-page level.  For example:

```<code>Layout = MainPage()

Layout.Title = "Google Image Search"

Layout.Nav1.Add("Google", "http://www.google.com", Selected=True)
Layout.Nav1.Add("Yahoo", "http://www.yahoo.com")
Layout.Nav1.Add("Bing", "http://www.bing.com")

Layout.Nav2.Add("Google Image Search", "http://......", Selected=True)
Layout.Nav2.Add("Google Shopping Search", "http://......")
Layout.Nav2.Add("Google Video Search", "http://......")
Layout.Nav2.Add("Google Web Search", "http://......")
</code>```

or, handling errors:

```<code>try:
   # do something
except ValidationError as e:
   Layout.Error.Add(e)
</code>```

or a php example:

```<code>$Layout->Info[] = "Your changes have been saved!";
</code>```

My question is: how do I implement similar functionality into ASP.Net MVC 3 Razor (VB)?

So far, I have been able to see how you can use ViewData to pass various bits of data to a view.  Also, I have been working with strongly typed views.

Frankly, I'm not sure who's job it is to have this logic, the controller or the view (or is there a model that should be in there somewhere).

Here is a summary of what I am shooting for:

A single place to initialize the default values for the layout (like the first layer of navigation, etc...)

Strongly typed attributes, such as Public Readonly Property Nav1 as List(of NavElement)

And a single place to render these layout elements (I assume _Layout.vbhtml)

Please forgive the here-and-there of this post...  I'm trying to figure out the "right way" it's done on a platform that is both new (Razor) and new to me (ASP.Net MVC).

General advise very welcome!

答:
It's not difficult! :-)
If layout model is of the same type of the content page, the association is automatic! Here is the simplest example...

This is a test layout:

```<code>@model string
<style>
.test
    {
        background:@Model;
    }
</style>
<div class="test">
    Ciao
</div>
@RenderBody()
</code>```

And this is a test content page

```<code>@{
    Layout = "~/Views/Shared/_Test.cshtml";
}
@model string
...blah blah...
</code>```

Just call the View with something like:

```<code>...
return View("Name", (object)"Green");
</code>```

and it's done! The model is the same in the content page and in the layout page!
Andrea

P.S.: Believe me! This is useful!!! Maybe it's not the best for purists, but it's really useful!!! :-)

Body:
In other languages (PHP/Python), I am used to creating a class which represents a given HTML page layout.  These classes can have an unlimited number of attributes and dynamic features, such as Navigation (multi level), error messages, info messages, footer text, etc... Most of these items have defaults, but may be overridden on a per-page level.  For example:

Layout = MainPage()

Layout.Title = "Google Image Search"

Layout.Nav1.Add("Google", "http://www.google.com", Selected=True)
Layout.Nav1.Add("Yahoo", "http://www.yahoo.com")
Layout.Nav1.Add("Bing", "http://www.bing.com")

Layout.Nav2.Add("Google Image Search", "http://......", Selected=True)
Layout.Nav2.Add("Google Shopping Search", "http://......")
Layout.Nav2.Add("Google Video Search", "http://......")
Layout.Nav2.Add("Google Web Search", "http://......")

or, handling errors:

try:
   # do something
except ValidationError as e:
   Layout.Error.Add(e)

or a php example:

$Layout->Info[] = "Your changes have been saved!";

My question is: how do I implement similar functionality into ASP.Net MVC 3 Razor (VB)?

So far, I have been able to see how you can use ViewData to pass various bits of data to a view.  Also, I have been working with strongly typed views.

Frankly, I'm not sure who's job it is to have this logic, the controller or the view (or is there a model that should be in there somewhere).

Here is a summary of what I am shooting for:

A single place to initialize the default values for the layout (like the first layer of navigation, etc...)

Strongly typed attributes, such as Public Readonly Property Nav1 as List(of NavElement)

And a single place to render these layout elements (I assume _Layout.vbhtml)

Please forgive the here-and-there of this post...  I'm trying to figure out the "right way" it's done on a platform that is both new (Razor) and new to me (ASP.Net MVC).

General advise very welcome!

Body:
It's not difficult! :-)
If layout model is of the same type of the content page, the association is automatic! Here is the simplest example...

This is a test layout:

@model string
<style>
.test
    {
        background:@Model;
    }
</style>
<div class="test">
    Ciao
</div>
@RenderBody()

And this is a test content page

@{
    Layout = "~/Views/Shared/_Test.cshtml";
}
@model string
...blah blah...

Just call the View with something like:

...
return View("Name", (object)"Green");

and it's done! The model is the same in the content page and in the layout page!
Andrea

P.S.: Believe me! This is useful!!! Maybe it's not the best for purists, but it's really useful!!! :-)


问:
How can i merge joins?
I have the following query which works but i would like to improve (performance wise):

.sentence_id and .project_id are indexes.

My goal now is to try to merge the 2 joins on the same tables into a single one (if possible)
How can i do that ?

```<code>SELECT rs.project_id,
               ms.id AS raw_sentence_id,
               rs.sentence AS raw_sentence_text,
               rs.sentence_id AS raw_sentence_text_id,
               rst.tokens AS tokenization_information,
               ns.sentence_id AS normalized_sentence_id,
               ns.sentence AS normalized_sentence_text,
               nst.token_indices
          FROM manual_sentences ms
          JOIN sentences rs ON (ms.original_sentence_id = rs.sentence_id AND rs.project_id = 623483)
     LEFT JOIN sentence_tokens rst ON (ms.original_sentence_id = rst.sentence_id AND rst.project_id = 623483)
          JOIN sentences ns ON (ms.sentence_id = ns.sentence_id AND ns.project_id = 623483)
     LEFT JOIN sentence_tokens nst ON (ms.sentence_id = nst.sentence_id AND nst.project_id = 623483)
     WHERE ms.project_id = 623483
</code>```

答:
You should be able to do that using a conjunction:</p>

```<code>SELECT rs.project_id,
               ms.id AS raw_sentence_id,
               rs.sentence AS raw_sentence_text,
               rs.sentence_id AS raw_sentence_text_id,
               rst.tokens AS tokenization_information,
               ns.sentence_id AS normalized_sentence_id,
               ns.sentence AS normalized_sentence_text,
               nst.token_indices
          FROM manual_sentences ms
          JOIN sentences rs ON (ms.original_sentence_id = rs.sentence_id AND rs.project_id = 623483)
     LEFT JOIN sentence_tokens rst ON (ms.original_sentence_id = rst.sentence_id AND ms.sentence_id = rst.sentence_id AND rst.project_id = 623483)
          JOIN sentences ns ON (ms.sentence_id = ns.sentence_id AND ns.project_id = 623483)
     WHERE ms.project_id = 623483
</code>```

Title: How can i merge joins?

Body:
I have the following query which works but i would like to improve (performance wise):

.sentence_id and .project_id are indexes.

My goal now is to try to merge the 2 joins on the same tables into a single one (if possible)
How can i do that ?

SELECT rs.project_id,
               ms.id AS raw_sentence_id,
               rs.sentence AS raw_sentence_text,
               rs.sentence_id AS raw_sentence_text_id,
               rst.tokens AS tokenization_information,
               ns.sentence_id AS normalized_sentence_id,
               ns.sentence AS normalized_sentence_text,
               nst.token_indices
          FROM manual_sentences ms
          JOIN sentences rs ON (ms.original_sentence_id = rs.sentence_id AND rs.project_id = 623483)
     LEFT JOIN sentence_tokens rst ON (ms.original_sentence_id = rst.sentence_id AND rst.project_id = 623483)
          JOIN sentences ns ON (ms.sentence_id = ns.sentence_id AND ns.project_id = 623483)
     LEFT JOIN sentence_tokens nst ON (ms.sentence_id = nst.sentence_id AND nst.project_id = 623483)
     WHERE ms.project_id = 623483

Body:
You should be able to do that using a conjunction:

SELECT rs.project_id,
               ms.id AS raw_sentence_id,
               rs.sentence AS raw_sentence_text,
               rs.sentence_id AS raw_sentence_text_id,
               rst.tokens AS tokenization_information,
               ns.sentence_id AS normalized_sentence_id,
               ns.sentence AS normalized_sentence_text,
               nst.token_indices
          FROM manual_sentences ms
          JOIN sentences rs ON (ms.original_sentence_id = rs.sentence_id AND rs.project_id = 623483)
     LEFT JOIN sentence_tokens rst ON (ms.original_sentence_id = rst.sentence_id AND ms.sentence_id = rst.sentence_id AND rst.project_id = 623483)
          JOIN sentences ns ON (ms.sentence_id = ns.sentence_id AND ns.project_id = 623483)
     WHERE ms.project_id = 623483


问:
Prestashop 1.7.1 - How to get product price with taxes (VAT)
If I do this in a custom module:

```<code><div class="product-price-and-shipping">
    <span class="price">
        {Tools::displayPrice($product.price)}
    </span>
</div>
</code>```

I get the price without taxes (+21% VAT).

How can I get the product price with taxes included (+21% VAT)

答: You must have a rule or a php misbehaviour somewhere because it's $product.price for full price and $product.price_tax_exc without VAT for product lists.</p>

Body:
If I do this in a custom module:

        {Tools::displayPrice($product.price)}

I get the price without taxes (+21% VAT).

How can I get the product price with taxes included (+21% VAT)


问:
Laravel: How to update packages in storage/framework
I have removed a package with composer remove and it's now removed from composer.json and composer.lock files and also removed from vendor directory. But I noticed that it's still listed in these two files: storage/framework/packages.php and storage/framework/services.php. How can I update/rebuild these files?

Also, when I run php artisan in the root of my project, I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
    Class 'Morilog\Jalali\JalaliServiceProvider' not found

I searched in all the files of the project and found JalaliServiceProvider still listed only in the two above-mentioned files.

答: Try to run composer dump-autoload in the terminal once


问:
How to enable proguard for only one module
I have a payment application with payumoney integration. It was working fine until i added the proguard. Recently I have added Proguard to my build.gradle file (Module: app)

```<code>  ` buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}`
</code>```

After this App gets closed when i proceed to payment. It is working fine when i Changed minifyEnabled to false.

Following is my  Module:PayuMoneySdk Build.gradle File

```<code>`buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }`
</code>```

How can I solve this issue? I can't disable proguard.

Can I enable proguard to only Module:app? And will it solve the issue?

I am new to programming. Please help!!

答:
The solution is to look up for the methods and classess that needs to be exempted and add them to the proguard rules as follows..</p>

```<code>-keep class com.mm.** {*;}
-keep class com.company.** {*;}
-keepclassmembers  class com.mm.** {*;}
-keepclassmembers  class com.company.** {*;}
</code>```

Body:
I have a payment application with payumoney integration. It was working fine until i added the proguard. Recently I have added Proguard to my build.gradle file (Module: app)

  ` buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.config
    }
}`

After this App gets closed when i proceed to payment. It is working fine when i Changed minifyEnabled to false.

Following is my  Module:PayuMoneySdk Build.gradle File

`buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }`

How can I solve this issue? I can't disable proguard.

Can I enable proguard to only Module:app? And will it solve the issue?

I am new to programming. Please help!!

Body:
The solution is to look up for the methods and classess that needs to be exempted and add them to the proguard rules as follows..

-keep class com.mm.** {*;}
-keep class com.company.** {*;}
-keepclassmembers  class com.mm.** {*;}
-keepclassmembers  class com.company.** {*;}


问:
Struts DiskFile.getInputStream() returns ByteArrayInputStream and FileArrayInputStream when file size changes
I was trying to analyse a recently-found issue in my application and realized that my inputStream.reset() method fails because I was trying to operate on FileInputStream.

It seems that my method call For apache's DiskFile.getInputStram() returns ByteArrayInputStream instance (mark supported) or FileInputStream (mark NOT supported) instance based on certain file size threshold.

The code I have to get this inputstream is:

```<code>FormFile file = multipartForm.getFiles().get(0); // It's always one file
InputStream is = file.getInputStream();

// Read the stream and did job
// Now I want to reset it.
// bad coding from my side because I didn't check markSupported

is.reset();

// Got IO error immediately after this. But anything below 256KB is ok
</code>```

I am sure this is mentioned/explained somewhere in Oracle JDK docs or apache's site. but cannot seem to remember any references. Does anyone know if this behaviour makes sense?

答:
I’m not familiar with the Struts API, but to me, it seems that when a return type is InputStream rather than a specific subclass, then you have no guarantees regarding the actual type of the returned stream.

Since calling reset() is only valid when having a preceding mark(readlimit) call, treating an unspecified InputStream type generically is straight-forward:

```<code>InputStream inputStream = …
int readlimit = …

if(!inputStream.markSupported()) {
    inputStream = new BufferedInputStream(inputStream, readlimit);
}

inputStream.mark(readlimit);
// read some date, not more than readlimit
inputStream.reset();
</code>```

Body:
I was trying to analyse a recently-found issue in my application and realized that my inputStream.reset() method fails because I was trying to operate on FileInputStream.

It seems that my method call For apache's DiskFile.getInputStram() returns ByteArrayInputStream instance (mark supported) or FileInputStream (mark NOT supported) instance based on certain file size threshold.

The code I have to get this inputstream is:

FormFile file = multipartForm.getFiles().get(0); // It's always one file
InputStream is = file.getInputStream();

// Read the stream and did job
// Now I want to reset it.
// bad coding from my side because I didn't check markSupported

is.reset();

// Got IO error immediately after this. But anything below 256KB is ok

I am sure this is mentioned/explained somewhere in Oracle JDK docs or apache's site. but cannot seem to remember any references. Does anyone know if this behaviour makes sense?

Body:
I’m not familiar with the Struts API, but to me, it seems that when a return type is InputStream rather than a specific subclass, then you have no guarantees regarding the actual type of the returned stream.

Since calling reset() is only valid when having a preceding mark(readlimit) call, treating an unspecified InputStream type generically is straight-forward:

InputStream inputStream = …
int readlimit = …

if(!inputStream.markSupported()) {
    inputStream = new BufferedInputStream(inputStream, readlimit);
}

inputStream.mark(readlimit);
// read some date, not more than readlimit
inputStream.reset();


问:
jQuery children selector
I have the following markup:

```<code><div class="form-fields">
  <div class="row">
    <span class="info">Info</span>
  </div>
</div>
</code>```

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

答:
```<code>$('.form-fields').children('.row').children('.info')
</code>```

you can test it like:

```<code>$(document).ready(function() {
    alert( $('.form-fields').children('.row').children('.info').length);

});
</code>```

Title: jQuery children selector

Body:
I have the following markup:

    Info

Using the children selector how can I select span.info? I have tried doing:

$('.form-fields').children('.row .info')

But this didn't work for me.

EDIT: Thanks for the answers everyone. If I assign the container DIV as follows:

var parentDiv = $('.form-fields')

Then using the var 'parentDiv' what is the best way to select span.info?

Body:
$('.form-fields').children('.row').children('.info')

you can test it like:

$(document).ready(function() {
    alert( $('.form-fields').children('.row').children('.info').length);

});


问:
use node.js express on iis with iisnode
I got a node.js express application and i need to make it run on my local IIS server so i can send valid http requests to it and work with the responses.

I am using win 10 and IIS 10.

I followed the different guides about working with iisnode in order to use node.js application on IIS.

https://github.com/tjanczuk/iisnode

I also managed to run the tests, so the iisnode is installed, valid and is working together with my IIS.

The "built-in" test is being executed under the default web site which comes with IIS, it creates a new application under it from which there is a working access to the different examples.

My problem is that i am still lacking some information about how to setup my own node.js app on IIS since this information seems to be lacking.
And later on how to overcome issues with invalid http requests.

```<code>HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error
</code>```

答:
I would advice to follow the next guide,

https://harveywilliams.net/blog/installing-iisnode

combined with the official github page of iisnode,
it has all the details about making a simple express node.js app working from scratch with iisnode on IIS.

I would advice to test each part before moving on to the next and once done testing to start first from a minimalistic and simple app of your own and once everything is working build it up from there.

P.S. The reason for this error for me was bad naming when i used express.routing

Title: use node.js express on iis with iisnode

Body:
I got a node.js express application and i need to make it run on my local IIS server so i can send valid http requests to it and work with the responses.

I am using win 10 and IIS 10.

I followed the different guides about working with iisnode in order to use node.js application on IIS.

https://github.com/tjanczuk/iisnode

I also managed to run the tests, so the iisnode is installed, valid and is working together with my IIS.

The "built-in" test is being executed under the default web site which comes with IIS, it creates a new application under it from which there is a working access to the different examples.

My problem is that i am still lacking some information about how to setup my own node.js app on IIS since this information seems to be lacking.
And later on how to overcome issues with invalid http requests.

HTTP status: 500
HTTP subStatus: 1001
HTTP reason: Internal Server Error