问:
Large core dump with no function names in GDB
I'm fairly new to debugging core dumps on Linux, and I'm running into a weird issue. Hoping to get some suggestions.

We're getting occasional crashes on our game servers running on AWS Linux boxes. I set up the boxes to generate core dumps. Often, the dumps are around a few hundred MB -- roughly the size of the program in memory. These I'm able to load in gdb and seemingly get a valid backtrace.

But frequently, we're getting dumps that are multiple GB in size. Usually, when I load these core dumps in gdb, there's no usable info in the backtrace.

Here's an example output:

```<code>> gdb AAPGOrbis core.3871
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.3) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from AAPGOrbis...Reading symbols from <path to>/AAPGOrbis.dbg...done.
done.
[New LWP 3871]
[New LWP 3877]
[New LWP 6557]
[New LWP 3876]
[New LWP 6558]
[New LWP 6559]

warning: Error reading shared library list entry at 0x302e6f732e646165

warning: Error reading shared library list entry at 0x74756d5f64616572
Core was generated by `/opt/aapg/Binaries/Linux/AAPGOrbis aaentry?game=AAGame.AAGamePreGameLobbyDedica'.
Program terminated with signal SIGABRT, Aborted.
#0  0x00007fed61d001f7 in ?? ()
(gdb) bt full
#0  0x00007fed61d001f7 in ?? ()
No symbol table info available.
#1  0x00007fed61d018e8 in ?? ()
No symbol table info available.
#2  0x0000000000000020 in ?? ()
No symbol table info available.
#3  0x0000000000000000 in ?? ()
No symbol table info available.
(gdb)
</code>```

Any ideas as to what might be causing this? I'm wondering if the size of the core dumps coupled with the lack of valid data is indicative of some really bad memory corruption.

Any insight would be greatly appreciated!

答:
warning: Error reading shared library list entry at 0x302e6f732e646165
  warning: Error reading shared library list entry at 0x74756d5f64616572

GDB is attempting to read the list of loaded shared libraries from a clearly bogus address (both of these addresses are ASCII strings ead.so.0read_mut).

The most frequent cause is that you have given GDB the wrong binary: the AAPGOrbis that you give GDB must be exactly the same binary as the one that crashed.

Another possibility is that the shared library list (which is in heap) has indeed been corrupted by the program running amok.

Body:
I'm fairly new to debugging core dumps on Linux, and I'm running into a weird issue. Hoping to get some suggestions.

We're getting occasional crashes on our game servers running on AWS Linux boxes. I set up the boxes to generate core dumps. Often, the dumps are around a few hundred MB -- roughly the size of the program in memory. These I'm able to load in gdb and seemingly get a valid backtrace.

But frequently, we're getting dumps that are multiple GB in size. Usually, when I load these core dumps in gdb, there's no usable info in the backtrace.

Here's an example output:

> gdb AAPGOrbis core.3871
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.3) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from AAPGOrbis...Reading symbols from <path to>/AAPGOrbis.dbg...done.
done.
[New LWP 3871]
[New LWP 3877]
[New LWP 6557]
[New LWP 3876]
[New LWP 6558]
[New LWP 6559]

warning: Error reading shared library list entry at 0x302e6f732e646165

warning: Error reading shared library list entry at 0x74756d5f64616572
Core was generated by `/opt/aapg/Binaries/Linux/AAPGOrbis aaentry?game=AAGame.AAGamePreGameLobbyDedica'.
Program terminated with signal SIGABRT, Aborted.
#0  0x00007fed61d001f7 in ?? ()
(gdb) bt full
#0  0x00007fed61d001f7 in ?? ()
No symbol table info available.
#1  0x00007fed61d018e8 in ?? ()
No symbol table info available.
#2  0x0000000000000020 in ?? ()
No symbol table info available.
#3  0x0000000000000000 in ?? ()
No symbol table info available.
(gdb)

Any ideas as to what might be causing this? I'm wondering if the size of the core dumps coupled with the lack of valid data is indicative of some really bad memory corruption.

Any insight would be greatly appreciated!


来源: stackexchange

问:
sed regular expression to fix css minification
I'm currently working on a minification task as post commit hook. I'm using the current version of yui-compressor for CSS-minification.

Bad thing about the current version of yui-compressor:
It breaks certain CSS3-rules that need whitespaces to function properly. (calc(10px + 10px))

To fix the issue i wrote a regular expression that should replace every occurence of calc(...) after compression.

my solution so far is the following RegEx:

Match:    /calc\((.*?)([\/\+\-\*])(.*?)\)/g

Replace:  calc(\1 \2 \3)

I used two online tools to validate my regular expression:

https://regex101.com/

https://regexr.com/

It also works in PHP. But as soon as i use "sed" only the last occurence per line is being replaced:

Compressed CSS: (before replace with regular expression)

```<code>.test{width:calc(1px+1px)}.test2{left:calc(4%+140px)}.test3{width:calc(1px+1px)}

.test{width:calc(1px-1px)}.test2{left:calc(4%-140px)}.test3{width:calc(1px-1px)}

.test{width:calc(1px*1px)}.test2{left:calc(4%*140px)}.test3{width:calc(1px*1px)}

.test{width:calc(1px/1px)}.test2{left:calc(4%/140px)}.test3{width:calc(1px/1px)}
</code>```

CSS after regular expression: (and correct result)

```<code>.test{width:calc(1px + 1px)}.test2{left:calc(4% + 140px)}.test3{width:calc(1px + 1px)}

.test{width:calc(1px - 1px)}.test2{left:calc(4% - 140px)}.test3{width:calc(1px - 1px)}

.test{width:calc(1px * 1px)}.test2{left:calc(4% * 140px)}.test3{width:calc(1px * 1px)}

.test{width:calc(1px / 1px)}.test2{left:calc(4% / 140px)}.test3{width:calc(1px / 1px)}
</code>```

sed in debian 8 - (loading the same rules from a file):

```<code>sed -r "s/calc\((.*?)([\/\+\-\*])(.*?)\)/calc(\1 \2 \3)/g" style.css
</code>```

prints the following:

```<code>.test{width:calc(1px+1px)}.test2{left:calc(4%+140px)}.test3{width:calc(1px + 1px)}
.test{width:calc(1px-1px)}.test2{left:calc(4%-140px)}.test3{width:calc(1px-1px)}
.test{width:calc(1px*1px)}.test2{left:calc(4%*140px)}.test3{width:calc(1px * 1px)}
.test{width:calc(1px/1px)}.test2{left:calc(4%/140px)}.test3{width:calc(1px / 1px)}
</code>```

It doesn't seem to work with sed. Does anyone have a clue what the heck is going on?

Thanks in advance!

答:
You are trying to use PCRE non-greedy repetition .*?, but sed supports only POSIX BRE and ERE, which don't define the non-greedy extension.

Instead, you have to modify your regular expression. In your case, you could use [^-+*/]* for the first captured group (left operand) -- to match everything until the operator, and [^)]* to match the second operand -- everything until the closing parenthesis. This will produce the output you expect:

```<code>sed -E 's/calc\(([^-+*/]*)([-+*/])([^)]*)\)/calc(\1 \2 \3)/g' style.css
#                ^^^^^^^^  ^^^^^^  ^^^^^
#            left operand    op    right operand
#            all until op          all until )
</code>```

Note the -E is equivalent to -r, but is also works in non-GNU sed. Also, you don't need to escape your operators inside the brackets. In fact, almost nothing has to be escaped inside the brackets -- except the closing bracket if not supplied as the first character, and ^ if supplied as the first character.

The output you were getting is easy to explain when you note the .*? is treated as a greedy .*, repeated zero or more times (?) -- The first .*? captures everything until the last operator in line, and the second .*? will capture the last operand, therefore "expanding" only the last calc expression in each line.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on a minification task as post commit hook. I'm using the current version of yui-compressor for CSS-minification.

Bad thing about the current version of yui-compressor:
It breaks certain CSS3-rules that need whitespaces to function properly. (calc(10px + 10px))

To fix the issue i wrote a regular expression that should replace every occurence of calc(...) after compression.

my solution so far is the following RegEx:

Match:    /calc\((.*?)([\/\+\-\*])(.*?)\)/g

Replace:  calc(\1 \2 \3)

I used two online tools to validate my regular expression:

https://regex101.com/

https://regexr.com/

It also works in PHP. But as soon as i use "sed" only the last occurence per line is being replaced:

Compressed CSS: (before replace with regular expression)

.test{width:calc(1px+1px)}.test2{left:calc(4%+140px)}.test3{width:calc(1px+1px)}

.test{width:calc(1px-1px)}.test2{left:calc(4%-140px)}.test3{width:calc(1px-1px)}

.test{width:calc(1px*1px)}.test2{left:calc(4%*140px)}.test3{width:calc(1px*1px)}

.test{width:calc(1px/1px)}.test2{left:calc(4%/140px)}.test3{width:calc(1px/1px)}

CSS after regular expression: (and correct result)

.test{width:calc(1px + 1px)}.test2{left:calc(4% + 140px)}.test3{width:calc(1px + 1px)}

.test{width:calc(1px - 1px)}.test2{left:calc(4% - 140px)}.test3{width:calc(1px - 1px)}

.test{width:calc(1px * 1px)}.test2{left:calc(4% * 140px)}.test3{width:calc(1px * 1px)}

.test{width:calc(1px / 1px)}.test2{left:calc(4% / 140px)}.test3{width:calc(1px / 1px)}

sed in debian 8 - (loading the same rules from a file):

sed -r "s/calc\((.*?)([\/\+\-\*])(.*?)\)/calc(\1 \2 \3)/g" style.css

prints the following:

.test{width:calc(1px+1px)}.test2{left:calc(4%+140px)}.test3{width:calc(1px + 1px)}
.test{width:calc(1px-1px)}.test2{left:calc(4%-140px)}.test3{width:calc(1px-1px)}
.test{width:calc(1px*1px)}.test2{left:calc(4%*140px)}.test3{width:calc(1px * 1px)}
.test{width:calc(1px/1px)}.test2{left:calc(4%/140px)}.test3{width:calc(1px / 1px)}

It doesn't seem to work with sed. Does anyone have a clue what the heck is going on?

Thanks in advance!

Body:
You are trying to use PCRE non-greedy repetition .*?, but sed supports only POSIX BRE and ERE, which don't define the non-greedy extension.

Instead, you have to modify your regular expression. In your case, you could use [^-+*/]* for the first captured group (left operand) -- to match everything until the operator, and [^)]* to match the second operand -- everything until the closing parenthesis. This will produce the output you expect:

sed -E 's/calc\(([^-+*/]*)([-+*/])([^)]*)\)/calc(\1 \2 \3)/g' style.css
#                ^^^^^^^^  ^^^^^^  ^^^^^
#            left operand    op    right operand
#            all until op          all until )

Note the -E is equivalent to -r, but is also works in non-GNU sed. Also, you don't need to escape your operators inside the brackets. In fact, almost nothing has to be escaped inside the brackets -- except the closing bracket if not supplied as the first character, and ^ if supplied as the first character.

The output you were getting is easy to explain when you note the .*? is treated as a greedy .*, repeated zero or more times (?) -- The first .*? captures everything until the last operator in line, and the second .*? will capture the last operand, therefore "expanding" only the last calc expression in each line.


问:
In c++ why is pass by reference is directed by callee rather than by caller
In c++, the function signature defines that it will take the arguments by reference or value. Isn’t it the caller should decide what it wants to pass by reference or value?
Suppose caller does not want the function to modify its values, and is unsure of what the calle is doing inside its function. Then the caller does not have a right to say that the arguments should not be modified.

How is this C++ definiton justified?

答:
Call-by-reference vs. call-by-value isn't primarily about "modification" vs. "read-only". const is for indicating if a parameter is read-only or not. The choice of call-by-reference vs. call-by-value in function design is more often about the performance impacts.

For example, an int is usually passed-in-register while a int * would pass the pointer in-register but require a dereference to access. This is most obvious in structures/classes where passing-by-value will involve copying chunks of memory larger than a machine word and/or calling constructors/destructors on temporaries.

For example, this function requires temporary generation, a ctor/dotr cycle, possibly with heap allocation on every call invocation:

```<code>void foo(const std::string s);
</code>```

While this one avoids additional temporaries while still being read-only:

```<code>void foo(const std::string& s);
</code>```

The design choices of how the function takes parameters is explicitly visible to the caller so that the developer can in turn make their own performance-related tradeoffs in how it's used. C/C++ code performance is in large part based on putting data in the right place, and passing references to it in the right way.

As for "how is this justified in C++" questions, see Stroustrup, "The Design and Evolution of C++", Addison-Wesley (1994)

Body:
Call-by-reference vs. call-by-value isn't primarily about "modification" vs. "read-only". const is for indicating if a parameter is read-only or not. The choice of call-by-reference vs. call-by-value in function design is more often about the performance impacts.

For example, an int is usually passed-in-register while a int * would pass the pointer in-register but require a dereference to access. This is most obvious in structures/classes where passing-by-value will involve copying chunks of memory larger than a machine word and/or calling constructors/destructors on temporaries.

For example, this function requires temporary generation, a ctor/dotr cycle, possibly with heap allocation on every call invocation:

void foo(const std::string s);

While this one avoids additional temporaries while still being read-only:

void foo(const std::string& s);

The design choices of how the function takes parameters is explicitly visible to the caller so that the developer can in turn make their own performance-related tradeoffs in how it's used. C/C++ code performance is in large part based on putting data in the right place, and passing references to it in the right way.

As for "how is this justified in C++" questions, see Stroustrup, "The Design and Evolution of C++", Addison-Wesley (1994)


问:
How to remove image from browser cache
In my web app, I have a large collection of thumbnails, the user is able to select a thumbnail and client side recrop from the original image to recreate a new thumbnail.

That's fine, in my app, I just set the newly created image instantly to the image source, without reloading it from the server, and next to this, the new image is uploaded to the server. This is to ensure a very responsive feeling. The problem is that when to user refreshes the page, he sees the cached old version of the thumbnail.

I know I could use some image.jpg?sometimestamp to be sure the browser has to download a new version of the thumbnail, but as I said, the app needs to be very responsive, even on small &slow internet connections. (Thats why the app in itself is stored on the user's computer and not downloaded live. Only uploads, downloads and jsons are transitting)

The ideal solution would be to be able to tell the browser : remove this particular file from your cache : someurl.com/somefolder/image.jpg, so that the browser has to fetch it again when it needs it. is this possible and how?

So I'm not asking how not to cache files or how to force re-verification each call, I'm asking how I could remove some particular file from browser's cache.

ps: this can be a webkit-only solution as this is the only platform it is running on.(it is actually a qtwebkit on a Qt project.

答:
Sorry for necropost, but I think it could be helpful for others in the same situation:

When your upload is done, perform an AJAX get request with no-cache header.

By specifing this in the REQUEST, you tell the browser to ignore cache and to perform a new request to server.

Assuming I have a cached image at /images/jondoe.jpg, it could be like this :

Code (using Axios):

```<code>Axios.post('/upload/new-image', FormDataObject).then(() => {
  Axios.get('/images/jondoe.jpg', {headers: {'Cache-Control': 'no-cache'}}).then(reloadPageFunction)
// Now you'll have a new image in your cache
})
</code>```

Title: How to remove image from browser cache

Body:
Sorry for necropost, but I think it could be helpful for others in the same situation:

When your upload is done, perform an AJAX get request with no-cache header.

By specifing this in the REQUEST, you tell the browser to ignore cache and to perform a new request to server.

Assuming I have a cached image at /images/jondoe.jpg, it could be like this :

Code (using Axios):

Axios.post('/upload/new-image', FormDataObject).then(() => {
  Axios.get('/images/jondoe.jpg', {headers: {'Cache-Control': 'no-cache'}}).then(reloadPageFunction)
// Now you'll have a new image in your cache
})


问:
Can I include dll in exe (in Visual Studio)?

Possible Duplicate:

  .NET windows application, can it be compressed into a single .exe?

To run my App I need AxInterop.WMPLib.dll and Interop.WMPLib.dll that are located in Debug and Release folder. Is there any way to include those dlls into exe so my app is available in one file only?

答: As long as your DLLs are .NET assemblies, then ILMerge should be able to combine your exe and all of its dependencies into a single file.</p>

OwnerDisplayName: mark

OwnerDisplayName: Princess

ContentLicense: CC BY-SA 2.5


问:
ACE_SOCK_Dgram::open() and errno
I tried to open already opened UDP port and ACE_SOCK_Dgram::open() failed.
As expected, strace shows that bind() failed and errno is set to EADDRINUSE.

To see what error happen, I used ACE_OS::last_error(), but it's not updated.

I'd like to give informative error to user that the port already in use, instead of some general error.

Bonus question - when ACE_OS::last_error() can be used?

Tnx

答: Have you tried just checking errno yourself after the call to open?  It seems to me that if errno == EADDRINUSE you can handle it however you like from there, without needing ACE's help.

Title: ACE_SOCK_Dgram::open() and errno


问:
Moneris - Setting up a Test Hosting Pay Page
I'm trying to make a fix to a moneris website, but I have to change the mode of moneris to test to test the changes before pushing in production.

I'm trying the code on the example page as is and got an error. "Invalid store credentials."

```<code><FORM METHOD="POST" ACTION= https://esqa.moneris.com/HPPDP/index.php >
    <INPUT TYPE="HIDDEN" NAME="ps_store_id" VALUE="AF4Fs1024">
    <INPUT TYPE="HIDDEN" NAME="hpp_key" VALUE="Hsjh4GSr4g">
    <INPUT TYPE="HIDDEN" NAME="charge_total" VALUE="1.00">
    <!--MORE OPTIONAL VARIABLES CAN BE DEFINED HERE -->
    <INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="Click to proceed to Secure Page">
</FORM>
</code>```

So if this is not how you can make a test payment to test the process, how can you?

PS: Seems there's no moneris tag.

答:
You need to goto the developers page of Moneris and create a test environment first Developer Page

After creating the test store you'll need to input the store id and hp key in the values of the form you posted.

Body:
I'm trying to make a fix to a moneris website, but I have to change the mode of moneris to test to test the changes before pushing in production.

I'm trying the code on the example page as is and got an error. "Invalid store credentials."

<FORM METHOD="POST" ACTION= https://esqa.moneris.com/HPPDP/index.php >
    <INPUT TYPE="HIDDEN" NAME="ps_store_id" VALUE="AF4Fs1024">
    <INPUT TYPE="HIDDEN" NAME="hpp_key" VALUE="Hsjh4GSr4g">
    <INPUT TYPE="HIDDEN" NAME="charge_total" VALUE="1.00">

    <INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="Click to proceed to Secure Page">
</FORM>

So if this is not how you can make a test payment to test the process, how can you?

PS: Seems there's no moneris tag.


问:
Ionic 3 - Issue converting JSON data to Object then displaying in list
I am creating a travel application using Ionic 3, Angular and Cordova, with the intention of getting train information from transportAPI.com to display in a list.

The HTML for the list page:

```<code>    <ion-content padding>
  <ion-list>
    <ion-item *ngFor = "let train of trainList">
      {{train.name}}
    </ion-item>
  </ion-list>
</ion-content>
</code>```

The code for my home page, home.ts:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { TravelServiceProvider} from '../../providers/travel-service/travel-service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  trainList = [];

  constructor(private travelService : TravelServiceProvider) {
    this.getTravel();
  }

  getTravel(){
    this.travelService.getTravel().subscribe(data => this.trainList = data);
  }
}
</code>```

My provider class is as follows:

```<code>@Injectable()
export class TravelServiceProvider {

  private url : string = "http://transportapi.com/v3/uk/places.json?query=&type=train_station&app_id=91676f07&app_key=e10dc441385db6f855e3e5ad29bcd6c8";

  constructor(private http: Http) {
    console.log('Hello TravelServiceProvider Provider');
  }

  getTravel(){
    return this.http.get(this.url)
    .do(this.logResponse)
    .map(this.extractData)
    .catch(this.catchError)
  }

  private logResponse(res : Response){
    console.log(res);
  }

  private extractData(res : Response){
    return res.json();
  }

  private catchError(error : Response | any){
    console.log(error);
    return Observable.throw(error.json().error || "Server Error" );
  }
}
</code>```

I am expecting to see the train names in the JSON to be printed in list form, by the *ngFor expression in the HTML, but instead nothing is displayed in place of the {{train.name}}, and I get the error "Error trying to diff '[object Object]'. Only arrays and iterables are allowed".

Any help would be much appreciated.

答:
As the error says you need to provide an array for ngFor , I think you need to access the member property of the response object which is an array, change it as</p>

```<code>this.travelService.getTravel().subscribe((data:any) => this.trainList = data.member);
</code>```

Body:
I am creating a travel application using Ionic 3, Angular and Cordova, with the intention of getting train information from transportAPI.com to display in a list.

The HTML for the list page:

    <ion-content padding>
  <ion-list>
    <ion-item *ngFor = "let train of trainList">
      {{train.name}}
    </ion-item>
  </ion-list>
</ion-content>

The code for my home page, home.ts:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { TravelServiceProvider} from '../../providers/travel-service/travel-service';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  trainList = [];

  constructor(private travelService : TravelServiceProvider) {
    this.getTravel();
  }

  getTravel(){
    this.travelService.getTravel().subscribe(data => this.trainList = data);
  }
}

My provider class is as follows:

@Injectable()
export class TravelServiceProvider {

  private url : string = "http://transportapi.com/v3/uk/places.json?query=&type=train_station&app_id=91676f07&app_key=e10dc441385db6f855e3e5ad29bcd6c8";

  constructor(private http: Http) {
    console.log('Hello TravelServiceProvider Provider');
  }

  getTravel(){
    return this.http.get(this.url)
    .do(this.logResponse)
    .map(this.extractData)
    .catch(this.catchError)
  }

  private logResponse(res : Response){
    console.log(res);
  }

  private extractData(res : Response){
    return res.json();
  }

  private catchError(error : Response | any){
    console.log(error);
    return Observable.throw(error.json().error || "Server Error" );
  }
}

I am expecting to see the train names in the JSON to be printed in list form, by the *ngFor expression in the HTML, but instead nothing is displayed in place of the {{train.name}}, and I get the error "Error trying to diff '[object Object]'. Only arrays and iterables are allowed".

Any help would be much appreciated.

Body:
As the error says you need to provide an array for ngFor , I think you need to access the member property of the response object which is an array, change it as

this.travelService.getTravel().subscribe((data:any) => this.trainList = data.member);


问:
Zookeeper connection error
We have a standalone zookeeper setup on a dev machine. It works fine for every other dev machine except this one testdev machine.

We get this error over and over again when trying to connect to zookeeper through testdev:

```<code>2012-11-09 14:06:53,909 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:53,911 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect
2012-11-09 14:06:55,366 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1058] - Opening socket connection to server zk01.dev.bunchball.net/192.168.8.58:2181
2012-11-09 14:06:55,368 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:55,368 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect
2012-11-09 14:06:57,271 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1058] - Opening socket connection to server zk01.dev.bunchball.net/192.168.8.58:2181
2012-11-09 14:06:57,274 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:57,275 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect
</code>```

We tried restarting the test dev machine, and also restart zookeeper host but nothing worked. We are totally confused why it works perfectly fine with other machines except this one. What might be the cause of this?

答:
Had the same error during setup on a 2 node cluster. I discovered I had mixed up the contents of the myid file versus the server.id=HOST_IP:port entry.

Essentially, if you have two servers (SERVER1 and SERVER2) for which you have created "myid" files in dataDir for zookeeper as below

```<code>SERVER1 (myid)
1

SERVER2 (myid)
2
</code>```

Ensure the entry in your zoo.cfg file corresponds for each of these i.e server.1 should use SERVER1 hostname and server.2 should use SERVER2 hostname followed by the port as below

```<code>SERVER1 (zoo.cfg)
... (other config omitted)
server.1=SERVER1:2888:3888
server.2=SERVER2:2888:3888

SERVER2 (zoo.cfg)
... (other config omitted)
server.1=SERVER1:2888:3888
server.2=SERVER2:2888:3888
</code>```

Just to make sure, I also deleted the version-* folder in the dataDir then restarted Zookeeper to get it working.

Title: Zookeeper connection error

Body:
We have a standalone zookeeper setup on a dev machine. It works fine for every other dev machine except this one testdev machine.

We get this error over and over again when trying to connect to zookeeper through testdev:

2012-11-09 14:06:53,909 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:53,911 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect
2012-11-09 14:06:55,366 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1058] - Opening socket connection to server zk01.dev.bunchball.net/192.168.8.58:2181
2012-11-09 14:06:55,368 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:55,368 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect
2012-11-09 14:06:57,271 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1058] - Opening socket connection to server zk01.dev.bunchball.net/192.168.8.58:2181
2012-11-09 14:06:57,274 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@947] - Socket connection established to zk01.dev.bunchball.net/192.168.8.58:2181, initiating session
2012-11-09 14:06:57,275 - INFO  [main-SendThread(zk01.dev.bunchball.net:2181):ClientCnxn$SendThread@1183] - Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect

We tried restarting the test dev machine, and also restart zookeeper host but nothing worked. We are totally confused why it works perfectly fine with other machines except this one. What might be the cause of this?

Body:
Had the same error during setup on a 2 node cluster. I discovered I had mixed up the contents of the myid file versus the server.id=HOST_IP:port entry.

Essentially, if you have two servers (SERVER1 and SERVER2) for which you have created "myid" files in dataDir for zookeeper as below

SERVER1 (myid)
1

SERVER2 (myid)
2

Ensure the entry in your zoo.cfg file corresponds for each of these i.e server.1 should use SERVER1 hostname and server.2 should use SERVER2 hostname followed by the port as below

SERVER1 (zoo.cfg)
... (other config omitted)
server.1=SERVER1:2888:3888
server.2=SERVER2:2888:3888

SERVER2 (zoo.cfg)
... (other config omitted)
server.1=SERVER1:2888:3888
server.2=SERVER2:2888:3888

Just to make sure, I also deleted the version-* folder in the dataDir then restarted Zookeeper to get it working.


问:
Differentiable round function in Tensorflow?
So the output of my network is a list of propabilities, which I then round using tf.round() to be either 0 or 1, this is crucial for this project.
I then found out that tf.round isn't differentiable so I'm kinda lost there.. :/ </p>

答:
You can use the fact that tf.maximum() and tf.minimum() are differentiable, and the inputs are probabilities from 0 to 1

```<code># round numbers less than 0.5 to zero;
# by making them negative and taking the maximum with 0
differentiable_round = tf.maximum(x-0.499,0)
# scale the remaining numbers (0 to 0.5) to greater than 1
# the other half (zeros) is not affected by multiplication
differentiable_round = differentiable_round * 10000
# take the minimum with 1
differentiable_round = tf.minimum(differentiable_round, 1)
</code>```

Example:

```<code>[0.1,       0.5,     0.7]
[-0.0989, 0.001, 0.20099] # x - 0.499
[0,       0.001, 0.20099] # max(x-0.499, 0)
[0,          10,  2009.9] # max(x-0.499, 0) * 10000
[0,         1.0,     1.0] # min(max(x-0.499, 0) * 10000, 1)
</code>```

Body:
You can use the fact that tf.maximum() and tf.minimum() are differentiable, and the inputs are probabilities from 0 to 1

# round numbers less than 0.5 to zero;
# by making them negative and taking the maximum with 0
differentiable_round = tf.maximum(x-0.499,0)
# scale the remaining numbers (0 to 0.5) to greater than 1
# the other half (zeros) is not affected by multiplication
differentiable_round = differentiable_round * 10000
# take the minimum with 1
differentiable_round = tf.minimum(differentiable_round, 1)

Example:

[0.1,       0.5,     0.7]
[-0.0989, 0.001, 0.20099] # x - 0.499
[0,       0.001, 0.20099] # max(x-0.499, 0)
[0,          10,  2009.9] # max(x-0.499, 0) * 10000
[0,         1.0,     1.0] # min(max(x-0.499, 0) * 10000, 1)


问:
how to define container templated with enum
I need to create a container which holds integer and templated with enum.

```<code> enum Color{R,G,B};

 template<class Color C,//class before color will be removed
 template <class, class = allocator<int>> class Container>
 class MyClass
 {
    Container<int> buffer;
 }
</code>```

I need to create vector and list out of it. Something like:

```<code> MyClass<Color::R, std::list> mbs
 MyClass<Color::G, std::vector> mbs

 //wrong number of template arguments (1, should be 2)
 MyClass<Color C, vector> v1;

 //for contaner
 Container<int>::iterator nth = buffer.begin()
</code>```

答:
You're looking for a non-type template parameter

For your container it would be defined like so:

```<code>template<Color C,
         template<class, class = std::allocator<int>> class Container>
class MyClass{
   Container<int> buffer;
   // ...
};
</code>```

You can create an instance like so:

```<code>MyClass<Color::R, std::vector> instance;
</code>```

You can create an iterator like so:

```<code>typename Container<int>::iterator iter = buffer.begin();
</code>```

typename is required because iterator is a dependent name

Body:
I need to create a container which holds integer and templated with enum.

 enum Color{R,G,B};

 template<class Color C,//class before color will be removed
 template <class, class = allocator<int>> class Container>
 class MyClass
 {
    Container<int> buffer;
 }

I need to create vector and list out of it. Something like:

 MyClass<Color::R, std::list> mbs
 MyClass<Color::G, std::vector> mbs

 //wrong number of template arguments (1, should be 2)
 MyClass<Color C, vector> v1;

 //for contaner
 Container<int>::iterator nth = buffer.begin()

Body:
You're looking for a non-type template parameter

For your container it would be defined like so:

template<Color C,
         template<class, class = std::allocator<int>> class Container>
class MyClass{
   Container<int> buffer;
   // ...
};

You can create an instance like so:

MyClass<Color::R, std::vector> instance;

You can create an iterator like so:

typename Container<int>::iterator iter = buffer.begin();

typename is required because iterator is a dependent name


问:
View Referencing it's self - Laravel 5.5
So I am new to laravel. I am trying to use a view but it keeps referencing its self with links.

See below what I mean

So I have a route "customers"

```<code>Route::get('customers/{cid?}',  [
    'uses' => 'customers@getCustomerView'
])->name('customers');
</code>```

In this route as you can see I reference a controller getCustomerView. With an optional CID as someone might just want to see a list of customers. Then choose their customer. So here is the controller function

```<code>public function getCustomerView($cid = null){
        $activeCustomer = array();
        if(!empty($cid)){
            // do middleware to get customer active detail
            $activeCustomer = array(
                'company' => 'Company '.$cid,
                'fname' => 'Test',
                'lname' => 'test'
            );
        }
        return view('customers.view', [
                'title' => 'Customer List',
                'cid' => $cid,
                'activeCustomer' => $activeCustomer,
                'clist' => [
                    ['company'=>'Company 1', 'fname' => 'Bob', 'lname' => 'Smith'],
                    ['company'=>'Company 2', 'fname' => 'Julie', 'lname' => 'Reid'],
                    ['company'=>'Company 3', 'fname' => 'Tony', 'lname' => 'Tima']
                ]
        ]);
    }
</code>```

When I load http://domain/customers - Everything works fine.

In my customers.view I have the following that loops and put's the array into a table. Later I will be using some middle ware or self function to get data from database. For now I am just using a harden array.

```<code>@foreach($clist as $key=>$customer)
    <tr>
        <td>{{$key+1}}</td>
        <td><a href="customers/{{$key+1}}">{{$customer['company']}}</a></td>
        <td>{{$customer['fname']}}</td>
        <td>{{$customer['lname']}}</td>
    </tr>
@endforeach
</code>```

The problem lies. Once I click on a customer. Page loads fine. http://domain/customers/1 - But if I go to click on another customer it does this

http://domain/customers/1/customers/2 - obviously this would cause an error. So why is it doing this?

How can I prevent it?

答:
use this :

```<code><td><a href="{{ route('customers' , [$key+1]) }}">{{$customer['company']}}</a></td>
</code>```

it will generate a full url like http://domain/customers/1

but you can simply do that :

```<code><td><a href="/customers/{{$key+1}}">{{$customer['company']}}</a></td>
</code>```

Body:
So I am new to laravel. I am trying to use a view but it keeps referencing its self with links.

See below what I mean

So I have a route "customers"

Route::get('customers/{cid?}',  [
    'uses' => 'customers@getCustomerView'
])->name('customers');

In this route as you can see I reference a controller getCustomerView. With an optional CID as someone might just want to see a list of customers. Then choose their customer. So here is the controller function

public function getCustomerView($cid = null){
        $activeCustomer = array();
        if(!empty($cid)){
            // do middleware to get customer active detail
            $activeCustomer = array(
                'company' => 'Company '.$cid,
                'fname' => 'Test',
                'lname' => 'test'
            );
        }
        return view('customers.view', [
                'title' => 'Customer List',
                'cid' => $cid,
                'activeCustomer' => $activeCustomer,
                'clist' => [
                    ['company'=>'Company 1', 'fname' => 'Bob', 'lname' => 'Smith'],
                    ['company'=>'Company 2', 'fname' => 'Julie', 'lname' => 'Reid'],
                    ['company'=>'Company 3', 'fname' => 'Tony', 'lname' => 'Tima']
                ]
        ]);
    }

When I load http://domain/customers - Everything works fine.

In my customers.view I have the following that loops and put's the array into a table. Later I will be using some middle ware or self function to get data from database. For now I am just using a harden array.

@foreach($clist as $key=>$customer)

        {{$key+1}}
        {{$customer['company']}}
        {{$customer['fname']}}
        {{$customer['lname']}}

@endforeach

The problem lies. Once I click on a customer. Page loads fine. http://domain/customers/1 - But if I go to click on another customer it does this

http://domain/customers/1/customers/2 - obviously this would cause an error. So why is it doing this?

How can I prevent it?

Body:
use this :

<td><a href="{{ route('customers' , [$key+1]) }}">{{$customer['company']}}</a></td>

it will generate a full url like http://domain/customers/1

but you can simply do that :

<td><a href="/customers/{{$key+1}}">{{$customer['company']}}</a></td>


问:
CSS: Box Shadow Effect on Scalene Triangle PseudoElement
I am trying to create a box shadow around a scalene triangle that exists as a pseudo element, as shown below. I have tried many ways but cannot seem to get an even shadow below my image.

I have tried putting a second scalene triangle pseudo element with slightly larger dimensions that is grey but since there is no gradient or shadow effect, it is not what I am looking for.

Does anyone have any solutions?

Would really appreciate some ideas; perhaps there is a way to get a border gradient effect on a second pseudo element and underlay it?

.box {
  height: 100px;
  width: 100px;
  background: blue;
  position: relative;
  box-shadow: 0 40px 5px 0 rgba(0, 0, 0, 0.50);
}

.box:after {
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  border-left: 20px solid transparent;
  border-right: 80px solid transparent;
  border-top: 30px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style='width: 300px;height:300px;background: white;'>
  <div class='box'>
  </div>
</div></code>```

答:
What you're looking for is filter!

```<code>filter: drop-shadow(0 0 10px rgba(0, 0, 0, 0.2));
</code>```

Maps the shadow around the visible parts of the element, instead of its box.

Note that this property is significantly different from and incompatible with Microsoft's older "filter" property.

Body:
What you're looking for is filter!

filter: drop-shadow(0 0 10px rgba(0, 0, 0, 0.2));

Maps the shadow around the visible parts of the element, instead of its box.

Note that this property is significantly different from and incompatible with Microsoft's older "filter" property.


问:
New project using Symfony 4 with MongoDB / service not found
I'm trying to create a new Symfony4 project with MongoDB.

First I created a Symfony4 project using this documentation:
https://symfony.com/doc/current/setup.html

Then I included MongoDB using this documentation:
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html

I tried to follow the instructions as exactly as possible (for example I didn't need to add anything to app/AppKernel.php, but MongoDB was automatically added to config/bundles.php).

Now I think everything should work, but my Symfony app doesn't find the MongoDB Service:

```<code>You have requested a non-existent service "doctrine_mongodb".
Did you mean one of these: "http_kernel", "request_stack", "router"?
in ServiceLocator.php (line 48)
</code>```

Controller:

```<code>namespace App\Controller;

use App\Document\Chapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends AbstractController {

    public function createAction() {
        $test = new Chapter();
        $test->setHeadline('Test');

        $dm = $this->get('doctrine_mongodb')->getManager();
        $dm->persist($test);
        $dm->flush();

        return new Response('Created product id '.$test->getId());
    }
}
</code>```

However, If I execute this on the console:

```<code>php bin/console debug:container
</code>```

I get a list of services including these:

```<code>doctrine_mongodb                                                                             Doctrine\Bundle\MongoDBBundle\ManagerRegistry
doctrine_mongodb.odm.default_connection                                                      Doctrine\MongoDB\Connection
doctrine_mongodb.odm.default_document_manager                                                Doctrine\ODM\MongoDB\DocumentManager
doctrine_mongodb.odm.document_manager                                                        alias for "doctrine_mongodb.odm.default_document_manager"
</code>```

So the service seems to be there, but Symfony can't load it from my app.

Any idea how I could solve this?
Is it possible that the Mongo-DB Server connection doesn't work and for some reason it isn't logged and the service just won't load?

答:
Try extending from "Controller" instead "AbstractController".</p>

```<code>class DefaultController extends Controller
</code>```

Body:
I'm trying to create a new Symfony4 project with MongoDB.

First I created a Symfony4 project using this documentation:
https://symfony.com/doc/current/setup.html

Then I included MongoDB using this documentation:
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html

I tried to follow the instructions as exactly as possible (for example I didn't need to add anything to app/AppKernel.php, but MongoDB was automatically added to config/bundles.php).

Now I think everything should work, but my Symfony app doesn't find the MongoDB Service:

You have requested a non-existent service "doctrine_mongodb".
Did you mean one of these: "http_kernel", "request_stack", "router"?
in ServiceLocator.php (line 48)

Controller:

namespace App\Controller;

use App\Document\Chapter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends AbstractController {

    public function createAction() {
        $test = new Chapter();
        $test->setHeadline('Test');

        $dm = $this->get('doctrine_mongodb')->getManager();
        $dm->persist($test);
        $dm->flush();

        return new Response('Created product id '.$test->getId());
    }
}

However, If I execute this on the console:

php bin/console debug:container

I get a list of services including these:

doctrine_mongodb                                                                             Doctrine\Bundle\MongoDBBundle\ManagerRegistry
doctrine_mongodb.odm.default_connection                                                      Doctrine\MongoDB\Connection
doctrine_mongodb.odm.default_document_manager                                                Doctrine\ODM\MongoDB\DocumentManager
doctrine_mongodb.odm.document_manager                                                        alias for "doctrine_mongodb.odm.default_document_manager"

So the service seems to be there, but Symfony can't load it from my app.

Any idea how I could solve this?
Is it possible that the Mongo-DB Server connection doesn't work and for some reason it isn't logged and the service just won't load?

Body:
Try extending from "Controller" instead "AbstractController".

class DefaultController extends Controller


问:
Exclude a list of tests with py.test but on the command line?
I would like to exclude a list (about 5 items) of tests with py.test.

I would like to give this list to py.test via the command line.

I would like to avoid to modify the source.

How to do that?

答:
You could get this to work by creating a conftest.py file:

```<code># content of conftest.py

import pytest
def pytest_addoption(parser):
    parser.addoption("--skiplist", action="store_true",
                     default="", help="skip listed tests")

def pytest_collection_modifyitems(config, items):
    tests_to_skip = config.getoption("--skiplist")
    if not tests_to_skip:
        # --skiplist not given in cli, therefore move on
        return
    skip_listed = pytest.mark.skip(reason="included in --skiplist")
    for item in items:
        if item.name in tests_to_skip:
            item.add_marker(skip_listed)
</code>```

You would use it with:

```<code>$ pytest --skiplist test1 test2
</code>```

Note that if you always skip the same test the list can be defined in conftest.

See also this useful link

Body:
You could get this to work by creating a conftest.py file:

# content of conftest.py

import pytest
def pytest_addoption(parser):
    parser.addoption("--skiplist", action="store_true",
                     default="", help="skip listed tests")

def pytest_collection_modifyitems(config, items):
    tests_to_skip = config.getoption("--skiplist")
    if not tests_to_skip:
        # --skiplist not given in cli, therefore move on
        return
    skip_listed = pytest.mark.skip(reason="included in --skiplist")
    for item in items:
        if item.name in tests_to_skip:
            item.add_marker(skip_listed)

You would use it with:

$ pytest --skiplist test1 test2

Note that if you always skip the same test the list can be defined in conftest.

See also this useful link


问:
Django hosted on Apache - Uploading a file going to wrong location
I have a simple website that allows the user to upload a file to my server. I want the file to be uploaded into my django project folder in a sub directory.

Everything is working fine but when I use the upload feature on my website I get a permissions denied on the folder /var/www BUT the thing is I changed the DocumentRoot to equal /mnt/public/apps - which is where I want my uploaded files to go (the upload creates a sub directory).

I have correct permissions in /mnt/public but I can't figure out how to point django or apache so that my upload goes to the /mnt/public/apps root instead of /var/www

Any help would be greatly appreciated!

答: As Alasdair said in the comments, which was a super quick reply (thanks!), the correct fix for my problem was to add the MEDIA_ROOT variable to my settings.py file.</p>


问:
Need suggestions on best approach to update text entered into multiple textboxes without causing a postback that shifts the page
This is a concept question.  I have a web form with 6 gridviews, below each gridview is a textbox. Each row of the gridview contains a question and 5 radio buttons. When a radio button is ticked or text is entered in the textbox it updates the database immediately with one caveat, the textbox is committed when the user presses the tab key, or refocuses curser outside the textbox, or clicks an unrelated button (basically when a postback or textchanged() event occurs).

The problem: There is a delay during postback when the text is committed to the database causing the user to think they can move to the next textbox only to have the curser return to the previous textbox.  I added code to prevent the curser jumping but the delay is still an annoyance to users during testing. I added a confirmation message (label) to alert the user when it's ok to move on but when the confirmation message disappears at the next postback, usually when the user ticks the next radio button, the gridview shifts up and the user's curser is pointed to a different line of the grid.  This is also annoying users.

Solutions? In my limited experience I have 2 alternatives maybe 3 (below). The reason I did not do either was because I wanted data to update the database as soon as it was typed or ticked.  Since the radio buttons cause an immediate update I didn't want the users to inadvertently think the textboxes did too   and forget to click a button to commit the text. Since entering text in the textboxes is optional, I don't have a way to validate if the user is done completing the form and remind them to click a button to commit their text input.

Put a button by each textbox to commit the text

Use one button to commit all textbox data when form is complete

Find a way to put a placeholder where the confirmation label is when its hidden so it doesn't shift on postback.

I'm starting to think one Submit button is the way to go and let the user think that is what saves the data? Simple.

At any rate is there a better way to achieve my goals of having input updated in database immediately without annoying delays (postbacks) and grid shifting at inopportune times?

答: In my case I changed the textbox AutoPostBack property to False and removed all code in the text_changed() event for all textboxes. I am committing the text when a Submit button is clicked. (The radio buttons still commit to db immediately when selected).  In the end, I think users are conditioned to click a submit or save button when they finish filling out a form anyway.


问:
fetch's fileReader blocks React Native props from updating
I am using the fetch API to send a base64 photo to my backend for manipulation, and then I return it. I want to read the photo and write it to my cameraRoll, which I can do.  The end goal is to share the photo to instagram, but for some reason the fileReader stops the props from updating.  Here is the method:

```<code>uploadImageAsync = async (uri, setImageText) => {
    let apiUrl = "some url"

    let uriParts = uri.split('.');
    let fileType = uri[uri.length - 1];

    let formData = new FormData();
    formData.append('photo', {
        uri,
        name: `photo`,
        type: `image/${fileType}`,
    });
    let options = {
        method: 'POST',
        body: formData,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
        },
    };
    return fetch(apiUrl, options)
        .then(response => {
            return response.blob();
        })
        .then( async myBlob => {
            const fileReader = new FileReader();
            fileReader.readAsText(myBlob);
            const objectURL = URL.createObjectURL(myBlob);
            fileReader.addEventListener('loadend', async (e) => {
                const text = e.srcElement.result;
                this.props.setImageText(text);
                let source = { uri: 'data:image/jpeg;base64,' + text };
                const cameraRollAddress = await CameraRoll.saveToCameraRoll(source.uri, 'photo');
                let instagramURL = `instagram://library?AssetPath=${cameraRollAddress}`;
                Linking.openURL(instagramURL);
                return;
            });
        });
}
</code>```

The photo saves to the camera roll, but the props are not updated, so the Linking doesn't happen until I press another button somewhere on the screen.

For instance, if I navigate to another screen, Instagram will open with the photo ready to be shared.  It doesn't matter what props I try to update, even something as simple as changing the text on the screen: when I use the fileReader, the props won't update.  When I take that line out, the props will update, but I need it to get the base64 text string for the image.

Also, the base64 text string does save to the state (I'm actually using Redux), but nothing is updated.

答:
Not sure if uri is in your state but a similar question was asked before:

My Redux state has changed, why doesn't React trigger a re-render?

You should never mutate any part of your state in Redux.
Up at the very top of your file you are doing the following:

```<code>let uriParts = uri.split('.');
</code>```

This is mutating your state which will prevent it from updating when you use uri below in "addEventListener".

As said in the link, try returning a new uri instead of changing the current one and mutating your state.

Let me know if this helps!

Body:
I am using the fetch API to send a base64 photo to my backend for manipulation, and then I return it. I want to read the photo and write it to my cameraRoll, which I can do.  The end goal is to share the photo to instagram, but for some reason the fileReader stops the props from updating.  Here is the method:

uploadImageAsync = async (uri, setImageText) => {
    let apiUrl = "some url"

    let uriParts = uri.split('.');
    let fileType = uri[uri.length - 1];

    let formData = new FormData();
    formData.append('photo', {
        uri,
        name: `photo`,
        type: `image/${fileType}`,
    });
    let options = {
        method: 'POST',
        body: formData,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
        },
    };
    return fetch(apiUrl, options)
        .then(response => {
            return response.blob();
        })
        .then( async myBlob => {
            const fileReader = new FileReader();
            fileReader.readAsText(myBlob);
            const objectURL = URL.createObjectURL(myBlob);
            fileReader.addEventListener('loadend', async (e) => {
                const text = e.srcElement.result;
                this.props.setImageText(text);
                let source = { uri: 'data:image/jpeg;base64,' + text };
                const cameraRollAddress = await CameraRoll.saveToCameraRoll(source.uri, 'photo');
                let instagramURL = `instagram://library?AssetPath=${cameraRollAddress}`;
                Linking.openURL(instagramURL);
                return;
            });
        });
}

The photo saves to the camera roll, but the props are not updated, so the Linking doesn't happen until I press another button somewhere on the screen.

For instance, if I navigate to another screen, Instagram will open with the photo ready to be shared.  It doesn't matter what props I try to update, even something as simple as changing the text on the screen: when I use the fileReader, the props won't update.  When I take that line out, the props will update, but I need it to get the base64 text string for the image.

Also, the base64 text string does save to the state (I'm actually using Redux), but nothing is updated.

Body:
Not sure if uri is in your state but a similar question was asked before:

My Redux state has changed, why doesn't React trigger a re-render?

You should never mutate any part of your state in Redux.
Up at the very top of your file you are doing the following:

let uriParts = uri.split('.');

This is mutating your state which will prevent it from updating when you use uri below in "addEventListener".

As said in the link, try returning a new uri instead of changing the current one and mutating your state.

Let me know if this helps!


问:
matching string to filenames with regex (java 1.6)
I have a bunch of images with names such as nineDiamonds.gif and aceHearts.gif along with a "Card" class for playing card faces.

In the constructor, I want to pass a String of the card name and be able to create a JPanel with the right image. Easy enough, but I want to be able to pass things such as:

"9 of hearts" => nineHearts.gif

"9 hearts" => nineHearts.gif

"nine of Hearts" => nineHearts.gif

Integer.toString(9) + "hearts" => nineHearts.gif

Integer.toString(1) + "hearts" => aceHearts.gif

"Ace of hearts" => aceHearts.gif

I understand I can overload the constructor and match things up with a switch and what not, but what I am really after is am elegant, functional style solution, something along the lines of:

```<code>String fileName = name.replaceAll("magic regex") + ".gif";
</code>```

Thanks!

答:
One .replaceAll() is not going to be enough.

Lowercase your string. (\S+)\s*(?:of)?\s*(hearts|clubs|diamonds|spades) will parse 9 of hearts and 9hearts to ("9", "hearts"), and aceofclubs to ("ace", "clubs"). Create a map that maps "1" to "ace", ... "13" to "king"; pass first groups of the match through it. Then creation of the filename becomes trivial.

Body:
I have a bunch of images with names such as nineDiamonds.gif and aceHearts.gif along with a "Card" class for playing card faces.

In the constructor, I want to pass a String of the card name and be able to create a JPanel with the right image. Easy enough, but I want to be able to pass things such as:

"9 of hearts" => nineHearts.gif

"9 hearts" => nineHearts.gif

"nine of Hearts" => nineHearts.gif

Integer.toString(9) + "hearts" => nineHearts.gif

Integer.toString(1) + "hearts" => aceHearts.gif

"Ace of hearts" => aceHearts.gif

I understand I can overload the constructor and match things up with a switch and what not, but what I am really after is am elegant, functional style solution, something along the lines of:

String fileName = name.replaceAll("magic regex") + ".gif";

Thanks!


问:
Bootstrap grid 2x2 stops growing horizontally
I'm having some problems with my layout.
Im trying to make a menu which has a header and a 2x2 tile grid, which has to be 1x4 on smaller screens.

Goal - Big screen
(Red = Header, Green = Tile)

On a small screen everything works fine, it shows the headerbar, and the 4 tiles underneath like this:

Goal and actual - Small screen

When I resize the screen to make it bigger, at some point it gets to the 2x2 grid but when I resize it to go even bigger the grid stops growing horizontally, which makes it look like this:

Actual - Big screen

HTML

```<code><div class="overlay-content" id="container-fluid">
    <div class="row">
        <div class="tile col-md-6 border">
            <a href="#">asdf</a>
         </div>
         <div class="tile col-md-6 border">
             <a href="#">asfd</a>
         </div>
         <div class="tile col-md-6 border">
             <a href="#">asdf</a>
         </div>
         <div class="tile col-md-6 border">
             <a href="#">asdf</a>
         </div>
     </div>
 </div>
</code>```

CSS

```<code>.overlay {
    height: 100%;
    width: 100%;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.9);
    overflow-x: hidden;
}

.overlay-header{
    border:10px;
    font-family:fontNavbar;
    filter: invert(100%);
}

.overlay-content {
    position: absolute;
    height: 100%;
    text-align: center;
    display:flex;
}
</code>```

What am I missing?
Thanks in advance!

答:
Since you don't have enough content to force the columns to their full 50% width, add the following CSS (and convert the container-fluid ID from an id to a class):

```<code>.overlay-content.container-fluid,
.overlay-content.container-fluid > .row {
    width: 100%;
}
</code>```

https://jsfiddle.net/2a6w3sve/

Body:
I'm having some problems with my layout.
Im trying to make a menu which has a header and a 2x2 tile grid, which has to be 1x4 on smaller screens.

Goal - Big screen
(Red = Header, Green = Tile)

On a small screen everything works fine, it shows the headerbar, and the 4 tiles underneath like this:

Goal and actual - Small screen

When I resize the screen to make it bigger, at some point it gets to the 2x2 grid but when I resize it to go even bigger the grid stops growing horizontally, which makes it look like this:

Actual - Big screen

HTML

            asdf

             asfd

             asdf

             asdf

CSS

.overlay {
    height: 100%;
    width: 100%;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    background-color: rgb(0, 0, 0);
    background-color: rgba(0, 0, 0, 0.9);
    overflow-x: hidden;
}

.overlay-header{
    border:10px;
    font-family:fontNavbar;
    filter: invert(100%);
}

.overlay-content {
    position: absolute;
    height: 100%;
    text-align: center;
    display:flex;
}

What am I missing?
Thanks in advance!

Body:
Since you don't have enough content to force the columns to their full 50% width, add the following CSS (and convert the container-fluid ID from an id to a class):

.overlay-content.container-fluid,
.overlay-content.container-fluid > .row {
    width: 100%;
}

https://jsfiddle.net/2a6w3sve/


问:
SSIS Excel Import (Column Names Changing)
I have an Excel file that loosely resembles the following format:

I'll explain the next step of the SSIS element first as the column names are not "important" as I am un-pivoting the data in a data flow to start getting it usable:

The issue is, the file will be updated - years and quarters will be removed (historical), new ones added to replace the old ones.  That means, as we all know, the metadata on a data flow is broken.

The cell range and position etc. will always remain the same.

Is there a way it can be handled in a data flow with the column names (2016q1) being fluid?

Thanks

答:
You're going to like this as it also does the pivot:

Using C# Script component source:

Add namespace:
Using System.Data.OleDb;

Add your 4 output columns and select data types:

Add code to new row section.

```<code>public override void CreateNewOutputRows()
    {
        /*
          Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
          For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        */
        string fileName = @"C:\test.xlsx";
        string SheetName = "Sheet1";
        string cstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

        OleDbConnection xlConn = new OleDbConnection(cstr);
        xlConn.Open();

        OleDbCommand xlCmd = xlConn.CreateCommand();
        xlCmd.CommandText = "Select * from [" + SheetName + "$]";
        xlCmd.CommandType = CommandType.Text;
        OleDbDataReader rdr = xlCmd.ExecuteReader();

        //int rowCt = 0; //Counter

        while (rdr.Read())
        {
            for (int i = 2; i < rdr.FieldCount; i++) //loop from 3 column to last
            {
                Output0Buffer.AddRow();
                Output0Buffer.ColA = rdr[0].ToString();
                Output0Buffer.ColB = rdr[1].ToString();
                Output0Buffer.FactName = rdr.GetName(i);
                Output0Buffer.FactValue = rdr.GetDouble(i);
            }

            //rowCt++; //increment counter
        }
        xlConn.Close();
    }
</code>```

Body:
You're going to like this as it also does the pivot:

Using C# Script component source:

Add namespace:
Using System.Data.OleDb;

Add your 4 output columns and select data types:

Add code to new row section.

public override void CreateNewOutputRows()
    {
        /*
          Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
          For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
        */
        string fileName = @"C:\test.xlsx";
        string SheetName = "Sheet1";
        string cstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";

        OleDbConnection xlConn = new OleDbConnection(cstr);
        xlConn.Open();

        OleDbCommand xlCmd = xlConn.CreateCommand();
        xlCmd.CommandText = "Select * from [" + SheetName + "$]";
        xlCmd.CommandType = CommandType.Text;
        OleDbDataReader rdr = xlCmd.ExecuteReader();

        //int rowCt = 0; //Counter

        while (rdr.Read())
        {
            for (int i = 2; i < rdr.FieldCount; i++) //loop from 3 column to last
            {
                Output0Buffer.AddRow();
                Output0Buffer.ColA = rdr[0].ToString();
                Output0Buffer.ColB = rdr[1].ToString();
                Output0Buffer.FactName = rdr.GetName(i);
                Output0Buffer.FactValue = rdr.GetDouble(i);
            }

            //rowCt++; //increment counter
        }
        xlConn.Close();
    }

ContentLicense: CC BY-SA 4.0


问:
Find the path to an executable
How can one find the absolute path to an executable based on the PATH environment variable (e.g. based on the environment variables for /bin/sh)?

In other words, is there a function, e.g. program_path "cal" that returns "/usr/bin/cal"?

The reason for asking this question: some functions in the OCaml library (e.g.  Unix.execvp) are able to only take the program's name (and the function will search for the program on its own). I was wondering whether or not this search functionality is available to the user.

答:
You can use the fileutils library, that implements a POSIX compliant file utilities, including the which utility, the one that you're looking for. E.g.

```<code># #use "topfind";;
# #require "fileutils";;
# FileUtil.which "cal";;
- : FilePath.filename = "/usr/bin/cal"
</code>```

Title: Find the path to an executable

Body:
You can use the fileutils library, that implements a POSIX compliant file utilities, including the which utility, the one that you're looking for. E.g.

# #use "topfind";;
# #require "fileutils";;
# FileUtil.which "cal";;
- : FilePath.filename = "/usr/bin/cal"


问:
Karate API: JSON parsing error shown instead of wrong HTTP code returned
Given have the following list of steps

```<code>Given path 'verify'
And header x-api-key = apiKey
And header tenant-id = tenantId
And request a_json_object_with_invalid_user_id_to_verify
When method put
Then status 404
</code>```

When the endpoint returned HTTP 200 (which is a bug that i need to fix) but with an invalid json response such as

```<code>{
  "score" :
}
</code>```

This exception is thrown

```<code>com.jayway.jsonpath.InvalidJsonException: net.minidev.json.parser.ParseException: Unexpected character (}) at position 15.
    at com.jayway.jsonpath.spi.json.JsonSmartJsonProvider.parse(JsonSmartJsonProvider.java:64)
    at com.jayway.jsonpath.internal.JsonContext.parse(JsonContext.java:82)
    at com.jayway.jsonpath.JsonPath.parse(JsonPath.java:596)
    at com.intuit.karate.JsonUtils.toJsonDoc(JsonUtils.java:84)
    at com.intuit.karate.StepDefs.method(StepDefs.java:344)
</code>```

I expect to see the test failed because of wrong status code 200 received of the expected 404. I would like to know if throwing this exception is correct in karate?

Thanks.

答:
I apologize for mis-reading your question.

There is indeed a bug in Karate when handling malformed JSON responses.

We have opened an issue, you should be able to get a patch version very soon: https://github.com/intuit/karate/issues/259

Body:
Given have the following list of steps

Given path 'verify'
And header x-api-key = apiKey
And header tenant-id = tenantId
And request a_json_object_with_invalid_user_id_to_verify
When method put
Then status 404

When the endpoint returned HTTP 200 (which is a bug that i need to fix) but with an invalid json response such as

{
  "score" :
}

This exception is thrown

com.jayway.jsonpath.InvalidJsonException: net.minidev.json.parser.ParseException: Unexpected character (}) at position 15.
    at com.jayway.jsonpath.spi.json.JsonSmartJsonProvider.parse(JsonSmartJsonProvider.java:64)
    at com.jayway.jsonpath.internal.JsonContext.parse(JsonContext.java:82)
    at com.jayway.jsonpath.JsonPath.parse(JsonPath.java:596)
    at com.intuit.karate.JsonUtils.toJsonDoc(JsonUtils.java:84)
    at com.intuit.karate.StepDefs.method(StepDefs.java:344)

I expect to see the test failed because of wrong status code 200 received of the expected 404. I would like to know if throwing this exception is correct in karate?

Thanks.


问:
Using For loop in Pandas with groupby function
unGrouped is a dataframe that looks like this:

```<code>         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN
</code>```

I have the following code:

```<code>for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount
</code>```

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

答:
Generally if you're using a for loop you're probably doing it wrong!

What you probably want is a groupby and count?

```<code>unGrouped.groupBy('borough').size()
</code>```

Body:
unGrouped is a dataframe that looks like this:

         date        borough
969609  01/01/2014       BROOKLYN
967983  01/01/2014          BRONX
967982  01/01/2014         QUEENS
865943  01/01/2014       BROOKLYN
967981  01/01/2014      MANHATTAN
967980  01/01/2014       BROOKLYN
967979  01/01/2014         QUEENS
967984  01/01/2014          BRONX
967978  01/01/2014         QUEENS
967976  01/01/2014       BROOKLYN
967975  01/01/2014       BROOKLYN

I have the following code:

for row in unGrouped:
if unGrouped['borough'][row]=='BRONX':
    bronxCount+=1
    print bronxCount

And it gives me a Key Error: date.
I would like to iterate through the column borough, increment bronxCount whenever it comes across BRONX, and store that value for each row in a column called `bronxCount', to eventually get a count of crimes in the bronx for each day. If anyone could get this loop to work I would greatly appreciate it. Thanks for the help!

Body:
Generally if you're using a for loop you're probably doing it wrong!

What you probably want is a groupby and count?

unGrouped.groupBy('borough').size()


问:
JavaScript logic error
I am trying to get JavaScript to generate a table with data from an array for me however when I run this code it enters the same data twice. Does anyone know what mistake I am making?

The HTML:

```<code><body>
<div class="container">
    <h1 class="page-header">Bookings</h1>
    <table id="bookTable" class="table table-bordered">
        <thead>
            <tr>
            <th>First Name</th>
            <th>Second Name</th>
            <th>Email</th>
            <th>From</th>
            <th>To</th>
        </tr>
        <tr>
            <td type="text" id="firstName"></td>
            <td type="text" id="secondName"></td>
            <td type="text" id="email"></td>
            <td type="text"id="dateFrom"></td>
            <td type="text"id="dateTo"></td>
        </tr>
    </thead>
  </table>
</div>
</code>```

The JavaScript is using a guide I found that I have adapted. In reality, the array comes from a python file that is fed in as a variable when Flask displays the template. I have used the same data that python prints out when looking at the contents of the variable that is passed.

```<code><script>
    var listOfBookings = [John`Doe`jd@gmail.com`03/01/2018`18/01/2018`John`Doe`jd@gmail.com`26/12/2017`27/12/2017]
    var array = listOfBookings.split("`");
    var count = 1
    for (var i = 0; i < array.length; i++){
        if (1%(i+1) == 0){
            var firstName = array[i];
            }
        if (2%(i+1) == 0){
            var secondName = array[i];
            }
        if (3%(i+1) == 0){
            var email = array[i];
            }
        if (4%(i+1) == 0){
            var dateFrom = array[i];
            }
        if (5%(i+1) == 0){
            var dateTo = array[i];
            }

        // Addapted from http://talkerscode.com/webtricks/add-edit-and-
delete-rows-from-table-dynamically-using-javascript.php
        if(count%5 == 0){
            var table=document.getElementById("bookTable");
            var table_len=(table.rows.length)-1;
            var row = table.insertRow(table_len).outerHTML="<tr
id='row"+table_len+"'><td id='date_row"+table_len+"'>"+firstName+"</td><td
id='name_row"+table_len+"'>"+secondName+"</td><td
id='country_row"+table_len+"'>"+email+"</td><td
id='country_row"+table_len+"'>"+dateFrom+"</td><td
id='country_row"+table_len+"'>"+dateTo+"</td></tr>";
        }
        count += 1
    }
</script>
</code>```

答:
Your code seems overly complicated. Here's a working example of how you might do it: (Note: I've added a tbody to your table, rather than have all these rows inserted into the thead)

var listOfBookings = "John`Doe`jd@gmail.com`03/01/2018`18/01/2018`John`Doe`jd@gmail.com`26/12/2017`27/12/2017";
var array = listOfBookings.split("`");
var count = 1;
var table = document.getElementById("bookTable").getElementsByTagName('tbody')[0];
var row = table.insertRow(-1); //appends initial row
row.id = "row_" + (count)
for (var i = 0; i < array.length; i++) {
  if (i % 5 == 0 && i > 0) {
    row = table.insertRow(-1); //appends a row
    row.id = "row_" + (++count)
  }
  var cell = row.insertCell(-1); //appends a cell
  var text = document.createTextNode(array[i]); //create the textNode
  cell.appendChild(text); //fill the cell with the text
  //(you could also set the cell id and other attributes at this point too)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1 class="page-header">Bookings</h1>
  <table id="bookTable" class="table table-bordered">
    <thead>
      <tr>
        <th>First Name</th>
        <th>Second Name</th>
        <th>Email</th>
        <th>From</th>
        <th>To</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div></code>```

Title: JavaScript logic error

Body:
I am trying to get JavaScript to generate a table with data from an array for me however when I run this code it enters the same data twice. Does anyone know what mistake I am making?

The HTML:

Bookings

            First Name
            Second Name
            Email
            From
            To

The JavaScript is using a guide I found that I have adapted. In reality, the array comes from a python file that is fed in as a variable when Flask displays the template. I have used the same data that python prints out when looking at the contents of the variable that is passed.

Body:
Your code seems overly complicated. Here's a working example of how you might do it: (Note: I've added a tbody to your table, rather than have all these rows inserted into the thead)

var listOfBookings = "John`Doe`jd@gmail.com`03/01/2018`18/01/2018`John`Doe`jd@gmail.com`26/12/2017`27/12/2017";
var array = listOfBookings.split("`");
var count = 1;
var table = document.getElementById("bookTable").getElementsByTagName('tbody')[0];
var row = table.insertRow(-1); //appends initial row
row.id = "row_" + (count)
for (var i = 0; i < array.length; i++) {
  if (i % 5 == 0 && i > 0) {
    row = table.insertRow(-1); //appends a row
    row.id = "row_" + (++count)
  }
  var cell = row.insertCell(-1); //appends a cell
  var text = document.createTextNode(array[i]); //create the textNode
  cell.appendChild(text); //fill the cell with the text
  //(you could also set the cell id and other attributes at this point too)
}

<div class="container">
  <h1 class="page-header">Bookings</h1>
  <table id="bookTable" class="table table-bordered">
    <thead>
      <tr>
        <th>First Name</th>
        <th>Second Name</th>
        <th>Email</th>
        <th>From</th>
        <th>To</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</div>


问:
How to join a sub-query to
Hey guys I have this report that i am working on. It has multiple Columns and in between those columns are some Left joins. so my question is, how do i add a left join to the query?

```<code>Declare @asofdate smalldatetime

Set @asofdate = '2017-08-24'

SELECT
      OCCONR                        as [Company Number],
      OCCMNR                     as [Claim Number],    --CMOCUR db)
      OCEXCD                        as [Claim Counsel],   ---(CMOCUR db)
      DATEFROMPARTS(OCEFCN*100+OCEFYY,OCEFMM,OCEFDD)    as [Policy Effective Date], -- (CMOCUR db)
      iif([True CAT Nbr] is null, OCCTCD, [True CAT Nbr])   as [CAT Code],   ---(Check Comment 1)
      iif(LSCMNT is null,'', LSCMNT)    as [NOA Comments], --- (Check Comemnt 2)
      concat([First_Name],' ',[Last_Name]) as [Insured Name], --- (Check Comment 3)
      DatefromParts([OCLSCN]*100+[OCLSYY],[OCLSMM],[OCLSDD])    as [Occurrence Date], --- (CMOCUR db)
      rtrim(ltrim(OCDACC)) as [Cause of Loss],    --- (CMOCUR db)
      DatefromParts([OCRPCN]*100+[OCRPYY],[OCRPMM],[OCRPDD])    as [Claim Reported Date],  --- (CMOCUR db)
      iif(LSSETLD is null,'', LSSETLD)  as [Settled Indicator],  --- (Check Comment 2)
      --iif(SUM([Incurred Loss NET OF S&S]) - SUM([Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Status in AS-400]
      iif(OCCLCN=0,'',datefromparts(OCCLCN*100+OCCLYY,OCCLMM,OCCLDD)) as [Closed Date],   --- (CMOCUR db)
      iif(LSCLCN=0 OR LSCLCN IS NULL,'',DatefromParts(LSCLCN*100+LSCLYY,LSCLMM,LSCLDD)) as [All Closed Date]    ----(Comment 2)
      --[Last Reserve Change Date]

FROM AS400.FRTDTA250.CMOCUR

LEFT JOIN Lookups.dbo.[Bad CAT Codes]                   ON [Claim Nbr] = OCCMNR     ---- This LEFT JOIN provides the CAT CODE for this report  (Comment 1)
LEFT JOIN AS400.FRTDTA250.CMLSCP                        ON LSCMNR = OCCMNR        ---- This is used to pull any COMMENTS and SETTLEMENT made on a claim   (Comment 2)
LEFT JOIN Lookups.dbo.Insured_Name_By_PolicyNum         ON Prefix = OCPRFX and Polnum = OCPLNR      --- This is to add the INSURED NAME        (comment 3)
</code>```

So, the issue i am having is that i have this other sub-queries that are meant to provide information for the [Status in AS-400] and [Last Reserve Change Date]. How do i connect this queries to the SQL?

Below are the 2 queries that i am trying to add to the select query:

-- Query for [Status in AS-400]

```<code>SELECT
     ---s1.[Claim Number],
     iif(SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Open / Closed]
     ---SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S])  as [Loss C/R]

FROM
(
   SELECT
   OCCMNR as [Claim Number],
   SUM(iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Incurred Loss NET OF S&S],
   SUM(iif(DATASETTYPE IN ('Paid LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Paid Loss NET OF S&S]

   FROM AS400.FRTDTA250.[CMOCUR] AS A

   INNER JOIN   AS400.FRTDTA250.[CMTRAN]AS B ON A.OCCMNR = B.CTCMNR

   LEFT JOIN Lookups.dbo.TransactionCodes AS C ON B.CTGRPC = C.TransactionCode

   WHERE    DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= @asofdate
        and CTTRSB not in (4,12)
        and CTTSCD = 'P'

   GROUP BY OCCMNR

   ) as s1

   GROUP BY s1.[Claim Number]

   ORDER BY  s1.[Claim Number]
</code>```

--Query for [Last Reserve Change Date]

```<code>  Select [Claim Number],
  left(convert(CHAR, Max([Loss Transaction Date]), 120),10) as [Last Reserve Change Date]

  From
     (
       Select [OCCMNR] as [Claim Number],
       DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) as [Loss Transaction Date],
       iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) as [Incurred Loss]

       From AS400.FRTDTA250.[CMTRAN] as b1

       LEFT JOIN AS400.FRTDTA250.[CMOCUR] as a1
       ON a1.OCCMNR = b1.CTCMNR

       LEFT JOIN Lookups.dbo.TransactionCodes as c1
       ON b1.CTGRPC = c1.TransactionCode

       Where (iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) <> 0)
       and DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= @asofdate
       and CTTRSB not in (4,12)
       AND CTTSCD = 'P'
       ) s2

       group by  [Claim Number]

       ) as G
       on G.[Claim Number] = a.[OCCMNR]
</code>```

And i use a MS-SQL Server

答:
Format for joining Sub-queries are as follows:</p>

```<code>SELECT *
FROM TABLEA A
INNER JOIN TABLED D on A.ID = D.ID
LEFT JOIN
  ( SELECT B.ID,COLUMN_A
    FROM TABLEB B
    INNER JOIN TABLEC C ON B.ID = C.ID
  ) X ON A.ID = X.ID
</code>```

Title: How to join a sub-query to

Body:
Hey guys I have this report that i am working on. It has multiple Columns and in between those columns are some Left joins. so my question is, how do i add a left join to the query?

Declare @asofdate smalldatetime

Set @asofdate = '2017-08-24'

SELECT
      OCCONR                        as [Company Number],
      OCCMNR                     as [Claim Number],    --CMOCUR db)
      OCEXCD                        as [Claim Counsel],   ---(CMOCUR db)
      DATEFROMPARTS(OCEFCN*100+OCEFYY,OCEFMM,OCEFDD)    as [Policy Effective Date], -- (CMOCUR db)
      iif([True CAT Nbr] is null, OCCTCD, [True CAT Nbr])   as [CAT Code],   ---(Check Comment 1)
      iif(LSCMNT is null,'', LSCMNT)    as [NOA Comments], --- (Check Comemnt 2)
      concat([First_Name],' ',[Last_Name]) as [Insured Name], --- (Check Comment 3)
      DatefromParts([OCLSCN]*100+[OCLSYY],[OCLSMM],[OCLSDD])    as [Occurrence Date], --- (CMOCUR db)
      rtrim(ltrim(OCDACC)) as [Cause of Loss],    --- (CMOCUR db)
      DatefromParts([OCRPCN]*100+[OCRPYY],[OCRPMM],[OCRPDD])    as [Claim Reported Date],  --- (CMOCUR db)
      iif(LSSETLD is null,'', LSSETLD)  as [Settled Indicator],  --- (Check Comment 2)
      --iif(SUM([Incurred Loss NET OF S&S]) - SUM([Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Status in AS-400]
      iif(OCCLCN=0,'',datefromparts(OCCLCN*100+OCCLYY,OCCLMM,OCCLDD)) as [Closed Date],   --- (CMOCUR db)
      iif(LSCLCN=0 OR LSCLCN IS NULL,'',DatefromParts(LSCLCN*100+LSCLYY,LSCLMM,LSCLDD)) as [All Closed Date]    ----(Comment 2)
      --[Last Reserve Change Date]

FROM AS400.FRTDTA250.CMOCUR

LEFT JOIN Lookups.dbo.[Bad CAT Codes]                   ON [Claim Nbr] = OCCMNR     ---- This LEFT JOIN provides the CAT CODE for this report  (Comment 1)
LEFT JOIN AS400.FRTDTA250.CMLSCP                        ON LSCMNR = OCCMNR        ---- This is used to pull any COMMENTS and SETTLEMENT made on a claim   (Comment 2)
LEFT JOIN Lookups.dbo.Insured_Name_By_PolicyNum         ON Prefix = OCPRFX and Polnum = OCPLNR      --- This is to add the INSURED NAME        (comment 3)

So, the issue i am having is that i have this other sub-queries that are meant to provide information for the [Status in AS-400] and [Last Reserve Change Date]. How do i connect this queries to the SQL?

Below are the 2 queries that i am trying to add to the select query:

-- Query for [Status in AS-400]

SELECT
     ---s1.[Claim Number],
     iif(SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S]) = 0, 'Closed', 'Open') as [Open / Closed]
     ---SUM(s1.[Incurred Loss NET OF S&S]) - SUM(s1.[Paid Loss NET OF S&S])  as [Loss C/R]

FROM
(
   SELECT
   OCCMNR as [Claim Number],
   SUM(iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Incurred Loss NET OF S&S],
   SUM(iif(DATASETTYPE IN ('Paid LOSS'), CTTRAM, iif(DATASETTYPE IN ('SALVAGE','SUBROGATION','OTHER RECOVERIES'), -CTTRAM, 0))) AS [Paid Loss NET OF S&S]

   FROM AS400.FRTDTA250.[CMOCUR] AS A

   INNER JOIN   AS400.FRTDTA250.[CMTRAN]AS B ON A.OCCMNR = B.CTCMNR

   LEFT JOIN Lookups.dbo.TransactionCodes AS C ON B.CTGRPC = C.TransactionCode

   WHERE    DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= @asofdate
        and CTTRSB not in (4,12)
        and CTTSCD = 'P'

   GROUP BY OCCMNR

   ) as s1

   GROUP BY s1.[Claim Number]

   ORDER BY  s1.[Claim Number]

--Query for [Last Reserve Change Date]

  Select [Claim Number],
  left(convert(CHAR, Max([Loss Transaction Date]), 120),10) as [Last Reserve Change Date]

  From
     (
       Select [OCCMNR] as [Claim Number],
       DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) as [Loss Transaction Date],
       iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) as [Incurred Loss]

       From AS400.FRTDTA250.[CMTRAN] as b1

       LEFT JOIN AS400.FRTDTA250.[CMOCUR] as a1
       ON a1.OCCMNR = b1.CTCMNR

       LEFT JOIN Lookups.dbo.TransactionCodes as c1
       ON b1.CTGRPC = c1.TransactionCode

       Where (iif(DATASETTYPE IN ('Incurred LOSS'), CTTRAM, 0) <> 0)
       and DATEFROMPARTS(CTTRCN*100+CTTRYY, CTTRMM, CTTRDD) <= @asofdate
       and CTTRSB not in (4,12)
       AND CTTSCD = 'P'
       ) s2

       group by  [Claim Number]

       ) as G
       on G.[Claim Number] = a.[OCCMNR]

And i use a MS-SQL Server

Body:
Format for joining Sub-queries are as follows:

SELECT *
FROM TABLEA A
INNER JOIN TABLED D on A.ID = D.ID
LEFT JOIN
  ( SELECT B.ID,COLUMN_A
    FROM TABLEB B
    INNER JOIN TABLEC C ON B.ID = C.ID
  ) X ON A.ID = X.ID


问:
Getting array data from PHP to jQuery for outputting
Here is the partial code from the remove PHP file:

```<code>if($action == 'trackings_get') {
    $result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
    $result_history = $result['data']['tracking']['checkpoints'];

    echo json_encode($result_history);

    // debugging
    //pretty_print($result_history);
}
</code>```

Here is the JS from the remote site i am trying to call the data for:

```<code>$.ajax({
  url: '/login/tracking.php',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
    //debug
    alert(JSON.stringify(json));
  }
});
</code>```

答:
try this</p>

```<code>function test(){
$.ajax({
  url: 'url',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
  }
});

}
</code>```

Body:
Here is the partial code from the remove PHP file:

if($action == 'trackings_get') {
    $result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
    $result_history = $result['data']['tracking']['checkpoints'];

    echo json_encode($result_history);

    // debugging
    //pretty_print($result_history);
}

Here is the JS from the remote site i am trying to call the data for:

$.ajax({
  url: '/login/tracking.php',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
    //debug
    alert(JSON.stringify(json));
  }
});

Body:
try this

function test(){
$.ajax({
  url: 'url',
  type: 'POST',
  dataType: "json",
  data: {
    action: action,
    tracking_id: tracking_id
  },
  success: function(json){
  }
});

}


问:
Check / match string against partial strings in array
I am trying to match a full UK postcode against a partial postcode.
Take a users postcode, i.e g22 1pf, and see if there's a match / partial match in the array / database.

```<code>//Sample data
$postcode_to_check= 'g401pf';
//$postcode_to_check= 'g651qr';
//$postcode_to_check= 'g51rq';
//$postcode_to_check= 'g659rs';
//$postcode_to_check= 'g40';

$postcodes = array('g657','g658','g659','g659pf','g40','g5');
$counter=0;

foreach($postcodes as $postcode){
    $postcode_data[] = array('id' =>$counter++ , 'postcode' => $postcode, 'charge' => '20.00');
}
</code>```

I do have some code but that was just comparing the strings with fixed lengths from the database. I need the strings in the array / database to be dynamic in length.

The database may contain "g22"  this would be a match, it could also contain more or less of the postcode, i.e "g221" or "g221p" which would also be a match.  It could contain "g221q" or "g221qr" these would not match.

Help Appreciated, Thank you

edit.

I was possibly overthinking this.  the following pseudo code seems to function as expected.

```<code>check_delivery('g401pf');
//this would match because g40 is in the database.

check_delivery('g651dt');
// g651dt this would NOT match because g651dt is not in the database.

check_delivery('g524pq');
//g524pq this would match because g5 is in the database.

check_delivery('g659pf');
//g659pf this would match because g659 is in the database.

check_delivery('g655pf');
//g655pf this would not match, g665 is not in the database

//expected output, 3 matches

function check_delivery($postcode_to_check){

    $postcodes = array('g657','g658','g659','g659pf','g40','g5');
    $counter=0;

    foreach($postcodes as $postcode){

        $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

        if($postcode==$stripped_postcode){
            echo "Matched<br><br>";
          break;
        }
    }
}
</code>```

答:
Check the length and strip the one you want to compare it with to the same length.

function check_delivery($postcode_to_check){

```<code>$postcodes = array('g657','g658','g659','g659pf','g40','g5');
$counter=0;

foreach($postcodes as $postcode){

    $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

    if($postcode==$stripped_postcode){
        echo "Matched<br><br>";
      break;
    }
}
</code>```

}

Body:
I am trying to match a full UK postcode against a partial postcode.
Take a users postcode, i.e g22 1pf, and see if there's a match / partial match in the array / database.

//Sample data
$postcode_to_check= 'g401pf';
//$postcode_to_check= 'g651qr';
//$postcode_to_check= 'g51rq';
//$postcode_to_check= 'g659rs';
//$postcode_to_check= 'g40';

$postcodes = array('g657','g658','g659','g659pf','g40','g5');
$counter=0;

foreach($postcodes as $postcode){
    $postcode_data[] = array('id' =>$counter++ , 'postcode' => $postcode, 'charge' => '20.00');
}

I do have some code but that was just comparing the strings with fixed lengths from the database. I need the strings in the array / database to be dynamic in length.

The database may contain "g22"  this would be a match, it could also contain more or less of the postcode, i.e "g221" or "g221p" which would also be a match.  It could contain "g221q" or "g221qr" these would not match.

Help Appreciated, Thank you

edit.

I was possibly overthinking this.  the following pseudo code seems to function as expected.

check_delivery('g401pf');
//this would match because g40 is in the database.

check_delivery('g651dt');
// g651dt this would NOT match because g651dt is not in the database.

check_delivery('g524pq');
//g524pq this would match because g5 is in the database.

check_delivery('g659pf');
//g659pf this would match because g659 is in the database.

check_delivery('g655pf');
//g655pf this would not match, g665 is not in the database

//expected output, 3 matches

function check_delivery($postcode_to_check){

    $postcodes = array('g657','g658','g659','g659pf','g40','g5');
    $counter=0;

    foreach($postcodes as $postcode){

        $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

        if($postcode==$stripped_postcode){
            echo "Matched

";
          break;
        }
    }
}

Body:
Check the length and strip the one you want to compare it with to the same length.

function check_delivery($postcode_to_check){

$postcodes = array('g657','g658','g659','g659pf','g40','g5');
$counter=0;

foreach($postcodes as $postcode){

    $stripped_postcode = substr($postcode_to_check,0, strlen($postcode));

    if($postcode==$stripped_postcode){
        echo "Matched<br><br>";
      break;
    }
}

}


问:
Evaluating a user-input expression in Rails
I need to accept an mathematical expression (including one or more unknowns) from the user and substitute values in for the unknowns to get a result.

I could use eval() to do this, but it's far too risky unless there is a way to recognise "safe" expressions.

I'd rather not write my own parser if I can help it.

I searched for a ready-made parser but the only one I found ( https://www.ruby-toolbox.com/gems/expression_parser , which seems to be the same as the one discussed at http://lukaszwrobel.pl/blog/math-parser-part-4-tests) seems to be limited to the "four rules" +-*/. I need to include exponential, log and trig functions at the very least.

Any suggestions?

UPDATE: EXAMPLE

```<code>include Math

def exp(x)
 Math.exp(x)
end

def cos(x)
 Math.cos(x)
end

pi=Math::PI
t=2
string= '(3*exp(t/2)*cos(3*t-pi/2))'
puts eval(string)
</code>```

UPDATE - a pre-parsing validation step

I think I will use this regex to check the string has the right kinds of tokens in it:

/((((cos\(|sin\()|(tan\(|acos\())|((asin\(|atan\()|(exp\(|log\())|ln\()(([+-\/*^\(\)A-Z]|\d)+))*([+-\/*^\(\)A-Z]|\d)+/

But I will still implement the parsing method during the actual evaluation.

Thanks for the help!

答:
You can checkout the Dentaku gem - https://github.com/rubysolo/dentaku

You can use it to execute the user given formula.

Here is an example usage of this gem.

```<code>class FormulaExecutor
  def execute_my_formula(formula, params)
    calc = Dentaku::Calculator.new

    # Param 1 => formula to execute
    # Param 2 => Hash of local variables
    calc.evaluate(formula, params)
  end
end

FormulaExecutor.new.execute_my_formula( "length * breadth", {'length' => 11, 'breadth' => 120} )
</code>```

Body:
I need to accept an mathematical expression (including one or more unknowns) from the user and substitute values in for the unknowns to get a result.

I could use eval() to do this, but it's far too risky unless there is a way to recognise "safe" expressions.

I'd rather not write my own parser if I can help it.

I searched for a ready-made parser but the only one I found ( https://www.ruby-toolbox.com/gems/expression_parser , which seems to be the same as the one discussed at http://lukaszwrobel.pl/blog/math-parser-part-4-tests) seems to be limited to the "four rules" +-*/. I need to include exponential, log and trig functions at the very least.

Any suggestions?

UPDATE: EXAMPLE

include Math

def exp(x)
 Math.exp(x)
end

def cos(x)
 Math.cos(x)
end

pi=Math::PI
t=2
string= '(3*exp(t/2)*cos(3*t-pi/2))'
puts eval(string)

UPDATE - a pre-parsing validation step

I think I will use this regex to check the string has the right kinds of tokens in it:

/((((cos\(|sin\()|(tan\(|acos\())|((asin\(|atan\()|(exp\(|log\())|ln\()(([+-\/*^\(\)A-Z]|\d)+))*([+-\/*^\(\)A-Z]|\d)+/

But I will still implement the parsing method during the actual evaluation.

Thanks for the help!

Body:
You can checkout the Dentaku gem - https://github.com/rubysolo/dentaku

You can use it to execute the user given formula.

Here is an example usage of this gem.

class FormulaExecutor
  def execute_my_formula(formula, params)
    calc = Dentaku::Calculator.new

    # Param 1 => formula to execute
    # Param 2 => Hash of local variables
    calc.evaluate(formula, params)
  end
end

FormulaExecutor.new.execute_my_formula( "length * breadth", {'length' => 11, 'breadth' => 120} )