问:
How can I send automated emails from bluehost?
I want to send newsletters and event information to my customers. Sending manual emails will take time. So, I was thinking of sending automated emails. </p>

<p>I just want to upload all my contact details to MySQL database in Bluehost where my website is placed and send automated emails. But, I don't know how to do it. Please help. </p>

答:
If you want to do this with posts, there are plugins that would do this fairly well. Just search for "posts to newsletters" or "posts to emails" in wp add plugs. If you're looking to do something more unique, you could use php mail() in a file to loop through contact emails, then call the file regularly with a remote cron job (as I believe you can't set up a cron job on the server) site like cron-job.org.

See:

http://php.net/manual/en/function.mail.php

https://cron-job.org

Body:
I want to send newsletters and event information to my customers. Sending manual emails will take time. So, I was thinking of sending automated emails.

I just want to upload all my contact details to MySQL database in Bluehost where my website is placed and send automated emails. But, I don't know how to do it. Please help.


来源: stackexchange

问:
How to check how much char space in 1 string
Lets say I have a string with some text:

```<code>String str="Hello My Name Is Help!"
</code>```

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

```<code>if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}
</code>```

答:
A solution is to use replaceAll to replace all non space ([^\s]) with empty and check the length of result output :

```<code>if (str.replaceAll("[^\\s]", "").length() > 3) {...}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Lets say I have a string with some text:

String str="Hello My Name Is Help!"

And I want to check how much space chars I have in the following String str. I would like a make a method that takes that following string and returns the number of whitespaces in that string. For example if I name my method getNumberOfWhiteSpaces(String str) and call it a I should get back the number of whitespaces.

if( getNumberOfWhiteSpaces(String str) > 3)
     System.out.println("There are more then 3 spaces in this string");

public int getNumberOfWhiteSpaces(String str) {
  ....
  return some number
}

Body:
A solution is to use replaceAll to replace all non space ([^\s]) with empty and check the length of result output :

if (str.replaceAll("[^\\s]", "").length() > 3) {...}


问:
Crash on FIRApp.configure() method
I added a firebase framework using cocoapods to existing Project but a crash occurs at the FIRApp.configure() method.

To figure out the problem, I create a new project and add a firebase Framework which is working.

I don't know what could be the Problem.

答: Make sure GoogleService-Info.plist is in your build target.</p>

Title: Crash on FIRApp.configure() method


问:
failed to open stream: No such file or directory composer cacert .pem file
I trying to installing ratchet using composer I installed composer using the insteller.exe but my problem is when I run this line on CMD I get this error

```<code>C:\1>php "C:/programData/ComposerSetup/bin/composer.phar" require cboden/ratchet

 [ErrorException]
 fopen(C:\Users\shako\AppData\Local\Temp;C:\xampp\mysql\bin;C:\xampp\php;/co
 mposer-cacert-300c74d6960d46715ffed607c8e36acfa7cbcad49862bb1b67d3c43dea9bf
 b40.pem): failed to open stream: No such file or directory
</code>```

I tryed  to fix this error by changing this line from php.ini  file
from

```<code>sys_temp_dir = "/tmp"
</code>```

to

```<code>sys_temp_dir = C:\Users\shako\AppData\Local\Temp;C:\xampp\mysql\bin;C:\xampp\php\php.exe
</code>```

but I still get the same error

答:
I tried to comment sys_temp_dir but it didn't work for me.

I resolved the issue by creating a folder for temporary files outside the application folder, a location which the users don't have access to. Then I defined that folder to sys_temp_dir. As an example:

sys_temp_dir = C:\inetpub\temp\files

Good luck!

Body:
I trying to installing ratchet using composer I installed composer using the insteller.exe but my problem is when I run this line on CMD I get this error

C:\1>php "C:/programData/ComposerSetup/bin/composer.phar" require cboden/ratchet

 [ErrorException]
 fopen(C:\Users\shako\AppData\Local\Temp;C:\xampp\mysql\bin;C:\xampp\php;/co
 mposer-cacert-300c74d6960d46715ffed607c8e36acfa7cbcad49862bb1b67d3c43dea9bf
 b40.pem): failed to open stream: No such file or directory

I tryed  to fix this error by changing this line from php.ini  file
from

sys_temp_dir = "/tmp"

to

sys_temp_dir = C:\Users\shako\AppData\Local\Temp;C:\xampp\mysql\bin;C:\xampp\php\php.exe

but I still get the same error


问:
Selenium - FirefoxDriver not accepting arguments in code
I am unable to use arguments for new FirefoxDriver as per code:

```<code>        File pathBinary = new File("C:\\Users\\myname\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
        FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
        FirefoxProfile firefoxProfile = new FirefoxProfile();
        WebDriver driver = new FirefoxDriver(firefoxBinary,firefoxProfile);
        //WebDriver driver = new FirefoxDriver();
</code>```

I get an error saying "remove arguments to match FirefoxProfile();

When I try using just new FirefoxDriver() I get:

```<code>        org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: WIN8_1
</code>```

I am using:

```<code>        geckodriver-v0.19.1-win32
        selenium-server-standalone-3.7.1
</code>```

Any help most appreciated.

答:
You need to pass them in as Firefox options try the following</p>

```<code>FirefoxProfile ffprofile = new FirefoxProfile();
FirefoxBinary ffBinary = new FirefoxBinary(new File("path to your firefox
executable"));
FirefoxOptions options = new FirefoxOptions();
options.setProfile(ffprofile);
options.setProfile(ffBinary);
options.setCapability(FirefoxOptions.FIREFOX_OPTIONS,options);
WebDriver driver = new FirefoxDriver(options);
</code>```

Body:
I am unable to use arguments for new FirefoxDriver as per code:

        File pathBinary = new File("C:\\Users\\myname\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
        FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
        FirefoxProfile firefoxProfile = new FirefoxProfile();
        WebDriver driver = new FirefoxDriver(firefoxBinary,firefoxProfile);
        //WebDriver driver = new FirefoxDriver();

I get an error saying "remove arguments to match FirefoxProfile();

When I try using just new FirefoxDriver() I get:

        org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: WIN8_1

I am using:

        geckodriver-v0.19.1-win32
        selenium-server-standalone-3.7.1

Any help most appreciated.

Body:
You need to pass them in as Firefox options try the following

FirefoxProfile ffprofile = new FirefoxProfile();
FirefoxBinary ffBinary = new FirefoxBinary(new File("path to your firefox
executable"));
FirefoxOptions options = new FirefoxOptions();
options.setProfile(ffprofile);
options.setProfile(ffBinary);
options.setCapability(FirefoxOptions.FIREFOX_OPTIONS,options);
WebDriver driver = new FirefoxDriver(options);


问:
How to download the original image from Google Photo with an `id` from Google Picker v3
I am trying to download the full image from my personal Google Photo account.

The image itself was shot with iPhone 6+ at a resolution of 2448×3264 but the biggest size I can get so far is a thumbnail size at 384x512.

Here is the data returned from the Google Picker API v3:

```<code>> data.docs[0]
{
   id:"6249684261772136370",
   mediaKey:"AF1QipPWLtKuyF09rcIQd4UT2tjb1YxkWSypm6PHXfeX",
   mimeType:"application/vnd.google-apps.photo",
   name:"IMG_5853.JPG",
   parentId:"6249684260517294833",
   serviceId: "picasa",
   thumbnails: (5) [{…}, {…}, {…}, {…}, {…}],
   type:"photo",
   url:"https://picasaweb.google.com/105232457300095210093/ALBUM_NAME#HASH"
}
</code>```

Here are the scopes I declared when requesting the access_token using OAuth2

```<code>"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/photos",
"https://www.googleapis.com/auth/drive",
"https://picasaweb.google.com/data/"
</code>```

Here is the request I sent to the "image metadata" endpoint with gdata version set to 3: https://picasaweb.google.com/data/entry/api/user/default/albumid/6249684260517294833/photoid/6249684261772136370

And get the following XML back https://pastebin.com/jgXEqftN but the image under <content type="image/jpeg" src="..." /> is still a thumbnail.

I know there must be a way for this to work since company like filestack can download the full-size image. Any comments/suggestions?

Please note that I am aware that Google photo and Google drive are two different products. But since you can access the images from Google photo through Google drive, and also in the Picker's documentation, it explicitly gives an example of using Google Drive v3 API,  I thought I'll give the example a try:

```<code>curl --header "Authorization: Bearer ya29.GlsABSW1XLQRocTsxsFlGKmVnx3iCwjAxQCFWG-3YH9nM6IYdLyp8x9v4XLglUEMK1XKsgf8SjYzRpbHJa5xDat5M7PcOfJhViOZAa-S6aAGuWKPe98AJ_y2QtH7" https://www.googleapis.com/drive/v3/files/6244822006604119090\?alt\=media
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "File not found: 6244822006604119090.",
    "locationType": "parameter",
    "location": "fileId"
   }
  ],
  "code": 404,
  "message": "File not found: 6244822006604119090."
 }
}
</code>```

答:
The problem is solved, but not without a sense of frustration and a tingling feeling of why this is not documented anywhere.

To get the original image, I need to url hack any of the returned thumbnail urls. For example, given the following

Notice the /s72 in the url. By replacing it with /s0, we'll get the uncropped image. Want the image to be 1024px wide? Pass in /s1024. Here is the javascript code for doing so

```<code>thumbnail_url.replace(/\/s\S+?\//g, "/s0/")
</code>```

Body:
I am trying to download the full image from my personal Google Photo account.

The image itself was shot with iPhone 6+ at a resolution of 2448×3264 but the biggest size I can get so far is a thumbnail size at 384x512.

Here is the data returned from the Google Picker API v3:

> data.docs[0]
{
   id:"6249684261772136370",
   mediaKey:"AF1QipPWLtKuyF09rcIQd4UT2tjb1YxkWSypm6PHXfeX",
   mimeType:"application/vnd.google-apps.photo",
   name:"IMG_5853.JPG",
   parentId:"6249684260517294833",
   serviceId: "picasa",
   thumbnails: (5) [{…}, {…}, {…}, {…}, {…}],
   type:"photo",
   url:"https://picasaweb.google.com/105232457300095210093/ALBUM_NAME#HASH"
}

Here are the scopes I declared when requesting the access_token using OAuth2

"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/photos",
"https://www.googleapis.com/auth/drive",
"https://picasaweb.google.com/data/"

Here is the request I sent to the "image metadata" endpoint with gdata version set to 3: https://picasaweb.google.com/data/entry/api/user/default/albumid/6249684260517294833/photoid/6249684261772136370

And get the following XML back https://pastebin.com/jgXEqftN but the image under <content type="image/jpeg" src="..." /> is still a thumbnail.

I know there must be a way for this to work since company like filestack can download the full-size image. Any comments/suggestions?

Please note that I am aware that Google photo and Google drive are two different products. But since you can access the images from Google photo through Google drive, and also in the Picker's documentation, it explicitly gives an example of using Google Drive v3 API,  I thought I'll give the example a try:

curl --header "Authorization: Bearer ya29.GlsABSW1XLQRocTsxsFlGKmVnx3iCwjAxQCFWG-3YH9nM6IYdLyp8x9v4XLglUEMK1XKsgf8SjYzRpbHJa5xDat5M7PcOfJhViOZAa-S6aAGuWKPe98AJ_y2QtH7" https://www.googleapis.com/drive/v3/files/6244822006604119090\?alt\=media
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "File not found: 6244822006604119090.",
    "locationType": "parameter",
    "location": "fileId"
   }
  ],
  "code": 404,
  "message": "File not found: 6244822006604119090."
 }
}

Body:
The problem is solved, but not without a sense of frustration and a tingling feeling of why this is not documented anywhere.

To get the original image, I need to url hack any of the returned thumbnail urls. For example, given the following

Notice the /s72 in the url. By replacing it with /s0, we'll get the uncropped image. Want the image to be 1024px wide? Pass in /s1024. Here is the javascript code for doing so

thumbnail_url.replace(/\/s\S+?\//g, "/s0/")


问:
When does an AnalyserNode have a buffer ready?
It's difficult to find information about the AnalyserNode in the MDN docs, so hopefully y'all can help: is there a way to tell when a buffer has been processed by the AnalyserNode and there's FFT data ready for me to view?  All of the MDN examples involve using the animation timer via requestAnimationFrame, which is good for visualizations but not for the audio analysis I'm trying to do.  I'd like to be able to get all of the FFT data, not just poll at the animation frame rate.  MDN lists some events but it doesn't actually explain any of them in the context of the AnalyserNode, and the FFT data isn't an output in the audio graph so I can't just connect the AnalyserNode to a ScriptProcessorNode and do what I need to do that way.

Thanks!

答: If you want to get literally all the data from the FFT, there's no way to do that with the AnalyserNode; you can't grab that output at the right time consistently.  You'd be better off using an external FFT library like DSP.js.</p>


问:
How HTTP servers accepts Telnet
I understand that Telnet is a protocol as much as HTTP. I have this notion that after the initial TCP connection is made the Telnet client would send some telnet specific code over to the server on the other side in this case a HTTP server. But since HTTP server doesn't understand Telnet specific codes it should throw an error or drop the connection etc. But in reality we can telnet to a HTTP server and fetch pages if we type in correct HTTP headers and send them. How can it be like that? Wikipedia entry really didn't help me to understand this specific point. (http://en.wikipedia.org/wiki/Telnet#Telnet_data)</p>

答:
You can query a http server using telnet, I often do as a quick and nasty test
telnet doesnt send any codes. it just makes the connection, but there are telnet specific codes you can send if you require

do this...

```<code>telnet server.com 80
GET http/1.0 /^m
host: server.com^m
^m

... servers response
</code>```

^m = enter key

I have done this is done in linux in windows it may be different.

DC

ContentLicense: CC BY-SA 2.5

Title: How HTTP servers accepts Telnet

Body:
You can query a http server using telnet, I often do as a quick and nasty test
telnet doesnt send any codes. it just makes the connection, but there are telnet specific codes you can send if you require

do this...

telnet server.com 80
GET http/1.0 /^m
host: server.com^m
^m

... servers response

^m = enter key

I have done this is done in linux in windows it may be different.

DC


问:
Transition Content into view from the same direction using CSS Transitions
I am attempting to slide one of two 'pages' i.e <divs> into view with a gentle transition where the user can see one page sliding out whilst the other page slides in. In my final application, the transition will be triggered from my backend (probably with a WebSocket message).

I would like the pages to slide in from the left and for the effect to 'loop'; that is that when returning to the first page, it still slides in from the left.

I have created a snippet below which demonstrates my current plan of using a CSS3 transition to achieve the desired effect. It works but feels very clunky.

It operates as follows:

#page1 starts in view and #page2 has it's horizontal position offset by its width through use of the in-frame and out-of-frame classes respectively.

For #page1 to #page2 transition, I simply apply the .slide class which uses a transform:translateX() to reposition both 'pages' by their width and the transition property of the page class handles the transition effect.

In order to perform loop-like behaviour I wait for the transition to finish, then I toggle which page has which in-frame or out-of-frame class with the intention of bringing #page1 back to being off-screen to the left of #page2. However in order to prevent this position-change running as a transition, I have to apply the .notransition class which feels like a kludgey work-around.

My Question: Is there a better way to achieve this behaviour using CSS transitions?

I know bootstrap's carousel can do it for me like this but it would be nice to know if/where I am going wrong.

// add transition finished handler to each page
$('.page').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
  // toggle in/out of frame
  $(this).toggleClass('in-frame')
    .toggleClass('out-of-frame')
    .addClass('notransition')
    .removeClass('slide')
})

$('body').click(function() {
  // start transform
  $('.page').removeClass('notransition').addClass('slide')
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  overflow: hidden;
  text-align: center;
  font-size: 2em;
}

#content {
  position: relative;
  height: 100%;
}

.page {
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
  -webkit-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  -moz-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  -o-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide {
  -webkit-transform: translateX(100%);
  -moz-transform: translateX(100%);
  -o-transform: translateX(100%);
  transform: translateX(100%);
}

.in-frame {
  left: 0%;
}

.out-of-frame {
  left: -100%;
}

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}</code>```

    Main Page
 (Click Me)

    Other Page
 (Click Me)

```

答:
Your way looks good to me, another solution still using CSS transitions could be to use a setTimeout() and create a variable which you check to see if it has changed before allowing another click. </p>

```<code>//set a variable
var finish = true;
$('body').click(function() {

    //check to see if last transition has finished
    if(finish == true){

      //set variable to false
      finish = false;
        // start transform
        $('.page').removeClass('notransition').addClass('slide');

        setTimeout(function(){
             finish = true;
             $('.page').toggleClass('in-frame').toggleClass('out-of-frame').addClass('notransition').removeClass('slide')
              }
        ,2000);
    }
});
</code>```

Body:
I am attempting to slide one of two 'pages' i.e <divs> into view with a gentle transition where the user can see one page sliding out whilst the other page slides in. In my final application, the transition will be triggered from my backend (probably with a WebSocket message).

I would like the pages to slide in from the left and for the effect to 'loop'; that is that when returning to the first page, it still slides in from the left.

I have created a snippet below which demonstrates my current plan of using a CSS3 transition to achieve the desired effect. It works but feels very clunky.

It operates as follows:

#page1 starts in view and #page2 has it's horizontal position offset by its width through use of the in-frame and out-of-frame classes respectively.

For #page1 to #page2 transition, I simply apply the .slide class which uses a transform:translateX() to reposition both 'pages' by their width and the transition property of the page class handles the transition effect.

In order to perform loop-like behaviour I wait for the transition to finish, then I toggle which page has which in-frame or out-of-frame class with the intention of bringing #page1 back to being off-screen to the left of #page2. However in order to prevent this position-change running as a transition, I have to apply the .notransition class which feels like a kludgey work-around.

My Question: Is there a better way to achieve this behaviour using CSS transitions?

I know bootstrap's carousel can do it for me like this but it would be nice to know if/where I am going wrong.

// add transition finished handler to each page
$('.page').on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function() {
  // toggle in/out of frame
  $(this).toggleClass('in-frame')
    .toggleClass('out-of-frame')
    .addClass('notransition')
    .removeClass('slide')
})

$('body').click(function() {
  // start transform
  $('.page').removeClass('notransition').addClass('slide')
})

html,
body {
  height: 100%;
  overflow: hidden;
  text-align: center;
  font-size: 2em;
}

#content {
  position: relative;
  height: 100%;
}

.page {
  position: absolute;
  top: 0;
  height: 100%;
  width: 100%;
  -webkit-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  -moz-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  -o-transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
  transition: transform 2s cubic-bezier(0.19, 1, 0.22, 1);
}

.slide {
  -webkit-transform: translateX(100%);
  -moz-transform: translateX(100%);
  -o-transform: translateX(100%);
  transform: translateX(100%);
}

.in-frame {
  left: 0%;
}

.out-of-frame {
  left: -100%;
}

.notransition {
  -webkit-transition: none !important;
  -moz-transition: none !important;
  -o-transition: none !important;
  transition: none !important;
}

    Main Page
 (Click Me)

    Other Page
 (Click Me)

Body:
Your way looks good to me, another solution still using CSS transitions could be to use a setTimeout() and create a variable which you check to see if it has changed before allowing another click.

//set a variable
var finish = true;
$('body').click(function() {

    //check to see if last transition has finished
    if(finish == true){

      //set variable to false
      finish = false;
        // start transform
        $('.page').removeClass('notransition').addClass('slide');

        setTimeout(function(){
             finish = true;
             $('.page').toggleClass('in-frame').toggleClass('out-of-frame').addClass('notransition').removeClass('slide')
              }
        ,2000);
    }
});


问:
Error: name is not defined - Recursive function in class
I am still learning Python, and most errors I receive have been syntactical at this point, though I am now receiving an error that reads

NameError: name 'mergeSort' is not defined

I can't seem to understand why when called outside of the class, the method works, though once I include it in the class the function breaks.

```<code>class MergeStringList(list):

    def add(self, item):
        self.append(item)

    def mergeSort(self):
        print("Splitting ",self)
        if len(self)>1:
            mid = len(self)//2
            lefthalf = self[:mid]
            righthalf = self[mid:]

            mergeSort(lefthalf)
            mergeSort(righthalf)

            i=0
            j=0
            k=0

            while i < len(lefthalf) and j < len(righthalf):
                if lefthalf[i] < righthalf[j]:
                    self[k]=lefthalf[i]
                    i=i+1
                else:
                    self[k]=righthalf[j]
                    j=j+1
                    k=k+1

            while i < len(lefthalf):
                self[k]=lefthalf[i]
                i=i+1
                k=k+1

            while j < len(righthalf):
                self[k]=righthalf[j]
                j=j+1
                k=k+1
        print("Merging ",self)

    def printList(self):
        print(self)

mergeList = MergeStringList()
mergeList.add("stitch")
mergeList.add("daily")
mergeList.add("blade")
mergeList.printList()
mergeList.mergeSort()
mergeList.printList()
</code>```

答:
Recurse calls require to invoked on the object i.e. self.mergeSort. Change these two lines:

mergeSort(lefthalf)
mergeSort(righthalf)

Update:

To make the code functional you should also, change the method signature since, it doesn't accept arguments right now. That is,

def mergeSort(self, input)

Body:
I am still learning Python, and most errors I receive have been syntactical at this point, though I am now receiving an error that reads

NameError: name 'mergeSort' is not defined

I can't seem to understand why when called outside of the class, the method works, though once I include it in the class the function breaks.

class MergeStringList(list):

    def add(self, item):
        self.append(item)

    def mergeSort(self):
        print("Splitting ",self)
        if len(self)>1:
            mid = len(self)//2
            lefthalf = self[:mid]
            righthalf = self[mid:]

            mergeSort(lefthalf)
            mergeSort(righthalf)

            i=0
            j=0
            k=0

            while i < len(lefthalf) and j < len(righthalf):
                if lefthalf[i] < righthalf[j]:
                    self[k]=lefthalf[i]
                    i=i+1
                else:
                    self[k]=righthalf[j]
                    j=j+1
                    k=k+1

            while i < len(lefthalf):
                self[k]=lefthalf[i]
                i=i+1
                k=k+1

            while j < len(righthalf):
                self[k]=righthalf[j]
                j=j+1
                k=k+1
        print("Merging ",self)

    def printList(self):
        print(self)

mergeList = MergeStringList()
mergeList.add("stitch")
mergeList.add("daily")
mergeList.add("blade")
mergeList.printList()
mergeList.mergeSort()
mergeList.printList()


问:
Simulation with plotting within for loop - making faster discretization
It must be quiet simple thing, but I'm lost with it. dt/tsym describes rate of change o my values - tsym simulates full hour in seconds and dt one second which in my case is basically one iteration. My objective is to make simulation less accurate but faster - where dt can be 2 second or even 10 seconds. My dt is a part of equations.

```<code>tsym=3600; %[s]
x=zeros(0,tsym)
y=zeros(0,tsym);
h=zeros(0,tsym);
dt=0;

 for dt=1:tsym

Q1=v1*cww*k1*t1+v1*cwp*pwp*t1;
Q2=(dV*cww*k1*t1+dV*cwp*pwp*t1)*(dt/tsym); %out
Q3=(dV*cww*k3*t3+dV*cwp*pwp*t3)*(dt/tsym); %in
Q1=Q1-Q2+Q3; %po jednym cyklu

W1=(v1-dV*(dt/tsym))*k1+dV*(dt/tsym)*k3; %kg
k1=(W1/v1); % kg/m3
%parameters
t1=Q1/(v1*cwp*pwp+cww*W1);
fi1=(k1*1000*(1+0.00366*t1)/(4.88624*(10^(t1*A/(t1+B)))))*100;
%PLOTS
x(dt)=dt;
y(dt)=t1;
h(dt)=fi1;
drawnow

hold on
subplot(2,1,1);
plot(x-1,y);
grid on
title('Temperature');
xlabel('sec');
ylabel('t1 [C]');
subplot(2,1,2);
grid on
plot(x-1,h);
title('Humidity');
xlabel('sec');
ylabel('\Phi [%]');
   end
</code>```

With this code I'm receiving a correct plot but it takes quiet a while. In order to receive it faster i should make sampling time which is dt longer, but if i change for loop step size it just creates another lines for each value of dt every iteration. Should i create separate variables or loops to create faster plots?
Correct plot but takes long to simulate.

Incorrect plot

答:
I assume you want to see the plot animate.  Otherwise you could just do all of the plotting after the loop completes and it would be much faster.

However, if you do want to see it animate then do the following.  Move initial plotting code outside of the loop. Only update your YData of the line handle inside of the loop.  This removes a bunch of the plotting overhead.

I also initialized y and h to NaN so the line was invisible until the parameter is filled.

```<code>tsym=3600; %[s]
dt=0;

% Initialize vars outside of loop
x = 1:tsym;
y = nan(size(x));
h = nan(size(x));

% Initialize plot outside of loop
a(1) = subplot(2,1,1);
lH(1) = plot(a(1),x-1,y);
title(a(1),'Temperature');
xlabel(a(1),'sec');
ylabel(a(1),'t1 [C]');
hold(a(1),'on')
grid(a(1),'on')

a(2) = subplot(2,1,2);
lH(2) = plot(a(2),x-1,h);
title(a(2),'Humidity');
xlabel(a(2),'sec');
ylabel(a(2),'\Phi [%]');
hold(a(2),'on')
grid(a(2),'on')

for dt=1:tsym

    % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    % REMOVED YOUR CODE I COULDN'T TEST
    % Simulate with random number
    % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    y(dt)=rand(1,1); %t1;
    h(dt)=rand(1,1); %fi1;

    %Update Plot
    lH(1).YData = y;
    lH(2).YData = h;
    drawnow
end
</code>```

Body:
It must be quiet simple thing, but I'm lost with it. dt/tsym describes rate of change o my values - tsym simulates full hour in seconds and dt one second which in my case is basically one iteration. My objective is to make simulation less accurate but faster - where dt can be 2 second or even 10 seconds. My dt is a part of equations.

tsym=3600; %[s]
x=zeros(0,tsym)
y=zeros(0,tsym);
h=zeros(0,tsym);
dt=0;

 for dt=1:tsym

Q1=v1*cww*k1*t1+v1*cwp*pwp*t1;
Q2=(dV*cww*k1*t1+dV*cwp*pwp*t1)*(dt/tsym); %out
Q3=(dV*cww*k3*t3+dV*cwp*pwp*t3)*(dt/tsym); %in
Q1=Q1-Q2+Q3; %po jednym cyklu

W1=(v1-dV*(dt/tsym))*k1+dV*(dt/tsym)*k3; %kg
k1=(W1/v1); % kg/m3
%parameters
t1=Q1/(v1*cwp*pwp+cww*W1);
fi1=(k1*1000*(1+0.00366*t1)/(4.88624*(10^(t1*A/(t1+B)))))*100;
%PLOTS
x(dt)=dt;
y(dt)=t1;
h(dt)=fi1;
drawnow

hold on
subplot(2,1,1);
plot(x-1,y);
grid on
title('Temperature');
xlabel('sec');
ylabel('t1 [C]');
subplot(2,1,2);
grid on
plot(x-1,h);
title('Humidity');
xlabel('sec');
ylabel('\Phi [%]');
   end

With this code I'm receiving a correct plot but it takes quiet a while. In order to receive it faster i should make sampling time which is dt longer, but if i change for loop step size it just creates another lines for each value of dt every iteration. Should i create separate variables or loops to create faster plots?
Correct plot but takes long to simulate.

Incorrect plot

Body:
I assume you want to see the plot animate.  Otherwise you could just do all of the plotting after the loop completes and it would be much faster.

However, if you do want to see it animate then do the following.  Move initial plotting code outside of the loop. Only update your YData of the line handle inside of the loop.  This removes a bunch of the plotting overhead.

I also initialized y and h to NaN so the line was invisible until the parameter is filled.

tsym=3600; %[s]
dt=0;

% Initialize vars outside of loop
x = 1:tsym;
y = nan(size(x));
h = nan(size(x));

% Initialize plot outside of loop
a(1) = subplot(2,1,1);
lH(1) = plot(a(1),x-1,y);
title(a(1),'Temperature');
xlabel(a(1),'sec');
ylabel(a(1),'t1 [C]');
hold(a(1),'on')
grid(a(1),'on')

a(2) = subplot(2,1,2);
lH(2) = plot(a(2),x-1,h);
title(a(2),'Humidity');
xlabel(a(2),'sec');
ylabel(a(2),'\Phi [%]');
hold(a(2),'on')
grid(a(2),'on')

for dt=1:tsym

    % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    % REMOVED YOUR CODE I COULDN'T TEST
    % Simulate with random number
    % xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    y(dt)=rand(1,1); %t1;
    h(dt)=rand(1,1); %fi1;

    %Update Plot
    lH(1).YData = y;
    lH(2).YData = h;
    drawnow
end


问:
Observable finally not getting fired
This works:

```<code>this.http.get('/doesntexist1')
  .finally(() => console.log('finally1'))
  .subscribe(() => { });
</code>```

But this doesn't:

```<code>const obs = this.http.get('/doesntexist2');
obs.finally(() => console.log('finally2'))
obs.subscribe(() => { });
</code>```

Both URL produce a 404.

I run both and I only see "finally1" being displayed in the console, any idea why?

答:
The difference is that in the second example the .finally is not in the same stream as the .subscribe since you aren't chaining them.

Your first example creates this stream:

```<code>get -> finally -> subscribe
</code>```

Your second example creates two branches:

```<code>get -> finally
get -> subscribe
</code>```

The finally wont be executed without a subscription after it.

If you want to build a stream then you need to chain the operators by using the result of the previous operator. It isn't like an in-place operator.

Title: Observable finally not getting fired

Body:
This works:

this.http.get('/doesntexist1')
  .finally(() => console.log('finally1'))
  .subscribe(() => { });

But this doesn't:

const obs = this.http.get('/doesntexist2');
obs.finally(() => console.log('finally2'))
obs.subscribe(() => { });

Both URL produce a 404.

I run both and I only see "finally1" being displayed in the console, any idea why?

Body:
The difference is that in the second example the .finally is not in the same stream as the .subscribe since you aren't chaining them.

Your first example creates this stream:

get -> finally -> subscribe

Your second example creates two branches:

get -> finally
get -> subscribe

The finally wont be executed without a subscription after it.

If you want to build a stream then you need to chain the operators by using the result of the previous operator. It isn't like an in-place operator.


问:
How to edit /etc/hosts file in Android Studio emulator running in nougat?
Anyone know how to edit /etc/hosts file inside an android studio emulator running in nougat? I will be editing it so I can use my virtual host in my local web server. I tried  editing it through terminal using adb however, it is returning Read-only file system. Tried also using chmod but still it fails.

Update:
I also tried pulling and pushing files using adb
$ ./adb -s emulator-5554 push ~/Desktop/hosts /system/etc/hosts

adb: error: failed to copy '/Users/Christian/Desktop/hosts' to '/system/etc/hosts': couldn't create file: Read-only file system

答:
Follow the below 3 steps :

Start emulator in writable mode : ./emulator -avd <emulator_name> -writable-system

remount : adb remount

push the hosts file attached : adb push hosts /system/etc/

Note :

Run one and only one emulator_name with above steps

executable emulator is located within android-sdk. For me it was under sdk/emulator.

Attached hosts file will resolve www.facebook.com to 127.0.0.1, hence blocks www.facebook.com on emulator.


问:
Margin ( or padding not sure ) problem in Chrome/Safari
Heres my link ( BE WARNED, its got autoplay audio - sorry...!)

link text

Its not the usual 'looks fine in FF but bad in IE' problem :)

It looks fine in IE6/7 Firefox, but in Chrome & Safari it has big problems with what looks like either margin/padding, or positioning. ( That narrows it down eh? )

If you have a look you'll see what I mean. It looks like I may have a conflict with one of my CSS rules, but then wouldn't that cause problems consistently across all browsers?

Any help and pointers is gratefully received. Thank you.

EDIT:Unsure as to why my reset.css rules are not taking effect...

答:
The problem is the margin-top on the
 inside product-panel-content
s.

Modify the following style in site.css:

```<code>.product-panel-content h4 {
    font-size:140%;
    letter-spacing:-0.5px;
}
</code>```

to be:

```<code>.product-panel-content h4 {
    font-size:140%;
    margin-top:0;
    letter-spacing:-0.5px;
}
</code>```

Will fix the display issue in WebKit-based browsers (Safari and Chrome, for example). I am not sure if this will cause other display issues for your other browsers but experiment with using padding-top on the
 to supplement the lack of margin for spacing on that element if it does.

OwnerDisplayName: Pickledegg

LastEditorDisplayName: Pickledegg

Body:
The problem is the margin-top on the <h4> inside product-panel-content <div>s.

Modify the following style in site.css:

.product-panel-content h4 {
    font-size:140%;
    letter-spacing:-0.5px;
}

to be:

.product-panel-content h4 {
    font-size:140%;
    margin-top:0;
    letter-spacing:-0.5px;
}

Will fix the display issue in WebKit-based browsers (Safari and Chrome, for example). I am not sure if this will cause other display issues for your other browsers but experiment with using padding-top on the <h4> to supplement the lack of margin for spacing on that element if it does.

OwnerDisplayName: bjeanes


问:
How to map + filter in single loop
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

```<code>Array.prototype.filterAndMap = function(){};
</code>```

where I can use it like so:

```<code>[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});
</code>```

the above would return:

```<code>  [4,8]
</code>```

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

```<code>   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });
</code>```

答:
You could iterate the array and concat the value if valid or an empty array if not.

var array = [1, 2, 3, 4, 5],
    result = array.reduce(function(r, a) {
        return r.concat(a % 2 ? [] : 2 * a);
    }, []);

console.log(result);```
</div>
</div>
</p>

<p>ES6</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [1, 2, 3, 4, 5],
    result = array.reduce((r, a) => r.concat(a % 2 ? [] : 2 * a), []);

console.log(result);</code>```

Title: How to map + filter in single loop

Body:
I have asked this question on SO before but I cannot find the question/answers!

Basically I want to create this:

Array.prototype.filterAndMap = function(){};

where I can use it like so:

[1,2,3,4,5].filterAndMap(function(){
     if(i % 2 === 0){
        return i*2;
     }
});

the above would return:

  [4,8]

I think the best way to implement this is using Array.prototype.reduce...but I am not sure.

What I am trying to avoid, is iterating through the list twice:

   [1,2,3,4,5].filter(function(){
         return i % 2 === 0;
    })
    .map(function(i){
         return i * 2;
    });

Body:
You could iterate the array and concat the value if valid or an empty array if not.

var array = [1, 2, 3, 4, 5],
    result = array.reduce(function(r, a) {
        return r.concat(a % 2 ? [] : 2 * a);
    }, []);

console.log(result);

ES6

var array = [1, 2, 3, 4, 5],
    result = array.reduce((r, a) => r.concat(a % 2 ? [] : 2 * a), []);

console.log(result);


问:
Can you have multiple .net Consoles (as in Console.Writeline)
It would be handy during debugging to have multiple consoles (not multiple monitors, which I already have).  I am imagining something like Console.WriteLine(1, String1) which would send  String1 to one console window 1 and Console.WriteLine(2, String2) which would send String2 to console window 2.</p>

答:
I had the same need and I found your question here in SO. A lot of years later :)

In fact, .NET doesn't have this capability, but we can simulate it by splitting the screen with a grid, using some buffering.

Here is an example:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void print(int x, int y, int n)
        {
            for(int i = 0; i < 20; i++)
            {
                Console.CursorLeft = x; Console.CursorTop = y++;
                Console.Write(new string(n.ToString().Last(), 60));
            }
        }

        static void Main(string[] args)
        {
            var l = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            while (true)
            {
                Console.Clear();
                Console.CursorVisible = false;

                for (int i = 0; i < l.Count; i++)
                {
                    print((i % 3) * 60, (i / 3) * 20, l[i]++);
                }

                Task.Delay(1000).Wait();
            }
        }
    }
}
</code>```

So the screen is divided into a 3x3 grid and each screen is updated using the cursor position.

It could be packaged into a lib and a generic API, like you described:

```<code>Console.WriteLine(1, String1)
Console.WriteLine(2, String2)
</code>```

Hope it helps someone.

OwnerDisplayName: NormD

Body:
I had the same need and I found your question here in SO. A lot of years later :)

In fact, .NET doesn't have this capability, but we can simulate it by splitting the screen with a grid, using some buffering.

Here is an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void print(int x, int y, int n)
        {
            for(int i = 0; i < 20; i++)
            {
                Console.CursorLeft = x; Console.CursorTop = y++;
                Console.Write(new string(n.ToString().Last(), 60));
            }
        }

        static void Main(string[] args)
        {
            var l = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            while (true)
            {
                Console.Clear();
                Console.CursorVisible = false;

                for (int i = 0; i < l.Count; i++)
                {
                    print((i % 3) * 60, (i / 3) * 20, l[i]++);
                }

                Task.Delay(1000).Wait();
            }
        }
    }
}

So the screen is divided into a 3x3 grid and each screen is updated using the cursor position.

It could be packaged into a lib and a generic API, like you described:

Console.WriteLine(1, String1)
Console.WriteLine(2, String2)

Hope it helps someone.


问:
async constructor functions in TypeScript?
I have some setup I want during a constructor, but it seems that is not allowed

Which means I can't use:

How else should I do this?

Currently I have something outside like this, but this is not guaranteed to run in the order I want?

```<code>async function run() {
  let topic;
  debug("new TopicsModel");
  try {
    topic = new TopicsModel();
  } catch (err) {
    debug("err", err);
  }

  await topic.setup();
</code>```

答:
Use an asynchronous factory method instead.

```<code>class MyClass {
   private mMember: Something;

   constructor() {
      this.mMember = await SomeFunctionAsync(); // error
   }
}
</code>```

Becomes:

```<code>class MyClass {
   private mMember: Something;

   // make private if possible; I can't in TS 1.8
   constructor() {
   }

   public static CreateAsync = async () => {
      const me = new MyClass();

      me.mMember = await SomeFunctionAsync();

      return me;
   };
}
</code>```

This will mean that you will have to await the construction of these kinds of objects, but that should already be implied by the fact that you are in the situation where you have to await something to construct them anyway.

There's another thing you can do but I suspect it's not a good idea:

```<code>// probably BAD
class MyClass {
   private mMember: Something;

   constructor() {
      this.LoadAsync();
   }

   private LoadAsync = async () => {
      this.mMember = await SomeFunctionAsync();
   };
}
</code>```

This can work and I've never had an actual problem from it before, but it seems to be dangerous to me, since your object will not actually be fully initialized when you start using it.

Another way to do it, which might be better than the first option in some ways, is to await the parts, and then construct your object after:

```<code>export class MyClass {
   private constructor(
      private readonly mSomething: Something,
      private readonly mSomethingElse: SomethingElse
   ) {
   }

   public static CreateAsync = async () => {
      const something = await SomeFunctionAsync();
      const somethingElse = await SomeOtherFunctionAsync();

      return new MyClass(something, somethingElse);
   };
}
</code>```

Body:
I have some setup I want during a constructor, but it seems that is not allowed

Which means I can't use:

How else should I do this?

Currently I have something outside like this, but this is not guaranteed to run in the order I want?

async function run() {
  let topic;
  debug("new TopicsModel");
  try {
    topic = new TopicsModel();
  } catch (err) {
    debug("err", err);
  }

  await topic.setup();

Body:
Use an asynchronous factory method instead.

class MyClass {
   private mMember: Something;

   constructor() {
      this.mMember = await SomeFunctionAsync(); // error
   }
}

Becomes:

class MyClass {
   private mMember: Something;

   // make private if possible; I can't in TS 1.8
   constructor() {
   }

   public static CreateAsync = async () => {
      const me = new MyClass();

      me.mMember = await SomeFunctionAsync();

      return me;
   };
}

This will mean that you will have to await the construction of these kinds of objects, but that should already be implied by the fact that you are in the situation where you have to await something to construct them anyway.

There's another thing you can do but I suspect it's not a good idea:

// probably BAD
class MyClass {
   private mMember: Something;

   constructor() {
      this.LoadAsync();
   }

   private LoadAsync = async () => {
      this.mMember = await SomeFunctionAsync();
   };
}

This can work and I've never had an actual problem from it before, but it seems to be dangerous to me, since your object will not actually be fully initialized when you start using it.

Another way to do it, which might be better than the first option in some ways, is to await the parts, and then construct your object after:

export class MyClass {
   private constructor(
      private readonly mSomething: Something,
      private readonly mSomethingElse: SomethingElse
   ) {
   }

   public static CreateAsync = async () => {
      const something = await SomeFunctionAsync();
      const somethingElse = await SomeOtherFunctionAsync();

      return new MyClass(something, somethingElse);
   };
}

ContentLicense: CC BY-SA 4.0


答:
Telnet is just an easy interactive way to open a TCP connection to a listening socket.  Because the telnet client blindly sends what you type to that socket, it can theoretically emulate any other protocol on top of TCP.  Actually the fact that non printable chars are interpreted by the keyboard driver is the only limit.

HTTP does not use non printable chars except to delimit between  the HTTP header and the body with two consecutive "line breaks" (i.e. a "blank line").

Please note that I'm not talking about the HTML body tag here, but the payload (e.g SOAP body).

No magic here basically.

Let's see the dynamic of things.

HTTP supports a number of commands like GET, POST, PUT etc...
Each command has its syntax and there is an associated response with an agreed upon syntax and well defined error codes.
When you connect to an HTTP server using telnet, you open the socket connection and the server forks a thread to manage the dialog with your client.  You can then mimic a browser by typing the command that the browser would send. Each time you strike the CR key, the client submits the line to the server.  If a command contains several lines, you can enter several lines, each of them corresponding to a line of the command header.  Once you strike two CR in a row (i.e. an empty line), the command header is deemed complete by the server and the response is put together and sent back to your client.  Because a telnet client's life goal is to echo received characters (unless told otherwise), then you can see the response header and body on your terminal window.  Telnet stops there.  A browser would render the HTML (if the response is an HTML page).

I hope that clarifies it all.

Title: How HTTP servers accepts Telnet

Body: I understand that Telnet is a protocol as much as HTTP. I have this notion that after the initial TCP connection is made the Telnet client would send some telnet specific code over to the server on the other side in this case a HTTP server. But since HTTP server doesn't understand Telnet specific codes it should throw an error or drop the connection etc. But in reality we can telnet to a HTTP server and fetch pages if we type in correct HTTP headers and send them. How can it be like that? Wikipedia entry really didn't help me to understand this specific point. (http://en.wikipedia.org/wiki/Telnet#Telnet_data)


问:
JavaScript Save Cookies
I am following a tutorial for cookies and in the tutorial you enter your name, and you can refresh then display your name, so the name is actually saved as a cookie. However when I am trying this in a personal file, the cookie is not being saved if I refresh the page, I can only see the cookie once per session, so how do I save the cookie for as many sessions as I want?

I suppose you can't use cookies in a snippet, but if you can help, copy and paste this into a personal file.

function WriteCookie() {
  customer = document.getElementById('customer');
  if (customer.innerHTML == "") {
    alert("Enter some value!");
    return;
  }
  cookievalue = escape(customer.innerHTML);
  document.cookie = "name=" + cookievalue;
  console.log("name=" + cookievalue);

  // expires
  var now = new Date();
  now.setMonth(now.getMonth() + 1);

  document.cookie = "expires=" + now.toUTCString() + ";"
  // output = document.getElementById('output');
  // output.innerHTML = cookievalue;
}

function ReadCookie() {
  var allcookies = document.cookie;
  console.log("All Cookies : " + allcookies);

  // Get all the cookies pairs in an array
  cookiearray = allcookies.split(';');

  // Now take key value pair out of this array
  for (var i = 0; i < cookiearray.length; i++) {
    name = cookiearray[i].split('=')[0];
    value = cookiearray[i].split('=')[1];
    console.log("Key is : " + name + " and Value is : " + value);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
</head>

<body>
  <form name="myform" action="">
    <!-- Enter name: <input type="text" name="customer"/> -->
    <h4>Enter Name:</h4>
    <h4 contenteditable="true" id="customer" style="background-color: #eee"></h4>
    <!-- <h4>Your Name is:</h4>
         <h4 id="output" style="width: 100%; height: 20px; background-color: #ddd;"></h4> -->
    <input type="button" value="Set Cookie" onclick="WriteCookie();" />
    <input type="button" value="Read Cookie" onclick="ReadCookie();" />
  </form>
</body>

</html></code>```

答:
Cookies are stored (in the browser) associated with a particular origin. Cookies are not supported on pages loaded with file: scheme URLs, as they lack hostnames.

Use HTTP (or HTTPS) instead.

Title: JavaScript Save Cookies

Body:
I am following a tutorial for cookies and in the tutorial you enter your name, and you can refresh then display your name, so the name is actually saved as a cookie. However when I am trying this in a personal file, the cookie is not being saved if I refresh the page, I can only see the cookie once per session, so how do I save the cookie for as many sessions as I want?

I suppose you can't use cookies in a snippet, but if you can help, copy and paste this into a personal file.

function WriteCookie() {
  customer = document.getElementById('customer');
  if (customer.innerHTML == "") {
    alert("Enter some value!");
    return;
  }
  cookievalue = escape(customer.innerHTML);
  document.cookie = "name=" + cookievalue;
  console.log("name=" + cookievalue);

  // expires
  var now = new Date();
  now.setMonth(now.getMonth() + 1);

  document.cookie = "expires=" + now.toUTCString() + ";"
  // output = document.getElementById('output');
  // output.innerHTML = cookievalue;
}

function ReadCookie() {
  var allcookies = document.cookie;
  console.log("All Cookies : " + allcookies);

  // Get all the cookies pairs in an array
  cookiearray = allcookies.split(';');

  // Now take key value pair out of this array
  for (var i = 0; i < cookiearray.length; i++) {
    name = cookiearray[i].split('=')[0];
    value = cookiearray[i].split('=')[1];
    console.log("Key is : " + name + " and Value is : " + value);
  }
}

  <form name="myform" action="">

Enter Name:

    <input type="button" value="Set Cookie" onclick="WriteCookie();" />
    <input type="button" value="Read Cookie" onclick="ReadCookie();" />
  </form>


问:
How to insert an array in MySQL table with Laravel ORM
I am trying to insert an entire api response into a MySQL table using Laravel Eloquent but I am getting 'Array to string conversion' error. How do I solve this?

Please note, it is compulsory that I save the entire API response.

My API call

```<code>$response = Curl::to($url.$request->account_number)
                    ->withData($data)
                    ->asJson(true)
                    ->get();
</code>```

My Query

```<code> TransactionLog::create([
                        'payer' => $request->payer,
                        'amount' => $request->amount,
                        'phone' => $request->phone,
                        'response' => $response

                    ]);
</code>```

答:
Looks like you using ixudra/curl ?

With asJson(true) you will receive json_decode response, so if your plan is to save raw json response in the database you'll have to json_encode it like:

```<code>TransactionLog::create([
  'payer' => $request->payer,
  'amount' => $request->amount,
  'phone' => $request->phone,
  'response' => json_encode($response)
]);
</code>```

Body:
I am trying to insert an entire api response into a MySQL table using Laravel Eloquent but I am getting 'Array to string conversion' error. How do I solve this?

Please note, it is compulsory that I save the entire API response.

My API call

$response = Curl::to($url.$request->account_number)
                    ->withData($data)
                    ->asJson(true)
                    ->get();

My Query

 TransactionLog::create([
                        'payer' => $request->payer,
                        'amount' => $request->amount,
                        'phone' => $request->phone,
                        'response' => $response

                    ]);

Body:
Looks like you using ixudra/curl ?

With asJson(true) you will receive json_decode response, so if your plan is to save raw json response in the database you'll have to json_encode it like:

TransactionLog::create([
  'payer' => $request->payer,
  'amount' => $request->amount,
  'phone' => $request->phone,
  'response' => json_encode($response)
]);


问:
SSIS Azure BLOB / DW Upload task error
When trying to load a text file using the Azure SQL DW Upload Task in SSIS, I get the following error:

Error: 0x0 at Azure SQL DW Upload Task, Azure SQL DW Upload Task:
  Failed to upload to blob storage. Unable to create Azure Blob
  container. Endpoint: https://[removed].blob.core.windows.net/,
  Container Name: [myContainer]. The remote server returned an error: (403)
  Forbidden. The remote server returned an error: (403) Forbidden

Tthe SSIS task is failing.I also tried the BLOB upload task and that fails. Any help is appreciated.

答:
For anyone who deosn't want to beat their head against the wall, here was the issue / solution:

I had "PackageProtectionLevel" set to "DoNotSaveSensitive" so I used Package Parameters to configure Password / SecurityToken and then set those as the task values with an expression. SSIS shold have thrown a better error, but at least its solved

Title: SSIS Azure BLOB / DW Upload task error


问:
Redux state clear on page changes
I have react container which is connected to an 'items' reducer. By navigating to another page, such as user profile, I want to get the user's 'items' list from the server and change the state. The issue is, that if I navigate from the main page, the items state is already filled with data, then on the user page I see the old for couple of seconds until it is changed from the api call. I was thinking about creating new reducer for the userItems, but then, if I will navigate to another user page, I will see the previous userItems for couple of seconds.

The solution is to fetch the data and keep it only in the react component state? And not redux?

Thanks.

答:
I think the two better options for tackling this problem are:

If you really want your redux state to only contain the 'items' relative to the page you are looking at, you could include a 'fetching' attribute in your state, and show a loading bar while you call the API and update your state

You could store a user's 'items' in an array inside the user object in your state, and then display user.items for the relevant user. You don't necessarily have to have all users 'items' in the redux store at all times.  If you were to do this without a loading indicator, the user page would load with no items, and the items would appear once the API was called and the Redux state updated

Title: Redux state clear on page changes


问:
Grunt task for combining multiple Jquery ready functions into single ready function
I have ready functions spread across multiple files which I am looking to merge and minify. Is there a grunt task which will merge all ready into one function ?

```<code>// file1.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })
})

// file2.js
$(document).ready(function(){
    $(".class3").on("blur", function () {
        // Some Action
    })
})

// file3.js
$(document).ready(function(){
    $(".class2").on("change", function () {
        // Some Action
    })
})

// file4.js
$(document).ready(function(){
    $(".class3").click(function () {
        // Some Action
    })
})
</code>```

I am looking for something like ...

```<code>// file.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })

    $(".class3").on("blur", function () {
        // Some Action
    })

    $(".class2").on("change", function () {
        // Some Action
    })

    $(".class3").click(function () {
        // Some Action
    })
})
</code>```

Will it harm the performance if I just run grunt task to combine all the files and have multiple ready functions in a file merged like this using grunt-contrib-uglify ?

```<code>// file.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class3").on("blur", function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class2").on("change", function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class3").click(function () {
        // Some Action
    })
})
</code>```

Thank you for checking this question out. Have a great day. Sorry if this is a repeat question. Posting this question because could not find the answer anywhere else.

答:
You can use grunt-jquery-ready which will do what you want.

You should concat first all your files and then use this grunt plugin in this way. I tested this and It works

grunt.initConfig({
  'jquery-ready' : {
      path: 'path_to_your_folder/your_script_file.js',
      runSync: false
  }

  grunt.loadNpmTasks('grunt-jquery-ready');

  grunt.registerTask('default', "jquery-ready");
});```
</div>
</div>

as a result after executing this I got my file in this format:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>$(document).ready(function(){
  all the content of my script.js file is placed here automatically.
});</code>```

Please refer to the main website for more information:

Wrapping your concatenated .js file into ready function

Body:
I have ready functions spread across multiple files which I am looking to merge and minify. Is there a grunt task which will merge all ready into one function ?

// file1.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })
})

// file2.js
$(document).ready(function(){
    $(".class3").on("blur", function () {
        // Some Action
    })
})

// file3.js
$(document).ready(function(){
    $(".class2").on("change", function () {
        // Some Action
    })
})

// file4.js
$(document).ready(function(){
    $(".class3").click(function () {
        // Some Action
    })
})

I am looking for something like ...

// file.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })

    $(".class3").on("blur", function () {
        // Some Action
    })

    $(".class2").on("change", function () {
        // Some Action
    })

    $(".class3").click(function () {
        // Some Action
    })
})

Will it harm the performance if I just run grunt task to combine all the files and have multiple ready functions in a file merged like this using grunt-contrib-uglify ?

// file.js
$(document).ready(function(){
    $(".class1").click(function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class3").on("blur", function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class2").on("change", function () {
        // Some Action
    })
})

$(document).ready(function(){
    $(".class3").click(function () {
        // Some Action
    })
})

Thank you for checking this question out. Have a great day. Sorry if this is a repeat question. Posting this question because could not find the answer anywhere else.

Body:
You can use grunt-jquery-ready which will do what you want.

You should concat first all your files and then use this grunt plugin in this way. I tested this and It works

grunt.initConfig({
  'jquery-ready' : {
      path: 'path_to_your_folder/your_script_file.js',
      runSync: false
  }

  grunt.loadNpmTasks('grunt-jquery-ready');

  grunt.registerTask('default', "jquery-ready");
});

as a result after executing this I got my file in this format:

$(document).ready(function(){
  all the content of my script.js file is placed here automatically.
});

Please refer to the main website for more information:

Wrapping your concatenated .js file into ready function


问:
Unable to use LayoutInflater in custom adapter
I'm looking into writing a custom adapter to populate a listview with 3 textviews per line. I've found quite a bit of example code to do this, but the one that seemed the best was at: http://www.anddev.org/custom_widget_adapters-t1796.html

After a few minor tweaks to fix some compiler issues with the latest Android SDK, I got it running, only to get the exception:

ERROR/AndroidRuntime(281): java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

So I did a lot of research and found lots of possible reasons and fixes for this. None of which changed a thing. My adapter code is currently:

```<code>public class WeatherAdapter extends BaseAdapter {

    private Context context;
    private List<Weather> weatherList;

    public WeatherAdapter(Context context, int rowResID,
                        List<Weather> weatherList ) {
        this.context = context;
        this.weatherList = weatherList;
    }

    public int getCount() {
        return weatherList.size();
    }

    public Object getItem(int position) {
        return weatherList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Weather weather = weatherList.get(position);

        //LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater inflater = LayoutInflater.from(context);

        View v = inflater.inflate(R.layout.weather_row, null, true);
        TextView cityControl = (TextView)v.findViewById( R.id.city );
        TextView temperatureControl = (TextView)v.findViewById( R.id.temperature );
        ImageView skyControl = (ImageView)v.findViewById( R.id.sky );
        return v;
    }

}
</code>```

So I have tried the commented out way of getting the inflater, and the currently uncommented out. I have tried passing "parent" to inflate as well as null, and passing "true", "false" and omitting completely the last parameter.  None of them have worked, and all examples I've found so far have been from 2008 which I get the feeling are a bit outdated.

If anyone could help with this then I would love to resolve the issue.

答:
I'm a beginner also so take this answer with a pinch of salt - if it doesn't work, move on and Google some more. Not familiar with AdapterView since I traditionally have a ListView or GridView and a custom Adapter extended off a BaseAdapter and then listView.setAdapter(myCustomAdapter).

You could try making something like this inside the WeatherAdapter class:

```<code>public void addToList(Weather mWeather) {
    weatherList.add(mWeather);
}
</code>```

Then in the class that calls WeatherAdapter:

```<code>weatherAdapter.addToList(weatherToAdd);
weatherAdapter.notifyDataSetChanged();
</code>```

Also you need to optimize it more in the getView method:

http://www.youtube.com/watch?v=wDBM6wVEO70

Body:
I'm looking into writing a custom adapter to populate a listview with 3 textviews per line. I've found quite a bit of example code to do this, but the one that seemed the best was at: http://www.anddev.org/custom_widget_adapters-t1796.html

After a few minor tweaks to fix some compiler issues with the latest Android SDK, I got it running, only to get the exception:

ERROR/AndroidRuntime(281): java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

So I did a lot of research and found lots of possible reasons and fixes for this. None of which changed a thing. My adapter code is currently:

public class WeatherAdapter extends BaseAdapter {

    private Context context;
    private List<Weather> weatherList;

    public WeatherAdapter(Context context, int rowResID,
                        List<Weather> weatherList ) {
        this.context = context;
        this.weatherList = weatherList;
    }

    public int getCount() {
        return weatherList.size();
    }

    public Object getItem(int position) {
        return weatherList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Weather weather = weatherList.get(position);

        //LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater inflater = LayoutInflater.from(context);

        View v = inflater.inflate(R.layout.weather_row, null, true);
        TextView cityControl = (TextView)v.findViewById( R.id.city );
        TextView temperatureControl = (TextView)v.findViewById( R.id.temperature );
        ImageView skyControl = (ImageView)v.findViewById( R.id.sky );
        return v;
    }

}

So I have tried the commented out way of getting the inflater, and the currently uncommented out. I have tried passing "parent" to inflate as well as null, and passing "true", "false" and omitting completely the last parameter.  None of them have worked, and all examples I've found so far have been from 2008 which I get the feeling are a bit outdated.

If anyone could help with this then I would love to resolve the issue.

Body:
I'm a beginner also so take this answer with a pinch of salt - if it doesn't work, move on and Google some more. Not familiar with AdapterView since I traditionally have a ListView or GridView and a custom Adapter extended off a BaseAdapter and then listView.setAdapter(myCustomAdapter).

You could try making something like this inside the WeatherAdapter class:

public void addToList(Weather mWeather) {
    weatherList.add(mWeather);
}

Then in the class that calls WeatherAdapter:

weatherAdapter.addToList(weatherToAdd);
weatherAdapter.notifyDataSetChanged();

Also you need to optimize it more in the getView method:

http://www.youtube.com/watch?v=wDBM6wVEO70


问:
Animate a border with CSS
I want to recreate a CSS animation in my computer (local) but it's not working, when I try the code in Codepen it's working, what am I doing wrong?

Here is the code: https://codepen.io/jvera/pen/gXxgXx

{
  background: none;
  border: 0;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  margin: 1em;
  padding: 1em 2em;
  text-align: center;
  text-transform: capitalize;
  vertical-align: middle;
}
.draw {
  overflow: hidden;
  position: relative;
}
.draw::before, .draw::after {
  content: '';
  box-sizing: border-box;
  position: absolute;
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  animation: border 2s infinite;
}
.draw::after {
  bottom: 0;
  right: 0;
  animation: border 2s 1s infinite, borderColor 2s 1s infinite;
}

@keyframes border {
  0% {
    width: 0;
    height: 0;
  }
  25% {
    width: 100%;
    height: 0;
  }
  50% {
    width: 100%;
    height: 100%;
  }
  100% {
    width: 100%;
    height: 100%;
  }
}
@keyframes borderColor {
  0% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  50% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  51% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
  100% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><center><h2 class="draw">Titulo</h2><center></code>```

I created the two files and put them into the folder, when I run the HTML file I can't see the animation effect (like the demo) so, what can I do? why I'm not seeing the results?

Thanks.

答: Try adding the -WebKit-keyframes feature. It might be your browser. Link to how to do it </p>

Title: Animate a border with CSS

Body:
I want to recreate a CSS animation in my computer (local) but it's not working, when I try the code in Codepen it's working, what am I doing wrong?

Here is the code: https://codepen.io/jvera/pen/gXxgXx

{
  background: none;
  border: 0;
  box-sizing: border-box;
  box-shadow: inset 0 0 0 2px #f45e61;
  color: #f45e61;
  font-size: inherit;
  font-weight: 700;
  margin: 1em;
  padding: 1em 2em;
  text-align: center;
  text-transform: capitalize;
  vertical-align: middle;
}
.draw {
  overflow: hidden;
  position: relative;
}
.draw::before, .draw::after {
  content: '';
  box-sizing: border-box;
  position: absolute;
  border: 2px solid transparent;
  width: 0;
  height: 0;
}
.draw::before {
  top: 0;
  left: 0;
  border-top-color: #60daaa;
  border-right-color: #60daaa;
  animation: border 2s infinite;
}
.draw::after {
  bottom: 0;
  right: 0;
  animation: border 2s 1s infinite, borderColor 2s 1s infinite;
}

@keyframes border {
  0% {
    width: 0;
    height: 0;
  }
  25% {
    width: 100%;
    height: 0;
  }
  50% {
    width: 100%;
    height: 100%;
  }
  100% {
    width: 100%;
    height: 100%;
  }
}
@keyframes borderColor {
  0% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  50% {
    border-bottom-color: #60daaa;
    border-left-color: #60daaa;
  }
  51% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
  100% {
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
}

Titulo

I created the two files and put them into the folder, when I run the HTML file I can't see the animation effect (like the demo) so, what can I do? why I'm not seeing the results?

Thanks.


问:
Sum a list of options in Scala
How can I sum a list of options List[Option[Double]] with the following rules?

List(Some(1), ..., Some(n)) --> Some(1 + ... + n)

List(Some(1), ..., Some(n), None) --> None

List(None, ..., None) --> None

答:
There is even a simpler way just using fold:

```<code>val ls = List(Some(2.1d), Some(5.6d), Some(4.3d), Some(1.2))

ls.fold(Option(0d))((rs,x) => for(n <- x; m <- rs) yield {n+m})
</code>```

=> Some(13.2)

```<code>val ls = List(Some(2.1d),None, Some(5.6d), Some(4.3d), Some(1.2))

ls.fold(Option(0d))((rs,x) => for(n <- x; m <- rs) yield {n+m})
</code>```

=> None

Title: Sum a list of options in Scala

Body:
There is even a simpler way just using fold:

val ls = List(Some(2.1d), Some(5.6d), Some(4.3d), Some(1.2))

ls.fold(Option(0d))((rs,x) => for(n <- x; m <- rs) yield {n+m})

=> Some(13.2)

val ls = List(Some(2.1d),None, Some(5.6d), Some(4.3d), Some(1.2))

ls.fold(Option(0d))((rs,x) => for(n <- x; m <- rs) yield {n+m})

=> None


问:
Python turtle game, making walls that aren't outside borders
I am trying to make a game in Python turtle. I know that's not what it's made for, but I thought it would be fun. I have a "river" in my game that I don't want players be able to cross unless they cross the bridge, so I'm trying to make it so that they get set back to the start if they try to cross the river without using the bridge. I just don't know how to do this after multiple attempts.
Here is my code:</p>

```<code>import turtle
import random
import time
wn = turtle.Screen()
layout = turtle.Turtle()
layout.speed(100)
layout.up()

wn.bgcolor("lightgreen")
def drawTree(t, sd):
for i in range(4):
    layout.down()
    t.forward(sd)
    t.right(90)
    layout.up()

def drawRiver():
for i in range(2):
    print(layout.pos()[0])
    print(layout.pos()[1])
    layout.color("darkblue")
    layout.fillcolor("blue")
    layout.begin_fill()
    layout.down()
    layout.forward(2000)
    layout.right(90)
    layout.forward(99)
    layout.right(90)
    layout.forward(4000)
    layout.end_fill()
    layout.up()

def tree(branchLen,layout):
if branchLen > 6:
    layout.down()
    layout.forward(branchLen)
    layout.right(20)
    tree(branchLen-6,layout)
    layout.left(40)
    tree(branchLen-6,layout)
    layout.right(20)
    layout.backward(branchLen)
    layout.up()

def main():
myWin = turtle.Screen()
layout.left(90)
layout.up()
layout.backward(100)
layout.down()
layout.color("brown")
tree(36,layout)
layout.right(90)
layout.up()

def drawBridge():
layout.goto(50, -120)
layout.down()
layout.color("rosybrown4")
layout.fillcolor("saddlebrown")
layout.begin_fill()
layout.forward(100)
layout.left(90)
layout.forward(150)
layout.left(90)
layout.forward(100)
layout.left(90)
layout.forward(150)
layout.left(90)
layout.up()
layout.end_fill()
layout.goto(150, -118)
layout.left(90)
for i in range(38):
    layout.pensize(.1)
    layout.down()
    layout.color("black")
    layout.forward(.1)
    layout.left(90)
    layout.forward(100)
    layout.left(90)
    layout.forward(.1)
    layout.left(90)
    layout.forward(100)
    layout.left(90)
    layout.up()
    layout.forward(4)
layout.up()
layout.right(90)

layout.goto(-799, 0)
drawRiver()
drawBridge()
# Tree locations
layout.goto(222, 198)
main()
layout.goto(-334, 155)
main()
layout.goto(132, 140)
main()
layout.goto(400, -200)
main()
layout.goto(50, -222)
main()
layout.goto(180, -122)
main()
layout.goto(-400, 400)
main()
layout.goto(-332, -332)
main()
layout.goto(-472, 400)
main()
layout.goto(-400, -380)
main()
layout.goto(-362,200)
main()
layout.goto(-222, 198)
main()
layout.goto(-750, -300)
main()
layout.goto(600, -467)
main()
layout.goto(100, 450)
main()
layout.goto(-100, 400)
main()
layout.goto(-600, 400)
main()
layout.goto(500, 123)
main()
layout.goto(700, 400)
main()
layout.goto(350, 350)
main()

layout.color("blue")
layout.goto(0, -50)
Player = turtle.Turtle()
Player.up()
Player.goto(0, -200)
Player.left(90)

def k1():
Player.forward(45)

def k2():
Player.left(30)

def k3():
Player.right(30)

def k4():
Player.back(45)

wn.onkey(k1, "Up")
wn.onkey(k2, "Left")
wn.onkey(k3, "Right")
wn.onkey(k4, "Down")

wn.listen()
</code>```

答:
Your code is a challenge to work with.

For this example, I've tossed your trees and bridge planks as they have no affect on the problem.  Since your river and bridge are rectangular, I've wrapped their drawing in a begin_poly() and end_poly() combination so that we have the bounding boxes of those rectangles.  Then, for the two movement commands (forward and backward) we test if the resulting movement puts us in the river, but not the bridge, and simply goto() the starting position if that's the case:

```<code>from turtle import Turtle, Screen

def inside(point, rectangle):
    x, y = point

    # not efficient, just a quick solution
    x1 = min(p[0] for p in rectangle)
    y1 = min(p[1] for p in rectangle)
    x2 = max(p[0] for p in rectangle)
    y2 = max(p[1] for p in rectangle)

    return x1 < x < x2 and y1 < y < y2

def not_safe(turtle):
    position = turtle.position()
    return inside(position, river) and not inside(position, bridge)

def drawRiver(turtle):
    turtle.color('darkblue', 'blue')

    turtle.goto(-WIDTH / 2, 0)

    turtle.begin_poly()
    turtle.begin_fill()
    turtle.forward(WIDTH)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(WIDTH)
    turtle.end_fill()
    turtle.end_poly()

    return turtle.get_poly()

def drawBridge(turtle):
    turtle.right(180)
    turtle.goto(50, -120)
    turtle.color('rosybrown4', 'saddlebrown')

    turtle.begin_poly()
    turtle.begin_fill()
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(150)
    turtle.left(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.end_fill()
    turtle.end_poly()

    return turtle.get_poly()

wn = Screen()
wn.bgcolor('lightgreen')
WIDTH = wn.window_width()

layout = Turtle(visible=False)
layout.speed('fastest')
layout.penup()

river = drawRiver(layout)
bridge = drawBridge(layout)

player = Turtle('turtle')
player.penup()

player.goto(0, -200)
player.setheading(90)

def k1():
    player.forward(45)
    if not_safe(player):
        player.goto(0, -200)
        player.setheading(90)

def k2():
    player.back(45)
    if not_safe(player):
        player.goto(0, -200)
        player.setheading(90)

def k3():
    player.left(30)

def k4():
    player.right(30)

wn.onkey(k1, 'Up')
wn.onkey(k2, 'Down')
wn.onkey(k3, 'Left')
wn.onkey(k4, 'Right')

wn.listen()
wn.mainloop()
</code>```

Body:
I am trying to make a game in Python turtle. I know that's not what it's made for, but I thought it would be fun. I have a "river" in my game that I don't want players be able to cross unless they cross the bridge, so I'm trying to make it so that they get set back to the start if they try to cross the river without using the bridge. I just don't know how to do this after multiple attempts.
Here is my code:

import turtle
import random
import time
wn = turtle.Screen()
layout = turtle.Turtle()
layout.speed(100)
layout.up()

wn.bgcolor("lightgreen")
def drawTree(t, sd):
for i in range(4):
    layout.down()
    t.forward(sd)
    t.right(90)
    layout.up()

def drawRiver():
for i in range(2):
    print(layout.pos()[0])
    print(layout.pos()[1])
    layout.color("darkblue")
    layout.fillcolor("blue")
    layout.begin_fill()
    layout.down()
    layout.forward(2000)
    layout.right(90)
    layout.forward(99)
    layout.right(90)
    layout.forward(4000)
    layout.end_fill()
    layout.up()

def tree(branchLen,layout):
if branchLen > 6:
    layout.down()
    layout.forward(branchLen)
    layout.right(20)
    tree(branchLen-6,layout)
    layout.left(40)
    tree(branchLen-6,layout)
    layout.right(20)
    layout.backward(branchLen)
    layout.up()

def main():
myWin = turtle.Screen()
layout.left(90)
layout.up()
layout.backward(100)
layout.down()
layout.color("brown")
tree(36,layout)
layout.right(90)
layout.up()

def drawBridge():
layout.goto(50, -120)
layout.down()
layout.color("rosybrown4")
layout.fillcolor("saddlebrown")
layout.begin_fill()
layout.forward(100)
layout.left(90)
layout.forward(150)
layout.left(90)
layout.forward(100)
layout.left(90)
layout.forward(150)
layout.left(90)
layout.up()
layout.end_fill()
layout.goto(150, -118)
layout.left(90)
for i in range(38):
    layout.pensize(.1)
    layout.down()
    layout.color("black")
    layout.forward(.1)
    layout.left(90)
    layout.forward(100)
    layout.left(90)
    layout.forward(.1)
    layout.left(90)
    layout.forward(100)
    layout.left(90)
    layout.up()
    layout.forward(4)
layout.up()
layout.right(90)

layout.goto(-799, 0)
drawRiver()
drawBridge()
# Tree locations
layout.goto(222, 198)
main()
layout.goto(-334, 155)
main()
layout.goto(132, 140)
main()
layout.goto(400, -200)
main()
layout.goto(50, -222)
main()
layout.goto(180, -122)
main()
layout.goto(-400, 400)
main()
layout.goto(-332, -332)
main()
layout.goto(-472, 400)
main()
layout.goto(-400, -380)
main()
layout.goto(-362,200)
main()
layout.goto(-222, 198)
main()
layout.goto(-750, -300)
main()
layout.goto(600, -467)
main()
layout.goto(100, 450)
main()
layout.goto(-100, 400)
main()
layout.goto(-600, 400)
main()
layout.goto(500, 123)
main()
layout.goto(700, 400)
main()
layout.goto(350, 350)
main()

layout.color("blue")
layout.goto(0, -50)
Player = turtle.Turtle()
Player.up()
Player.goto(0, -200)
Player.left(90)

def k1():
Player.forward(45)

def k2():
Player.left(30)

def k3():
Player.right(30)

def k4():
Player.back(45)

wn.onkey(k1, "Up")
wn.onkey(k2, "Left")
wn.onkey(k3, "Right")
wn.onkey(k4, "Down")

wn.listen()

Body:
Your code is a challenge to work with.

For this example, I've tossed your trees and bridge planks as they have no affect on the problem.  Since your river and bridge are rectangular, I've wrapped their drawing in a begin_poly() and end_poly() combination so that we have the bounding boxes of those rectangles.  Then, for the two movement commands (forward and backward) we test if the resulting movement puts us in the river, but not the bridge, and simply goto() the starting position if that's the case:

from turtle import Turtle, Screen

def inside(point, rectangle):
    x, y = point

    # not efficient, just a quick solution
    x1 = min(p[0] for p in rectangle)
    y1 = min(p[1] for p in rectangle)
    x2 = max(p[0] for p in rectangle)
    y2 = max(p[1] for p in rectangle)

    return x1 < x < x2 and y1 < y < y2

def not_safe(turtle):
    position = turtle.position()
    return inside(position, river) and not inside(position, bridge)

def drawRiver(turtle):
    turtle.color('darkblue', 'blue')

    turtle.goto(-WIDTH / 2, 0)

    turtle.begin_poly()
    turtle.begin_fill()
    turtle.forward(WIDTH)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(WIDTH)
    turtle.end_fill()
    turtle.end_poly()

    return turtle.get_poly()

def drawBridge(turtle):
    turtle.right(180)
    turtle.goto(50, -120)
    turtle.color('rosybrown4', 'saddlebrown')

    turtle.begin_poly()
    turtle.begin_fill()
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(150)
    turtle.left(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.end_fill()
    turtle.end_poly()

    return turtle.get_poly()

wn = Screen()
wn.bgcolor('lightgreen')
WIDTH = wn.window_width()

layout = Turtle(visible=False)
layout.speed('fastest')
layout.penup()

river = drawRiver(layout)
bridge = drawBridge(layout)

player = Turtle('turtle')
player.penup()

player.goto(0, -200)
player.setheading(90)

def k1():
    player.forward(45)
    if not_safe(player):
        player.goto(0, -200)
        player.setheading(90)

def k2():
    player.back(45)
    if not_safe(player):
        player.goto(0, -200)
        player.setheading(90)

def k3():
    player.left(30)

def k4():
    player.right(30)

wn.onkey(k1, 'Up')
wn.onkey(k2, 'Down')
wn.onkey(k3, 'Left')
wn.onkey(k4, 'Right')

wn.listen()
wn.mainloop()


问:
DTO to entity mapping when entity has many to one relationship
I'm trying to map business object into entity but got stuck and have no idea how to resolve this.

The problem is when I try to map these attributes from DTO which are attributes of many-to-one relationship with another table.

Here is how my Entity looks like:

```<code>@Entity
@Table(name = "t_car")
public class Car extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdCar")
private Long id;

@Column(nullable = false, columnDefinition="VARCHAR(45)")
private String brand;

@Column(nullable = false)
private Integer productionYear;

@Column(nullable = false)
private Float engineCapacity;

@Column(nullable = false)
private Float power;

@Column(nullable = false)
private Integer distance;

@ManyToOne
@JoinColumn(name = "fkIdType")
private CarType carType;

@ManyToOne
@JoinColumn(name = "fkIdColor")
private Color color;
... }
</code>```

And here is DTO:

```<code>public class CarDto {

private Long id;

private String brand;

private Integer productionYear;

private Float engineCapacity;

private Float power;

private Integer distance;

private CarTypes carType;

private ColorTypes color;
... }
</code>```

CarTypes and ColorTypes are enums which have assigned number corresponding to their primary key in database. For example CarTypes is:

```<code>REGULAR_TWO_DOOR(1),
REGULAR_FOUR_DOOR(2),
STATION_WAGON(3),
MINIVAN(4),
SPORT(5),
LUXURY(6);
</code>```

And here is the mapper i managed to write. How can I assign proper CarType (that's entity) to carEntity basing on CarType primary key?

```<code>public class CarMapper {

...
public static Car carDtoToCar(CarDto carDto, Car carEntity) {

    if(carEntity == null) {
        carEntity = new Car();
    }

    carEntity.setBrand(carDto.getBrand());
    carEntity.setProductionYear(carDto.getProductionYear());
    carEntity.setEngineCapacity(carDto.getEngineCapacity());
    carEntity.setPower(carDto.getPower());
    carEntity.setDistance(carDto.getDistance());

    Long carTypeId = Long.valueOf(carDto.getCarType().getNumber());
    Long carColorId = Long.valueOf(carDto.getColor().getNumber());

    /* ? */

    return carEntity;
}
}
</code>```

CarType entity:

```<code>@Entity
@Table(name = "t_car_type")
public class CarType extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdType")
private Long id;

@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition="VARCHAR(45)")
private CarTypes type;
... }
</code>```

答:
Get the CarType entity based on the Cartype Id. For example:

CarType carType = entityManager.find(CarType.class, carTypeId);

And then set this carType in CarEntity as

carEntity.setCarType(carType);

Body:
I'm trying to map business object into entity but got stuck and have no idea how to resolve this.

The problem is when I try to map these attributes from DTO which are attributes of many-to-one relationship with another table.

Here is how my Entity looks like:

@Entity
@Table(name = "t_car")
public class Car extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdCar")
private Long id;

@Column(nullable = false, columnDefinition="VARCHAR(45)")
private String brand;

@Column(nullable = false)
private Integer productionYear;

@Column(nullable = false)
private Float engineCapacity;

@Column(nullable = false)
private Float power;

@Column(nullable = false)
private Integer distance;

@ManyToOne
@JoinColumn(name = "fkIdType")
private CarType carType;

@ManyToOne
@JoinColumn(name = "fkIdColor")
private Color color;
... }

And here is DTO:

public class CarDto {

private Long id;

private String brand;

private Integer productionYear;

private Float engineCapacity;

private Float power;

private Integer distance;

private CarTypes carType;

private ColorTypes color;
... }

CarTypes and ColorTypes are enums which have assigned number corresponding to their primary key in database. For example CarTypes is:

REGULAR_TWO_DOOR(1),
REGULAR_FOUR_DOOR(2),
STATION_WAGON(3),
MINIVAN(4),
SPORT(5),
LUXURY(6);

And here is the mapper i managed to write. How can I assign proper CarType (that's entity) to carEntity basing on CarType primary key?

public class CarMapper {

...
public static Car carDtoToCar(CarDto carDto, Car carEntity) {

    if(carEntity == null) {
        carEntity = new Car();
    }

    carEntity.setBrand(carDto.getBrand());
    carEntity.setProductionYear(carDto.getProductionYear());
    carEntity.setEngineCapacity(carDto.getEngineCapacity());
    carEntity.setPower(carDto.getPower());
    carEntity.setDistance(carDto.getDistance());

    Long carTypeId = Long.valueOf(carDto.getCarType().getNumber());
    Long carColorId = Long.valueOf(carDto.getColor().getNumber());

    /* ? */

    return carEntity;
}
}

CarType entity:

@Entity
@Table(name = "t_car_type")
public class CarType extends AbstractEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "pkIdType")
private Long id;

@Enumerated(EnumType.STRING)
@Column(nullable = false, columnDefinition="VARCHAR(45)")
private CarTypes type;
... }


问:
Parsing and using list item content via Twig
I am experimenting with using Grav to create my next website.  One of the things I would be able to do is to build a unordered list using data provided in Grav frontmatter from the Grav page that uses the template.  Here is how I am trying to do this

```<code>---
sectionone:
     listitems: "['Benefit 1','Benefit 2','Benefit 3']"
---
</code>```

and then in the template somehow do the following

```<code>{% block featurelist %}
<ul>
{% set items = {{page.header.sectionone.consumers.benefits|json_decode}} %}
{% for item in {{}} %}
<li>{{item}}</li>
{% endfor %}
</ul>
{% endblock %}
</code>```

However, Twig does not like this and reports back an error along the lines of

Twig_Error_Syntax
  A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".

with the offending line being my {% set items = ... } statement.  I am clearly doing something wrong here but I am a Twig newbie so I fail to see what that might be.

答:
```<code>{% block featurelist %}
<ul>
   {% set items = page.header.sectionone.consumers.benefits|json_decode %}
   {% for item in items %}
      <li>{{item}}</li>
   {% endfor %}
</ul>
{% endblock %}
</code>```

Body:
I am experimenting with using Grav to create my next website.  One of the things I would be able to do is to build a unordered list using data provided in Grav frontmatter from the Grav page that uses the template.  Here is how I am trying to do this

---
sectionone:
     listitems: "['Benefit 1','Benefit 2','Benefit 3']"
---

and then in the template somehow do the following

{% block featurelist %}

{% set items = {{page.header.sectionone.consumers.benefits|json_decode}} %}
{% for item in {{}} %}

{{item}}

{% endfor %}

{% endblock %}

However, Twig does not like this and reports back an error along the lines of

Twig_Error_Syntax
  A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{".

with the offending line being my {% set items = ... } statement.  I am clearly doing something wrong here but I am a Twig newbie so I fail to see what that might be.


问:
Could not find com.android.tools.build:gradle:2.3.3
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

```<code>`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`
</code>```

Could you help me what am I missing?

答: i hit the similar issue recently after upgrading Android Studio to 3.0. You might want to do some cleanup (erasing .gradle and .idea folders) and rebuild, as discussed in Android studio build error after update to v 3.0.</p>

Body:
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`

Could you help me what am I missing?


问:
regex to check 9 length characters for the prefix
I'm trying to create a regex to

valid following type string only

first 2 characters 0 to 9

next 3 characters 000 to 366 then 501 to 866

next 4 characters 0 to 9

finally x or X

so I did that using following

```<code>([0-9]{2}(001|002|003|004|005|006|007... |366|501|...|866)[0-9]{4}[x|X]$)
</code>```

so this can validate properly 900033618x

but this also taking 9001033618x as valid onces

how to restrict to 9 character length before x or X

I tried do this, like following

```<code>(^\d[[0-9]{2}(001|002|003|004|005|006|007... |366|501|...|866)[0-9]{4}]{9}[x|X]$)
</code>```

but this not working

Body:
I'm trying to create a regex to

valid following type string only

first 2 characters 0 to 9

next 3 characters 000 to 366 then 501 to 866

next 4 characters 0 to 9

finally x or X

so I did that using following

([0-9]{2}(001|002|003|004|005|006|007... |366|501|...|866)[0-9]{4}[x|X]$)

so this can validate properly 900033618x

but this also taking 9001033618x as valid onces

how to restrict to 9 character length before x or X

I tried do this, like following

(^\d[[0-9]{2}(001|002|003|004|005|006|007... |366|501|...|866)[0-9]{4}]{9}[x|X]$)

but this not working

Body:
Just do what you say:

^[0-9]{2}(?:[01][0-9][0-9]|[24]00|3(?:6[6-9]|[7-9][0-9]))[0-9]{4}[xX]$

Note: watch beginning caret ^


问:
How to get field names from a tbl_dbi?
Is there a  way to directly get the field names from a tbl_dbi object (db_mtcars below)?

```<code> library(RSQLite)
 library(dbplyr)
 library(dplyr)
 con <- dbConnect(RSQLite::SQLite(), ":memory:")
 dbWriteTable(con, "mtcars", mtcars)

 db_mtcars <- tbl(con, "mtcars")
</code>```

答:
Yes with colnames()

```<code>> colnames(db_mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
</code>```

Title: How to get field names from a tbl_dbi?

Body:
Is there a  way to directly get the field names from a tbl_dbi object (db_mtcars below)?

 library(RSQLite)
 library(dbplyr)
 library(dplyr)
 con <- dbConnect(RSQLite::SQLite(), ":memory:")
 dbWriteTable(con, "mtcars", mtcars)

 db_mtcars <- tbl(con, "mtcars")

Body:
Yes with colnames()

> colnames(db_mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"


问:
Stream PDF to iframe
I have a pdf stream and would like to stream it right to the iframe. I know you can give an iframe a source file, but dont know if iframe can take in a stream instead and show pdf. Thankx</p>

答: Create an aspx page that binarywrites the PDF the response stream. Set this aspx page to the iframe.</p>

Title: Stream PDF to iframe