问:
Modify request in middleware?
I have a TrimInput middleware registrated as a middleware for my routes to trim all user input before the request hits the controller. Within the middleware the trimming seems working, but when I dump the request in the action the request seems unmodified like there was no middleware before.

What's the problem here? The problem is the ClientRequest but why?

```<code>// TrimInput.php
<?php namespace App\Http\Middleware;

use Closure;

class TrimInput {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $request->replace($this->trimArrayRecursive($request->all()));
        // When I dump $request right here, all seems fine (the input is trimmed)

        return $next($request);
    }

    protected function trimArrayRecursive($input) {
        if (!is_array($input)) {
            return trim($input);
        }

        return array_map([$this, 'trimArrayRecursive'], $input);
    }

}

// Somwhere in my routes.php
Route::post('/test', ['middleware' => 'trim', 'uses' => function(\App\Http\Requests\ClientRequest $request) {
    dd($request->all()); // Unfortunately dumps the unfiltered (untrimmed) input
}]);
</code>```

EDIT: It turned out, that the above code is working, but unfortunately my ClientRequest ignores the TrimInputMiddleware.

```<code>// ClientRequest.php
<?php namespace App\Http\Requests;

class ClientRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        $idToIgnore = $this->input('id');

        return [
            'name'           => 'required|max:255|unique:clients,name,' . $idToIgnore,
            'street'         => 'required|max:255',
            'postal_code'    => 'required|digits:5',
            'city'           => 'required|max:255',
            'contact_person' => 'required|max:255'
        ];
    }

}
</code>```

答:
use the framework's Illuminate\Foundation\Http/Middleware\TrimStrings.php
middleware and add it to your web middleware group

Title: Modify request in middleware?

Body:
I have a TrimInput middleware registrated as a middleware for my routes to trim all user input before the request hits the controller. Within the middleware the trimming seems working, but when I dump the request in the action the request seems unmodified like there was no middleware before.

What's the problem here? The problem is the ClientRequest but why?

// TrimInput.php
<?php namespace App\Http\Middleware;

use Closure;

class TrimInput {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $request->replace($this->trimArrayRecursive($request->all()));
        // When I dump $request right here, all seems fine (the input is trimmed)

        return $next($request);
    }

    protected function trimArrayRecursive($input) {
        if (!is_array($input)) {
            return trim($input);
        }

        return array_map([$this, 'trimArrayRecursive'], $input);
    }

}

// Somwhere in my routes.php
Route::post('/test', ['middleware' => 'trim', 'uses' => function(\App\Http\Requests\ClientRequest $request) {
    dd($request->all()); // Unfortunately dumps the unfiltered (untrimmed) input
}]);

EDIT: It turned out, that the above code is working, but unfortunately my ClientRequest ignores the TrimInputMiddleware.

// ClientRequest.php
<?php namespace App\Http\Requests;

class ClientRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        $idToIgnore = $this->input('id');

        return [
            'name'           => 'required|max:255|unique:clients,name,' . $idToIgnore,
            'street'         => 'required|max:255',
            'postal_code'    => 'required|digits:5',
            'city'           => 'required|max:255',
            'contact_person' => 'required|max:255'
        ];
    }

}


来源: stackexchange

问:
Video overlay issue
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}</code>```

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>

```

答:
Maybe ditch jquery and do a pure javascript implementation?

Or have seperate logic that has a more fluid use in javascript. for which browser type.

:)

Hope you figure it out I'd look at the video api through mozilla
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement

ContentLicense: CC BY-SA 3.0

Title: Video overlay issue

Body:
I'd like to create a video overlay. It works great in Chrome with https://stackoverflow.com/a/30310041/8254123, but has some issues in Safari. When I add controls to the video tag and want to pause the video, Safari returns this error:

Unhandled Promise Rejection: [object DOMError]

If I remove the controls attribute it works, but I need controls and don't want to add custom controls.

jQuery('.video_home_1').click(function() {
  if (jQuery(this).children("video").get(0).paused) {
    jQuery(this).children("video").get(0).play();
    jQuery(this).find(".playpause").fadeOut();
    jQuery(this).find(".home_video_overlay").fadeOut();
  } else {
    jQuery(this).children("video").get(0).pause();
    jQuery(this).find(".playpause").fadeIn();
    jQuery(this).find(".home_video_overlay").fadeIn();
    jQuery(this).children(".home_video_overlay").css('background', 'transparent');
  }
});

.video_home_1 {
  display: table;
  width: auto;
  position: relative;
  width: auto;
  height: 425px;
}

.video_home_1 .playpause {
  background: url(https://www.squaresigns.com/wp-content/uploads/2017/11/play.png) 58% 50% no-repeat;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  position: absolute;
  left: 0%;
  right: 0%;
  background-size: 64px 64px;
  top: 0%;
  bottom: 0%;
  z-index: 100;
  margin: auto;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .3);
}

.video_home_1 .home_video_overlay {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: 100%;
  height: 425px;
  background-repeat: no-repeat;
  background-position: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  cursor: pointer;
}

.video_home_1 video {
  height: 425px;
  width: auto;
  padding-right: 4px;
}

  <video controls>
    <source type="video/mp4" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.mp4">
    <source type="video/webm" src="https://www.squaresigns.com/wp-content/uploads/2017/11/SquareSigns.webm">
  </video>


问:
What are these "none" at the bottom of my output?
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

```<code>def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))
</code>```

Example run:

```<code>>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]
</code>```

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

答:
I think it is because you aren't returning anything on your map function, so it doesn't work correctly. You can try this, so the instead of being mapped to None, it will be mapped to the results:

```<code>def rawGradeToLetter(grade):
    if grade >= 90:
        print ("A")
        return "A"
    elif grade < 90 and grade >= 80:
        print ("B")
        return "B"
    elif grade < 80 and grade >= 70:
        print ("C")
        return "C"
    elif grade < 70 and grade >= 60:
        print ("D")
        return "D"
    elif grade < 60:
        print ("F")
        return "F"

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))
</code>```

It is, if you want to maintain the prints, if not, you can remove them.

Body:
Brand new to python. When using the map function in python, i get a series of the word "none" as an output when i run my function. ive added screenshot below.

Code

def rawGradeToLetter(grade):
   if grade >= 90:
      print ("A")
   elif grade < 90 and grade >= 80:
      print ("B")
   elif grade < 80 and grade >= 70:
      print ("C")
   elif grade < 70 and grade >= 60:
      print ("D")
   elif grade < 60:
      print ("F")

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))

Example run:

>>> convertRawsToLetters([90,80,70])
A
B
C
[None, None, None]

I have a feeling it has something to do with the word list before the map function, but if I remove that all I get is the address of the map like "map object at 0x8g9b7ea51950".

Body:
I think it is because you aren't returning anything on your map function, so it doesn't work correctly. You can try this, so the instead of being mapped to None, it will be mapped to the results:

def rawGradeToLetter(grade):
    if grade >= 90:
        print ("A")
        return "A"
    elif grade < 90 and grade >= 80:
        print ("B")
        return "B"
    elif grade < 80 and grade >= 70:
        print ("C")
        return "C"
    elif grade < 70 and grade >= 60:
        print ("D")
        return "D"
    elif grade < 60:
        print ("F")
        return "F"

def convertRawsToLetters(myList):
   return list(map(rawGradeToLetter, myList))

It is, if you want to maintain the prints, if not, you can remove them.


问:
Detecting current rotation with Paper.js
I'm making a small shoot 'em up game with Paper.js,
but I'm unable to find that Paperscript provides any way to get the current rotation
of my group of items.

In the code beneath, rotating 'circlegroup' with Q and E keys, should affect the WASD navigation, moving the item in the direction that the 'nose' of the object is currently pointing at. I figure that I need to get the current rotation of my items in order to
affect the navigation. Does Paper.js provide any way to do this?

You can see/edit the Papersketch here

```<code>bigcircle = new Path.Circle({
  radius:10,
  fillColor: 'grey',
  position: (10, 20),
  selected: true
});

smallcircle = new Path.Circle({
  radius:5,
  fillColor: 'black'
});

var circlecontainer  = new Group({
  children:[smallcircle, bigcircle],
  position: view.center
});

var circlegroup = new Group({
  children: [circlecontainer]
});

function onKeyDown(event) {
  if(event.key == 'w') {
    circlegroup.position.y -= 10;
  }
  if(event.key == 'a') {
    circlegroup.position.x -= 10;
  }
  if(event.key == 's') {
    circlegroup.position.y += 10;
  }
  if(event.key == 'd') {
    circlegroup.position.x += 10;
  }
  if(event.key == 'q') {
      // hold down
    circlegroup.rotate(1);
  }
  if(event.key == 'e') {
      // hold downw
    circlegroup.rotate(-1);
  }
}
</code>```

答: Stumbled upon this question in 2017... there is a Path.position property http://paperjs.org/reference/path/#rotation</p>

Body:
I'm making a small shoot 'em up game with Paper.js,
but I'm unable to find that Paperscript provides any way to get the current rotation
of my group of items.

In the code beneath, rotating 'circlegroup' with Q and E keys, should affect the WASD navigation, moving the item in the direction that the 'nose' of the object is currently pointing at. I figure that I need to get the current rotation of my items in order to
affect the navigation. Does Paper.js provide any way to do this?

You can see/edit the Papersketch here

bigcircle = new Path.Circle({
  radius:10,
  fillColor: 'grey',
  position: (10, 20),
  selected: true
});

smallcircle = new Path.Circle({
  radius:5,
  fillColor: 'black'
});

var circlecontainer  = new Group({
  children:[smallcircle, bigcircle],
  position: view.center
});

var circlegroup = new Group({
  children: [circlecontainer]
});

function onKeyDown(event) {
  if(event.key == 'w') {
    circlegroup.position.y -= 10;
  }
  if(event.key == 'a') {
    circlegroup.position.x -= 10;
  }
  if(event.key == 's') {
    circlegroup.position.y += 10;
  }
  if(event.key == 'd') {
    circlegroup.position.x += 10;
  }
  if(event.key == 'q') {
      // hold down
    circlegroup.rotate(1);
  }
  if(event.key == 'e') {
      // hold downw
    circlegroup.rotate(-1);
  }
}


问:
TypeError: 'int' object is not iterable in map function
Sorry I'm a newbie python coder.
I wrote this code in PyCharm:

```<code>lst_3 = [1, 2, 3]

def square(lst):
    lst_1 = list()
    for n in lst:
        lst_1.append(n**2)

    return lst_1

print(list(map(square,lst_3)))
</code>```

and i have this type of error : TypeError: 'int' object is not iterable.
What is the error in my code?

答:
The issue here is your misunderstanding of what map is doing. Here's a representative example. I've created an "identity" function of sorts which just echoes a number and returns it. I'll map this function to a list, so you can see what's printed out:

```<code>In [382]: def foo(x):
     ...:     print('In foo: {}'.format(x))
     ...:     return x
     ...:

In [386]: list(map(foo, [1, 2, 3]))
In foo: 1
In foo: 2
In foo: 3
Out[386]: [1, 2, 3]
</code>```

Notice here that each element in the list is passed to foo in turn, by map. foo does not receive a list. Your mistake was thinking that it did, so you attempted to iterate over a number which resulted in the error you see.

What you need to do in your case, is define square like this:

```<code>In [387]: def square(x):
     ...:     return x ** 2
     ...:

In [388]: list(map(square, [1, 2, 3]))
Out[388]: [1, 4, 9]
</code>```

square should work under the assumption that it receives a scalar.

Alternatively, you may use a lambda to the same effect:

```<code>In [389]: list(map(lambda x: x ** 2, [1, 2, 3]))
Out[389]: [1, 4, 9]
</code>```

Keep in mind this is the functional programming way of doing it. For reference, it would be cheaper to use a list comprehension:

```<code>In [390]: [x ** 2 for x in [1, 2, 3]]
Out[390]: [1, 4, 9]
</code>```

Body:
Sorry I'm a newbie python coder.
I wrote this code in PyCharm:

lst_3 = [1, 2, 3]

def square(lst):
    lst_1 = list()
    for n in lst:
        lst_1.append(n**2)

    return lst_1

print(list(map(square,lst_3)))

and i have this type of error : TypeError: 'int' object is not iterable.
What is the error in my code?

Body:
The issue here is your misunderstanding of what map is doing. Here's a representative example. I've created an "identity" function of sorts which just echoes a number and returns it. I'll map this function to a list, so you can see what's printed out:

In [382]: def foo(x):
     ...:     print('In foo: {}'.format(x))
     ...:     return x
     ...:

In [386]: list(map(foo, [1, 2, 3]))
In foo: 1
In foo: 2
In foo: 3
Out[386]: [1, 2, 3]

Notice here that each element in the list is passed to foo in turn, by map. foo does not receive a list. Your mistake was thinking that it did, so you attempted to iterate over a number which resulted in the error you see.

What you need to do in your case, is define square like this:

In [387]: def square(x):
     ...:     return x ** 2
     ...:

In [388]: list(map(square, [1, 2, 3]))
Out[388]: [1, 4, 9]

square should work under the assumption that it receives a scalar.

Alternatively, you may use a lambda to the same effect:

In [389]: list(map(lambda x: x ** 2, [1, 2, 3]))
Out[389]: [1, 4, 9]

Keep in mind this is the functional programming way of doing it. For reference, it would be cheaper to use a list comprehension:

In [390]: [x ** 2 for x in [1, 2, 3]]
Out[390]: [1, 4, 9]


问:
Adding JavaFX to a shared project on GitHub
First of all, this is a college task and we don't get any instructions on how Java work with libs, JARs, etc. So I'd be very helpful if someone could be lenient and please ELI5 (I'm not a technical guy).

So all I want to do is add JavaFX to a Java project that I share with my team on GitHub. In Eclipse, I used the Install Software wizard, added the library to the build path, and merged these changes to the master branch.

When I open the master branch in eclipse, I can see the library:
my PC

But my team members (other computers) don't have it: their PC

If you look at the first image, there's a link next to the JAR that indicates it's saved somewhere on my C drive. Unlike the JARs under the hibernate lib which I added directly to my project by copy-pasting them.

We also have a .gitignore file with following lines:

bin/
.metadata
.recommenders

When there was more than 1 pull request, these folders caused unsolvable merging conflicts for the remaining ones after I merged one of them.

I thought about copy-pasting the JavaFX JAR into the project just like I did with the hibernate JARs, because my team members did get those. But as I sead earlier, I have no single clue how all of this works, all I do is follow tutorials. I don't even know if the JAR on its own will be sufficient, or where copy-pasted JARs are stored. Could it be in .metadata? Because I actually hadn't configured the .gitignore file yet when I merged the hibernate JARs.

On a last note, we don't use Maven or anything alike. All we use is github.com for merging, Git Bash for pulling/committing/pushing and normal eclipse (not EGit) for coding.

Any help would be greatly appreciated!

答: I found the solution I was looking for. As mentioned by James_D in the comments, the JavaFX JARs are part of the standard JRE. All my team members just had to install the e(fx)clipse plugins on their own IDE too and it did the trick. No configurations in the build path needed!</p>


问:
Inserting a character in a file name using Python
I am new to Python.

So, I have a couple of files like:

r_feature_info_call_home_cbr_16_6.xml

r_feature_info_flap_list_ts_cbr_16_6.xml

I want to remove all the '_' from the file name except the ones after the first 'r' and the one before '16_6'

I am trying to write some code:

```<code>import os

fpath = os.path.join('/Users/avishdas/Documents/Duplication Script/', 'Feature_Info')

flist = os.listdir(fpath)

for f in flist:
    file_name, file_ext = os.path.splitext(f)
    file_name = (file_name.replace("_", ""))
    ufile_name = os.rename(file_name, file_name.([ :1] + '_' + [1: ]))
    print ufile_name
</code>```

With this piece of code, I am first removing all the underscores and then trying to insert the two '_'.

The code works fine till:

```<code>file_name = (file_name.replace("_", ""))
</code>```

The next line is giving me an invalid syntax error. Please note that here I am just trying to add the '_' after the first 'r'.

What am I doing wrong? Is there any other way I can accomplish this?

答:
Here are some of the issues I can see:

you overwrite your file_name variable (line 9) and assume it still contains the original file name on the next line (line 10). Use one more intermediary variable

you forgot to add your extension file_ext back when you call os.rename. You need it on the first argument - it is up to you if you want it on the second argument.

you expect os.rename to return something interesting, it is going to return None on success and throw an Exception on failure (which you may want to handle)

you can't use parentheses after a ., that's your invalid syntax.

finally, your idea with substrings to reintroduce the _ is correct but it may be hard at the end of your file if the number of characters after the last _ varies because you won't be able to know the exact position.

Additional note: if you intend to keep the .xml extension, you may not need to split your filename.

Here is an example without assuming the length of each segment:

```<code>for f in flist:
    elements = f.split("_") # make a list of elements without _
    elements.insert(1, "_") # reintroduce the first _ in the list
    elements.insert(-1, "_") # reintroduce the last _ in the list
    new_name = "".join(elements) # recreate a string
    os.rename(f, new_name)
</code>```

Body:
I am new to Python.

So, I have a couple of files like:

r_feature_info_call_home_cbr_16_6.xml

r_feature_info_flap_list_ts_cbr_16_6.xml

I want to remove all the '_' from the file name except the ones after the first 'r' and the one before '16_6'

I am trying to write some code:

import os

fpath = os.path.join('/Users/avishdas/Documents/Duplication Script/', 'Feature_Info')

flist = os.listdir(fpath)

for f in flist:
    file_name, file_ext = os.path.splitext(f)
    file_name = (file_name.replace("_", ""))
    ufile_name = os.rename(file_name, file_name.([ :1] + '_' + [1: ]))
    print ufile_name

With this piece of code, I am first removing all the underscores and then trying to insert the two '_'.

The code works fine till:

file_name = (file_name.replace("_", ""))

The next line is giving me an invalid syntax error. Please note that here I am just trying to add the '_' after the first 'r'.

What am I doing wrong? Is there any other way I can accomplish this?

Body:
Here are some of the issues I can see:

you overwrite your file_name variable (line 9) and assume it still contains the original file name on the next line (line 10). Use one more intermediary variable

you forgot to add your extension file_ext back when you call os.rename. You need it on the first argument - it is up to you if you want it on the second argument.

you expect os.rename to return something interesting, it is going to return None on success and throw an Exception on failure (which you may want to handle)

you can't use parentheses after a ., that's your invalid syntax.

finally, your idea with substrings to reintroduce the _ is correct but it may be hard at the end of your file if the number of characters after the last _ varies because you won't be able to know the exact position.

Additional note: if you intend to keep the .xml extension, you may not need to split your filename.

Here is an example without assuming the length of each segment:

for f in flist:
    elements = f.split("_") # make a list of elements without _
    elements.insert(1, "_") # reintroduce the first _ in the list
    elements.insert(-1, "_") # reintroduce the last _ in the list
    new_name = "".join(elements) # recreate a string
    os.rename(f, new_name)


问:
Shift-F10, prevent context-menu in Firefox
In my application I have a SHIFT-F10 keyboard handler like below:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script>
$(document).on('keyup keydown', function(e) {
  if (e.keyCode === 121 && e.shiftKey === true) {
    console.log('shift-f10 detected');
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
  }
});
</script>
</body>
</html>
</code>```

But, in recent versions of Firefox (at least FF56), a context-menu is appearing in the top-right of the page:

I've been unsuccessful in disabling the context-menu with:

```<code>e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
</code>```

Is there a way to prevent this context-menu from appearing?

答:
Try next code:

```<code> $document.on('contextmenu',  (ev) => {
        return false;
 });
</code>```

or:

```<code>$(document).on('keydown', function(e) {
  if (e.keyCode === 121 && e.shiftKey === true) {
    return false;
  }
});
</code>```

Maybe you can use :

```<code> document.body.addEventListener('keydown',function(ev){
      if (ev.keyCode === 121 && ev.shiftKey === true)
               {
                 ev.preventDefault();
               }
    });
</code>```

If this code don't work -  focus don't locate in browser, or  you have other errors.  Try it code.

Body:
In my application I have a SHIFT-F10 keyboard handler like below:

<!DOCTYPE html>

  <meta charset="UTF-8">

But, in recent versions of Firefox (at least FF56), a context-menu is appearing in the top-right of the page:

I've been unsuccessful in disabling the context-menu with:

e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();

Is there a way to prevent this context-menu from appearing?

Body:
Try next code:

 $document.on('contextmenu',  (ev) => {
        return false;
 });

or:

$(document).on('keydown', function(e) {
  if (e.keyCode === 121 && e.shiftKey === true) {
    return false;
  }
});

Maybe you can use :

 document.body.addEventListener('keydown',function(ev){
      if (ev.keyCode === 121 && ev.shiftKey === true)
               {
                 ev.preventDefault();
               }
    });

If this code don't work -  focus don't locate in browser, or  you have other errors.  Try it code.


问:
jQuery selector DOM traversal direction and efficiency
What is the standard direction of search for multipart jQuery selectors?

e.g. the case

```<code>$('#myTable tr.selected');
</code>```

Is the first search for #myTable and then the tr.selected search is only within that table?

Or is the first search for all tr.selected on the page and the second search checking each ones parent nodes?

答:
The first search for #myTable and then the tr.selected search is only within that table

First it looks for an element with the id of myTable and then finds descendants that are 'tr' tags with the selected class

ContentLicense: CC BY-SA 2.5

Body:
What is the standard direction of search for multipart jQuery selectors?

e.g. the case

$('#myTable tr.selected');

Is the first search for #myTable and then the tr.selected search is only within that table?

Or is the first search for all tr.selected on the page and the second search checking each ones parent nodes?


问:
How to List Field's Name in table in Access Using SQL
Can you please let me know if it is possible to list all fields name in a  MS Access table?</p>

答:
This is not SQL, but this question is the top Google result for someone like me who just needs to list out the field names needed for a query to select since Access does not support "* except foo, bar" for getting 99% of a table.

Answer adapted from a social.msdn.com answer by Patrick Wood, Access MVP
https://social.msdn.microsoft.com/Forums/office/en-US/1fe5546b-db3f-4e17-9bf8-04f4dee233b7/how-to-list-all-the-field-names-in-a-specified-table?forum=accessdev

Change tablename to your name in the module.  This Function should be at the global level:

```<code>Function ListTdfFields()
    ' NOT doing DIMs, since then you must enable/attach ADODB or DAO
    ' Dim db As ADO.Database
    Set db = CurrentDb
    tablename = "tblProductLicense"  ' <=== YOUR TABLE NAME HERE
    Set tdf = db.TableDefs(tablename)
    For Each fld In tdf.Fields
        Debug.Print tablename; ".["; fld.Name; "]," ;
        ' remove ending ; for 1 line per field
    Next
    Debug.Print ""
    Set tdf = Nothing
    Set db = Nothing
End Function
</code>```

Then add a macro RunCode ListTdfFields() and run it.  Output will be sent to the Immediate window of the VBA design view for the module.

ContentLicense: CC BY-SA 4.0

Body:
This is not SQL, but this question is the top Google result for someone like me who just needs to list out the field names needed for a query to select since Access does not support "* except foo, bar" for getting 99% of a table.

Answer adapted from a social.msdn.com answer by Patrick Wood, Access MVP
https://social.msdn.microsoft.com/Forums/office/en-US/1fe5546b-db3f-4e17-9bf8-04f4dee233b7/how-to-list-all-the-field-names-in-a-specified-table?forum=accessdev

Change tablename to your name in the module.  This Function should be at the global level:

Function ListTdfFields()
    ' NOT doing DIMs, since then you must enable/attach ADODB or DAO
    ' Dim db As ADO.Database
    Set db = CurrentDb
    tablename = "tblProductLicense"  ' <=== YOUR TABLE NAME HERE
    Set tdf = db.TableDefs(tablename)
    For Each fld In tdf.Fields
        Debug.Print tablename; ".["; fld.Name; "]," ;
        ' remove ending ; for 1 line per field
    Next
    Debug.Print ""
    Set tdf = Nothing
    Set db = Nothing
End Function

Then add a macro RunCode ListTdfFields() and run it.  Output will be sent to the Immediate window of the VBA design view for the module.


问:
Custom Leaflet Renderer for GeoJSON
I want to render GeoJSON differently than provided by Leaflet by default. Unfortunately changing the style() function will not suffice as I need greater control over the vector graphics being created.

What is the idiomatic way of doing this? I reckon I can reuse lots of parts of the default SVG renderer found in src/layers/vector/SVG.js. I would however like to only replace it for one GeoJSON layer / one FeatureGroup. As none of these inherit from Path, this does not seem possible.

I tried extending the SVG class in a very basic way:

```<code>import {SVG} from 'leaflet/src/layer/vector/SVG'

export default class CustomSVG extends SVG {
  _updatePoly (layer, closed) {
    console.log('Custom renderer in action')
    super._updatePoly(layer, closed)
  }
}
</code>```

and then set it as the renderer while initializing Leaflet, but this fails with a TypeError: max2 is undefined (it is an unhandled promise rejection which stems from me using react-leaflet).

What is it I'm missing?

答:
I read the documentation again and I seem to have missed this bit about the GeoJSON options:

style: A Function defining the Path options for styling GeoJSON lines and polygons, called internally when data is added. The default value is to not override any defaults:

```<code>function (geoJsonFeature) {
  return {}
}
</code>```

The path options on the other hand take a renderer, which I can use to override the rendering of this particular GeoJSON layer only. Hope this helps anybody else!

Title: Custom Leaflet Renderer for GeoJSON

Body:
I want to render GeoJSON differently than provided by Leaflet by default. Unfortunately changing the style() function will not suffice as I need greater control over the vector graphics being created.

What is the idiomatic way of doing this? I reckon I can reuse lots of parts of the default SVG renderer found in src/layers/vector/SVG.js. I would however like to only replace it for one GeoJSON layer / one FeatureGroup. As none of these inherit from Path, this does not seem possible.

I tried extending the SVG class in a very basic way:

import {SVG} from 'leaflet/src/layer/vector/SVG'

export default class CustomSVG extends SVG {
  _updatePoly (layer, closed) {
    console.log('Custom renderer in action')
    super._updatePoly(layer, closed)
  }
}

and then set it as the renderer while initializing Leaflet, but this fails with a TypeError: max2 is undefined (it is an unhandled promise rejection which stems from me using react-leaflet).

What is it I'm missing?

Body:
I read the documentation again and I seem to have missed this bit about the GeoJSON options:

style: A Function defining the Path options for styling GeoJSON lines and polygons, called internally when data is added. The default value is to not override any defaults:

function (geoJsonFeature) {
  return {}
}

The path options on the other hand take a renderer, which I can use to override the rendering of this particular GeoJSON layer only. Hope this helps anybody else!


问:
calculating factorial using Java 8 IntStream?
I am relatively new in Java 8 and lambda expressions as well as Stream, i can calculate factorial using for loop or recursion. But is there a way to use IntStream to calculate factorial of a number ? I am fine even with factorial in integer range.

I read through IntStream docs here, http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html and i can see so many methods but not sure which one I can use to calculate factorial.

for example, there is rang method that says,

range(int startInclusive, int endExclusive) Returns a sequential
  ordered IntStream from startInclusive (inclusive) to endExclusive
  (exclusive) by an incremental step of 1.

so I can use it to provide the range of numbers to IntStream to be multiplied to calculate factorial.

```<code>number = 5;
IntStream.range(1, number)
</code>```

but how to multiply those numbers to get the factorial ?

答:
With LongStream.range() you can calculate factorial for number less 20. If you need calculate for larger number create stream with BigInteger:</p>

```<code> public BigInteger factorial(int number) {
    if (number < 20) {
        return BigInteger.valueOf(
                LongStream.range(1, number + 1).reduce((previous, current) -> previous * current).getAsLong()
        );
    } else {
        BigInteger result = factorial(19);
        return result.multiply(Stream.iterate(BigInteger.valueOf(20), i -> i.add(BigInteger.ONE)).limit(number - 19)
                .reduce((previous, current) -> previous.multiply(current)).get()
        );
    }
}
</code>```

Body:
I am relatively new in Java 8 and lambda expressions as well as Stream, i can calculate factorial using for loop or recursion. But is there a way to use IntStream to calculate factorial of a number ? I am fine even with factorial in integer range.

I read through IntStream docs here, http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html and i can see so many methods but not sure which one I can use to calculate factorial.

for example, there is rang method that says,

range(int startInclusive, int endExclusive) Returns a sequential
  ordered IntStream from startInclusive (inclusive) to endExclusive
  (exclusive) by an incremental step of 1.

so I can use it to provide the range of numbers to IntStream to be multiplied to calculate factorial.

number = 5;
IntStream.range(1, number)

but how to multiply those numbers to get the factorial ?

Body:
With LongStream.range() you can calculate factorial for number less 20. If you need calculate for larger number create stream with BigInteger:

 public BigInteger factorial(int number) {
    if (number < 20) {
        return BigInteger.valueOf(
                LongStream.range(1, number + 1).reduce((previous, current) -> previous * current).getAsLong()
        );
    } else {
        BigInteger result = factorial(19);
        return result.multiply(Stream.iterate(BigInteger.valueOf(20), i -> i.add(BigInteger.ONE)).limit(number - 19)
                .reduce((previous, current) -> previous.multiply(current)).get()
        );
    }
}


问:
Sentry JVM option placeholder
I'm configuring Sentry to use with our projects but have some issue with it. I would like to put some placeholders in configuration file like

```<code>extra=prj:${project.name}
</code>```

Where project.name is a JVM option set like this:

```<code>java -Dproject.name pname -jar my.jar
</code>```

Is there a way to access it?

答:
All of the Sentry Java SDK options can be provided as Java System Properties or System Environment Variables already. If you want to use either of those I would just skip using the sentry.properties file altogether: https://docs.sentry.io/clients/java/config/#configuration-via-the-runtime-environment

For example:

```<code>java -Dsentry.extra=prj:pname -jar my.jar
</code>```

All you need to do is prefix the option name with sentry. when you provide the property on the commandline.

Title: Sentry JVM option placeholder

Body:
I'm configuring Sentry to use with our projects but have some issue with it. I would like to put some placeholders in configuration file like

extra=prj:${project.name}

Where project.name is a JVM option set like this:

java -Dproject.name pname -jar my.jar

Is there a way to access it?

Body:
All of the Sentry Java SDK options can be provided as Java System Properties or System Environment Variables already. If you want to use either of those I would just skip using the sentry.properties file altogether: https://docs.sentry.io/clients/java/config/#configuration-via-the-runtime-environment

For example:

java -Dsentry.extra=prj:pname -jar my.jar

All you need to do is prefix the option name with sentry. when you provide the property on the commandline.


问:
How to write back end server code in Firebase
I am learning Firebase. I have learned how to read & write to Firebase Realtime Database and how to make rules for that database. I have also read about Cloud Functions.

But I'm still confused how to write my server-side code that applies some algorithm on Firebase Realtime Database and returns it to my Android app.

答:
Firebase is from its nature server-less meaning that all the logic of an app should be contained in the client side.

However if you believe that server side logic is imperative for your app, you may extend its functionality by using:

1) cloud functions. e.g. You upload a picture from your client app and a cloud function fires to resize the picture.

2) by using google cloud platform infrastructure.

3) by using firebase admin-sdk on your own server and creating a node.js backend.

You can check here for many useful samples regarding firebase usage and this information will help you understand more of the architecture you need to follow depending on the app you want to build.


问:
Can I use Apache Pivot instead of Swing?
I saw Apache Pivot, but this is meant for "installable Internet applications". What are IIA and can I use Apache Pivot instead of Swing because I like the UI of Pivot.</p>

答: We are using Pivot for a very large (>200,000 lines of code) desktop application, and it works very well. The "Internet" part of Pivot's description was the original intention, but it has equally good desktop support (actually better now that applets are pretty much phased out).</p>


问:
how to pass a javascript var value to a Grails controller?
I have found the following javascript code to get browser window size and it works great!

```<code><script type="text/javascript">
<!--

 var viewportwidth;
 var viewportheight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
    && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }

 // older versions of IE
 else
 {
       viewportwidth = document.body.clientWidth,
       viewportheight = document.body.clientHeight
 }
document.write('<p>Your viewport width is <b>'+viewportwidth+'x'+viewportheight+'</b>.</p>');
//-->
</script>
</code>```

Now I need to pass it to a Grails controller so I can resize a image according to screen size.

which is built using:

```<code><div align="center" valign="middle">
<img src="${createLink(controller:'chart', action:'buildChart')}" />
</div>
</code>```

How can I do so?
Thanks in advance!

答:
createLink tag will allow params to be passed on that call to the controller action.  Have your javascript determine the values and then plug them into hidden variables that can be referenced by the createLink tag.  jQuery has some great options for easily accessing DOM elements.

For example, your img element could look like this:

We use a similar technique to build remoteFunction method calls with Grails and jQuery.  You may have to adjust the above example, it is untested.

Body:
I have found the following javascript code to get browser window size and it works great!

Now I need to pass it to a Grails controller so I can resize a image according to screen size.

which is built using:

How can I do so?
Thanks in advance!

Body:
createLink tag will allow params to be passed on that call to the controller action.  Have your javascript determine the values and then plug them into hidden variables that can be referenced by the createLink tag.  jQuery has some great options for easily accessing DOM elements.

For example, your img element could look like this:
<img src="${createLink(controller:'chart', action:'buildChart', params:\"['vpWidth' : document.getElementById(\'vpWidth\').value, 'vpHeight': document.getElementById(\'vpHeight\').value]\")}" />

We use a similar technique to build remoteFunction method calls with Grails and jQuery.  You may have to adjust the above example, it is untested.


问:
Array throws error when called
I am creating an array from the values of a range, but when trying to get the values from the array, an error comes up. The code is:

```<code>Dim nombre() As Variant 'Declares the array
Dim arreglo As Long 'Declares the length of the array

fin = Cells(Rows.Count, "B").End(xlUp).Row 'Gets the last column with data
nombre = Range("B3:B" & fin).Value 'Fills the array with the values within the range
arreglo = Application.CountA(nombre) 'Gets the length of the array, in this case, 52

MsgBox nombre(1) 'This throws an error
</code>```

I think the problem arises when filling the arrange with values.

Thank you in advance.

答:
Unless a Range contains exactly 1 cell, Range.Value is always a 2D Variant array. If only 1 cell is involved, then the Variant will hold that value. So unless you know you're dealing with more than a single cell, you can't assume you'll be getting an array all the time.

You'll never get a 1D array directly from a straightforward Range.Value call.

You can use the IsArray function to determine if you're looking at an array or a single value:

```<code>Dim nombre As Variant ' don't declare as an array: let the variant hold an array instead
nombre = myRange.Value

If IsArray(nombre) Then
    'nombre is a 2D array
    If Not IsError(nombre(1, 1)) Then MsgBox nombre(1, 1)
Else
    'nombre contains a single value - possibly an error that can't be coerced into a String
    If Not IsError(nombre) Then MsgBox nombre
End If
</code>```

Title: Array throws error when called

Body:
I am creating an array from the values of a range, but when trying to get the values from the array, an error comes up. The code is:

Dim nombre() As Variant 'Declares the array
Dim arreglo As Long 'Declares the length of the array

fin = Cells(Rows.Count, "B").End(xlUp).Row 'Gets the last column with data
nombre = Range("B3:B" & fin).Value 'Fills the array with the values within the range
arreglo = Application.CountA(nombre) 'Gets the length of the array, in this case, 52

MsgBox nombre(1) 'This throws an error

I think the problem arises when filling the arrange with values.

Thank you in advance.

Body:
Unless a Range contains exactly 1 cell, Range.Value is always a 2D Variant array. If only 1 cell is involved, then the Variant will hold that value. So unless you know you're dealing with more than a single cell, you can't assume you'll be getting an array all the time.

You'll never get a 1D array directly from a straightforward Range.Value call.

You can use the IsArray function to determine if you're looking at an array or a single value:

Dim nombre As Variant ' don't declare as an array: let the variant hold an array instead
nombre = myRange.Value

If IsArray(nombre) Then
    'nombre is a 2D array
    If Not IsError(nombre(1, 1)) Then MsgBox nombre(1, 1)
Else
    'nombre contains a single value - possibly an error that can't be coerced into a String
    If Not IsError(nombre) Then MsgBox nombre
End If


问:
cut -c equivalent in Windows
I am trying to run logs using Android studio. My company uses Macs, but I have a PC. There is one command we use to run these logs, and I am trying to find the Windows version of the command.

The code is:

adb logcat | grep 'adb shell ps | grep com.company.company | cut -c10-15' >> /Users/all/Desktop/android.log

I already know grep should be changed to findstr, However, I can not find the windows equivalent to the cut command.

I am also not 100% sure what shell or ps are either.

答:
To have a powerful scripting environment in Windows you can use PowerShell.
with PowerShell you can you can open a file and split lines with a script like:

```<code>$filename = "myfile.txt"

Get-Content $filename | ForEach-Object {
    $_.split(" ")[1]
}
</code>```

Get-Content is alternative to cat and split() is alternative to cat.
Get-Content's output is piped to forEach-Object loop!!

Title: cut -c equivalent in Windows

Body:
To have a powerful scripting environment in Windows you can use PowerShell.
with PowerShell you can you can open a file and split lines with a script like:

$filename = "myfile.txt"

Get-Content $filename | ForEach-Object {
    $_.split(" ")[1]
}

Get-Content is alternative to cat and split() is alternative to cat.
Get-Content's output is piped to forEach-Object loop!!


问:
EXCEL 2007 - Need Help creating a button which takes the contents of active worksheet and pastes it in a new worksheet
I have search throughout this site to find a answer to my problem and most of the related solutions are for a far more complicated problem.  Here is what I need to have done.  I created a simple form in Excel 2007.  I am looking for the ability to add a button at the bottom of the form which allows the user to click on the button and copy that worksheet into a new worksheet within the same excel document.  Basically just duplicating the active worksheet.

I tried to do it with macros but did not get the desired results, and most of our co-workers still use Excel 2003 so I am not sure if macros will work in the older version of excel.  I do not know any VBA which is why I come here in search of help from you all.

So to recap.

One sheet Excel document with a simple form and a command button at the bottom of the active worksheet

The command button "Copy and Paste" that worksheet into a new worksheet within the same excel document

A solution that could work in both Excel 2003 and 2007 if possible.  If not, for 2007.

Thanks so much ahead of time for anyone who is willing to help out a Novice Excel User.

答: I know the question is quite old, but just wanted to note that you (and the user) can do the exact same thing with zero code:  right-click on the sheet name at the bottom and select Move or Copy..., then check the Create a copy box and click Ok. Yes, it takes 4 clicks, but it is super easy and avoids code.


问:
Multiple Left Joins in MS Access using sub-queries
I'm trying to run a query with multiple left joins. I understand that MS Access has additional parameters requiring () around the joins, otherwise I get a "Missing Operator" error, however I'm using sub-queries which adds even more complexity. I can't figure out the syntax. Can someone help? Here is my code:

```<code>SELECT nPrice.Commodity AS Commodity, nPrice.CodeName AS CodeName, nPrice.
[P/N] AS PartNumber, nPrice.Price AS Today, oPrice.Price AS Tomorrow,
pPrice.Price AS Next
FROM
   SELECT *
   FROM qryPrice
   WHERE [MyDate] = #9/1/2017# AND [Type] = 'Net Price' AND [Commodity] =
   'commodityX'
   ORDER BY CodeName ASC  AS nPrice
   LEFT JOIN SELECT *
             FROM qryPrice
             WHERE [MyDate] = #1/1/2018# AND [Type] = 'Net Price'
             ORDER BY CodeName ASC AS oPrice
             ON nPrice.[P/N] = oPrice.[P/N]
             LEFT JOIN  SELECT *
                        FROM qryPrice
                        WHERE [MyDate] = #2/1/2018# AND [Type] = 'Net Price'
                        ORDER BY CodeName ASC AS pPrice
                        ON oPrice.[P/N] = pPrice.[P/N]
ORDER BY nPrice.[P/N];
</code>```

Any help is appreciated. Thanks

答:
While MS Access' dialect requires parentheses around pairs of tables (which can be nested pairs), SQL the language as a general rule (outside of MS Access) requires subqueries to be wrapped in parentheses signifying a contained entity.

Specifically, for your particular JOIN clauses, you only need to wrap the first two derived tables and leave outside without any enclosing outer parentheses. However all subqueries have their own wrapped braces. Below indentation attempts to show parentheses pairings.

Finally, ORDER BY within subqueries are unnecessary as only outer query ordering matters.

```<code>SELECT nPrice.Commodity AS Commodity, nPrice.CodeName AS CodeName,
       nPrice.[P/N] AS PartNumber, nPrice.Price AS Today, oPrice.Price AS Tomorrow,
       pPrice.Price AS Next
FROM
   (
    (SELECT *
     FROM qryPrice
     WHERE [MyDate] = #9/1/2017# AND [Type] = 'Net Price' AND [Commodity] = 'commodityX'
    ) AS nPrice

   LEFT JOIN
     (SELECT *
      FROM qryPrice
      WHERE [MyDate] = #1/1/2018# AND [Type] = 'Net Price'
     ) AS oPrice
   ON nPrice.[P/N] = oPrice.[P/N]
  )

LEFT JOIN
   (SELECT *
    FROM qryPrice
    WHERE [MyDate] = #2/1/2018# AND [Type] = 'Net Price'
   ) AS pPrice

ON oPrice.[P/N] = pPrice.[P/N]

ORDER BY nPrice.[CodeName], pPrice.[CodeName], oPrice.[CodeName], nPrice.[P/N];
</code>```

Body:
I'm trying to run a query with multiple left joins. I understand that MS Access has additional parameters requiring () around the joins, otherwise I get a "Missing Operator" error, however I'm using sub-queries which adds even more complexity. I can't figure out the syntax. Can someone help? Here is my code:

SELECT nPrice.Commodity AS Commodity, nPrice.CodeName AS CodeName, nPrice.
[P/N] AS PartNumber, nPrice.Price AS Today, oPrice.Price AS Tomorrow,
pPrice.Price AS Next
FROM
   SELECT *
   FROM qryPrice
   WHERE [MyDate] = #9/1/2017# AND [Type] = 'Net Price' AND [Commodity] =
   'commodityX'
   ORDER BY CodeName ASC  AS nPrice
   LEFT JOIN SELECT *
             FROM qryPrice
             WHERE [MyDate] = #1/1/2018# AND [Type] = 'Net Price'
             ORDER BY CodeName ASC AS oPrice
             ON nPrice.[P/N] = oPrice.[P/N]
             LEFT JOIN  SELECT *
                        FROM qryPrice
                        WHERE [MyDate] = #2/1/2018# AND [Type] = 'Net Price'
                        ORDER BY CodeName ASC AS pPrice
                        ON oPrice.[P/N] = pPrice.[P/N]
ORDER BY nPrice.[P/N];

Any help is appreciated. Thanks

Body:
While MS Access' dialect requires parentheses around pairs of tables (which can be nested pairs), SQL the language as a general rule (outside of MS Access) requires subqueries to be wrapped in parentheses signifying a contained entity.

Specifically, for your particular JOIN clauses, you only need to wrap the first two derived tables and leave outside without any enclosing outer parentheses. However all subqueries have their own wrapped braces. Below indentation attempts to show parentheses pairings.

Finally, ORDER BY within subqueries are unnecessary as only outer query ordering matters.

SELECT nPrice.Commodity AS Commodity, nPrice.CodeName AS CodeName,
       nPrice.[P/N] AS PartNumber, nPrice.Price AS Today, oPrice.Price AS Tomorrow,
       pPrice.Price AS Next
FROM
   (
    (SELECT *
     FROM qryPrice
     WHERE [MyDate] = #9/1/2017# AND [Type] = 'Net Price' AND [Commodity] = 'commodityX'
    ) AS nPrice

   LEFT JOIN
     (SELECT *
      FROM qryPrice
      WHERE [MyDate] = #1/1/2018# AND [Type] = 'Net Price'
     ) AS oPrice
   ON nPrice.[P/N] = oPrice.[P/N]
  )

LEFT JOIN
   (SELECT *
    FROM qryPrice
    WHERE [MyDate] = #2/1/2018# AND [Type] = 'Net Price'
   ) AS pPrice

ON oPrice.[P/N] = pPrice.[P/N]

ORDER BY nPrice.[CodeName], pPrice.[CodeName], oPrice.[CodeName], nPrice.[P/N];


问:
How to make UISlider default thumb to be smaller like the ones in the iOS control center
I'm working on an app and I have a custom UISlider.

However, I'm having some issues on how to make the default thumb to appear smaller like the ones in the iOS control center.

Note that I want the same iOS thumb, not a custom thumb image. So far, I've tried thumbRect(forBounds...) but no luck.

Any suggestions?

答:
Here's an option for you, use a CGAffineTransform.

Swift 4

```<code>mySlider.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
</code>```

This will change the width and height of the slider, so you may need to realign it with your interface.

Body:
Here's an option for you, use a CGAffineTransform.

Swift 4

mySlider.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)

This will change the width and height of the slider, so you may need to realign it with your interface.


问:
How do you code a purge command
So I have been search far and wide over the internet, trying to find a possible way to make a purge command. Now I have found quite a lot of different ways to make one, but none of them either suited me in the way I wanted, or simply worked for me.
SO to start off, here is my code

```<code>const Discord = require("discord.js"); // use discord.js

const BOT_TOKEN = "secret bot token :)" // bot's token
const PREFIX = "*" // bot's prefix

var eightball = [ // sets the answers to an eightball
    "yes!",
    "no...",
    "maybe?",
    "probably",
    "I don't think so.",
    "never!",
    "you can try...",
    "up to you!",
]

var bot = new Discord.Client(); // sets Discord.Client to bot

bot.on("ready", function() { // when the bot starts up, set its game to Use *help and tell the console "Booted up!"
    bot.user.setGame("Use *info") // sets the game the bot is playing
    console.log("Booted up!") // messages the console Booted up!
});

bot.on("message", function(message) { // when a message is sent
    if (message.author.equals(bot.user)) return; // if the message is sent by a bot, ignore

    if (!message.content.startsWith(PREFIX)) return; // if the message doesn't contain PREFIX (*), then ignore

    var args = message.content.substring(PREFIX.length).split(" "); // removes the prefix from the message
    var command = args[0].toLowerCase(); // sets the command to lowercase (making it incase sensitive)
    var mutedrole = message.guild.roles.find("name", "muted");

    if (command == "help") { // creates a command *help
        var embedhelpmember = new Discord.RichEmbed() // sets a embed box to the variable embedhelpmember
            .setTitle("**List of Commands**\n") // sets the title to List of Commands
            .addField(" - help", "Displays this message (Correct usage: *help)") // sets the first field to explain the command *help
            .addField(" - info", "Tells info about myself :grin:") // sets the field information about the command *info
            .addField(" - ping", "Tests your ping (Correct usage: *ping)") // sets the second field to explain the command *ping
            .addField(" - cookie", "Sends a cookie to the desired player! :cookie: (Correct usage: *cookie @username)") // sets the third field to explain the command *cookie
            .addField(" - 8ball", "Answers to all of your questions! (Correct usage: *8ball [question])") // sets the field to the 8ball command
            .setColor(0xFFA500) // sets the color of the embed box to orange
            .setFooter("You need help, do you?") // sets the footer to "You need help, do you?"
        var embedhelpadmin = new Discord.RichEmbed() // sets a embed box to the var embedhelpadmin
            .setTitle("**List of Admin Commands**\n") // sets the title
            .addField(" - say", "Makes the bot say whatever you want (Correct usage: *say [message])")
            .addField(" - mute", "Mutes a desired member with a reason (Coorect usage: *mute @username [reason])") // sets a field
            .addField(" - unmute", "Unmutes a muted player (Correct usage: *unmute @username)")
            .addField(" - kick", "Kicks a desired member with a reason (Correct usage: *kick @username [reason])") //sets a field
            .setColor(0xFF0000) // sets a color
            .setFooter("Ooo, an admin!") // sets the footer
        message.channel.send(embedhelpmember); // sends the embed box "embedhelpmember" to the chatif
        if(message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.channel.send(embedhelpadmin); // if member is a botadmin, display this too
    }

    if (command == "info") { // creates the command *info
        message.channel.send("Hey! My name is cookie-bot and I'm here to assist you! You can do *help to see all of my commands! If you have any problems with the Minecraft/Discord server, you can contact an administrator! :smile:") // gives u info
    }

    if (command == "ping") { // creates a command *ping
        message.channel.send("Pong!"); // answers with "Pong!"
    }

    if (command == "cookie") { // creates the command cookie
        if (args[1]) message.channel.send(message.author.toString() + " has given " + args[1].toString() + " a cookie! :cookie:") // sends the message saying someone has given someone else a cookie if someone mentions someone else
        else message.channel.send("Who do you want to send a cookie to? :cookie: (Correct usage: *cookie @username)") // sends the error message if no-one is mentioned
    }

    if (command == "8ball") { // creates the command 8ball
        if (args[1] != null) message.reply(eightball[Math.floor(Math.random() * eightball.length).toString(16)]); // if args[1], post random answer
        else message.channel.send("Ummmm, what is your question? :rolling_eyes: (Correct usage: *8ball [question])"); // if not, error
    }

    if (command == "say") { // creates command say
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!");
        var sayMessage = message.content.substring(4)
        message.delete().catch(O_o=>{});
        message.channel.send(sayMessage);
    }

    if(command === "purge") {
        let messagecount = parseInt(args[1]) || 1;

        var deletedMessages = -1;

        message.channel.fetchMessages({limit: Math.min(messagecount + 1, 100)}).then(messages => {
            messages.forEach(m => {
                if (m.author.id == bot.user.id) {
                    m.delete().catch(console.error);
                    deletedMessages++;
                }
            });
        }).then(() => {
                if (deletedMessages === -1) deletedMessages = 0;
                message.channel.send(`:white_check_mark: Purged \`${deletedMessages}\` messages.`)
                    .then(m => m.delete(2000));
        }).catch(console.error);
    }

    if (command == "mute") { // creates the command mute
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var mutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!mutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        if (mutedmember.hasPermission("ADMINISTRATOR")) return message.reply("I cannot mute this member!") // if memebr is an admin
        var mutereasondelete = 10 + mutedmember.user.id.length //sets the length of the kickreasondelete
        var mutereason = message.content.substring(mutereasondelete).split(" "); // deletes the first letters until it reaches the reason
        var mutereason = mutereason.join(" "); // joins the list kickreason into one line
        if (!mutereason) return message.reply("Please indicate a reason for the mute!") // if no reason
        mutedmember.addRole(mutedrole) //if reason, kick
            .catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
        message.reply(`${mutedmember.user} has been muted by ${message.author} because: ${mutereason}`); // sends a message saying he was kicked
    }

    if (command == "unmute") { // creates the command unmute
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var unmutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!unmutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        unmutedmember.removeRole(mutedrole) //if reason, kick
            .catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
        message.reply(`${unmutedmember.user} has been unmuted by ${message.author}!`); // sends a message saying he was kicked
    }

    if (command == "kick") { // creates the command kick
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var kickedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!kickedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        if (!kickedmember.kickable) return message.reply("I cannot kick this member!") // if the member is unkickable
        var kickreasondelete = 10 + kickedmember.user.id.length //sets the length of the kickreasondelete
        var kickreason = message.content.substring(kickreasondelete).split(" "); // deletes the first letters until it reaches the reason
        var kickreason = kickreason.join(" "); // joins the list kickreason into one line
        if (!kickreason) return message.reply("Please indicate a reason for the kick!") // if no reason
        kickedmember.kick(kickreason) //if reason, kick
            .catch(error => message.reply(`Sorry @${message.author} I couldn't kick because of : ${error}`)); //if error, display error
        message.reply(`${kickedmember.user.username} has been kicked by ${message.author.username} because: ${kickreason}`); // sends a message saying he was kicked
    }

});

bot.login(BOT_TOKEN); // connects to the bot
</code>```

It is the only file in my bot folder except the package.json, package-lock.json and all the node_modules.

What I'm trying to do is type in discord *purge [number of messages I want to purge] and get the bot to delete the amount of the messages I asked it to delete, PLUS the command I entered (for example, if I ask the bot to delete 5 messages, he deletes 6 including the *purge 5 message.

Any help would be much appreciated, thanks!

答:
note sure if this is still relevant but this what i use in my bots

```<code>     if (!suffix) {
    var newamount = "2";
  } else {
    var amount = Number(suffix);
    var adding = 1;
    var newamount = amount + adding;
  }
  let messagecount = newamount.toString();
  msg.channel
    .fetchMessages({
      limit: messagecount
    })
    .then(messages => {
      msg.channel.bulkDelete(messages);
      // Logging the number of messages deleted on both the channel and console.
      msg.channel
        .send(
          "Deletion of messages successful. \n Total messages deleted including command: " +
            newamount
        )
        .then(message => message.delete(5000));
      console.log(
        "Deletion of messages successful. \n Total messages deleted including command: " +
          newamount
      );
    })
    .catch(err => {
      console.log("Error while doing Bulk Delete");
      console.log(err);
    });
</code>```

basic function is to specify number of messages to purge and it will delete that many plus the command used, the full example is here

Title: How do you code a purge command

Body:
So I have been search far and wide over the internet, trying to find a possible way to make a purge command. Now I have found quite a lot of different ways to make one, but none of them either suited me in the way I wanted, or simply worked for me.
SO to start off, here is my code

const Discord = require("discord.js"); // use discord.js

const BOT_TOKEN = "secret bot token :)" // bot's token
const PREFIX = "*" // bot's prefix

var eightball = [ // sets the answers to an eightball
    "yes!",
    "no...",
    "maybe?",
    "probably",
    "I don't think so.",
    "never!",
    "you can try...",
    "up to you!",
]

var bot = new Discord.Client(); // sets Discord.Client to bot

bot.on("ready", function() { // when the bot starts up, set its game to Use *help and tell the console "Booted up!"
    bot.user.setGame("Use *info") // sets the game the bot is playing
    console.log("Booted up!") // messages the console Booted up!
});

bot.on("message", function(message) { // when a message is sent
    if (message.author.equals(bot.user)) return; // if the message is sent by a bot, ignore

    if (!message.content.startsWith(PREFIX)) return; // if the message doesn't contain PREFIX (*), then ignore

    var args = message.content.substring(PREFIX.length).split(" "); // removes the prefix from the message
    var command = args[0].toLowerCase(); // sets the command to lowercase (making it incase sensitive)
    var mutedrole = message.guild.roles.find("name", "muted");

    if (command == "help") { // creates a command *help
        var embedhelpmember = new Discord.RichEmbed() // sets a embed box to the variable embedhelpmember
            .setTitle("**List of Commands**\n") // sets the title to List of Commands
            .addField(" - help", "Displays this message (Correct usage: *help)") // sets the first field to explain the command *help
            .addField(" - info", "Tells info about myself :grin:") // sets the field information about the command *info
            .addField(" - ping", "Tests your ping (Correct usage: *ping)") // sets the second field to explain the command *ping
            .addField(" - cookie", "Sends a cookie to the desired player! :cookie: (Correct usage: *cookie @username)") // sets the third field to explain the command *cookie
            .addField(" - 8ball", "Answers to all of your questions! (Correct usage: *8ball [question])") // sets the field to the 8ball command
            .setColor(0xFFA500) // sets the color of the embed box to orange
            .setFooter("You need help, do you?") // sets the footer to "You need help, do you?"
        var embedhelpadmin = new Discord.RichEmbed() // sets a embed box to the var embedhelpadmin
            .setTitle("**List of Admin Commands**\n") // sets the title
            .addField(" - say", "Makes the bot say whatever you want (Correct usage: *say [message])")
            .addField(" - mute", "Mutes a desired member with a reason (Coorect usage: *mute @username [reason])") // sets a field
            .addField(" - unmute", "Unmutes a muted player (Correct usage: *unmute @username)")
            .addField(" - kick", "Kicks a desired member with a reason (Correct usage: *kick @username [reason])") //sets a field
            .setColor(0xFF0000) // sets a color
            .setFooter("Ooo, an admin!") // sets the footer
        message.channel.send(embedhelpmember); // sends the embed box "embedhelpmember" to the chatif
        if(message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.channel.send(embedhelpadmin); // if member is a botadmin, display this too
    }

    if (command == "info") { // creates the command *info
        message.channel.send("Hey! My name is cookie-bot and I'm here to assist you! You can do *help to see all of my commands! If you have any problems with the Minecraft/Discord server, you can contact an administrator! :smile:") // gives u info
    }

    if (command == "ping") { // creates a command *ping
        message.channel.send("Pong!"); // answers with "Pong!"
    }

    if (command == "cookie") { // creates the command cookie
        if (args[1]) message.channel.send(message.author.toString() + " has given " + args[1].toString() + " a cookie! :cookie:") // sends the message saying someone has given someone else a cookie if someone mentions someone else
        else message.channel.send("Who do you want to send a cookie to? :cookie: (Correct usage: *cookie @username)") // sends the error message if no-one is mentioned
    }

    if (command == "8ball") { // creates the command 8ball
        if (args[1] != null) message.reply(eightball[Math.floor(Math.random() * eightball.length).toString(16)]); // if args[1], post random answer
        else message.channel.send("Ummmm, what is your question? :rolling_eyes: (Correct usage: *8ball [question])"); // if not, error
    }

    if (command == "say") { // creates command say
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!");
        var sayMessage = message.content.substring(4)
        message.delete().catch(O_o=>{});
        message.channel.send(sayMessage);
    }

    if(command === "purge") {
        let messagecount = parseInt(args[1]) || 1;

        var deletedMessages = -1;

        message.channel.fetchMessages({limit: Math.min(messagecount + 1, 100)}).then(messages => {
            messages.forEach(m => {
                if (m.author.id == bot.user.id) {
                    m.delete().catch(console.error);
                    deletedMessages++;
                }
            });
        }).then(() => {
                if (deletedMessages === -1) deletedMessages = 0;
                message.channel.send(`:white_check_mark: Purged \`${deletedMessages}\` messages.`)
                    .then(m => m.delete(2000));
        }).catch(console.error);
    }

    if (command == "mute") { // creates the command mute
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var mutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!mutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        if (mutedmember.hasPermission("ADMINISTRATOR")) return message.reply("I cannot mute this member!") // if memebr is an admin
        var mutereasondelete = 10 + mutedmember.user.id.length //sets the length of the kickreasondelete
        var mutereason = message.content.substring(mutereasondelete).split(" "); // deletes the first letters until it reaches the reason
        var mutereason = mutereason.join(" "); // joins the list kickreason into one line
        if (!mutereason) return message.reply("Please indicate a reason for the mute!") // if no reason
        mutedmember.addRole(mutedrole) //if reason, kick
            .catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
        message.reply(`${mutedmember.user} has been muted by ${message.author} because: ${mutereason}`); // sends a message saying he was kicked
    }

    if (command == "unmute") { // creates the command unmute
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var unmutedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!unmutedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        unmutedmember.removeRole(mutedrole) //if reason, kick
            .catch(error => message.reply(`Sorry ${message.author} I couldn't mute because of : ${error}`)); //if error, display error
        message.reply(`${unmutedmember.user} has been unmuted by ${message.author}!`); // sends a message saying he was kicked
    }

    if (command == "kick") { // creates the command kick
        if (!message.member.roles.some(r=>["bot-admin"].includes(r.name)) ) return message.reply("Sorry, you do not have the permission to do this!"); // if author has no perms
        var kickedmember = message.mentions.members.first(); // sets the mentioned user to the var kickedmember
        if (!kickedmember) return message.reply("Please mention a valid member of this server!") // if there is no kickedmmeber var
        if (!kickedmember.kickable) return message.reply("I cannot kick this member!") // if the member is unkickable
        var kickreasondelete = 10 + kickedmember.user.id.length //sets the length of the kickreasondelete
        var kickreason = message.content.substring(kickreasondelete).split(" "); // deletes the first letters until it reaches the reason
        var kickreason = kickreason.join(" "); // joins the list kickreason into one line
        if (!kickreason) return message.reply("Please indicate a reason for the kick!") // if no reason
        kickedmember.kick(kickreason) //if reason, kick
            .catch(error => message.reply(`Sorry @${message.author} I couldn't kick because of : ${error}`)); //if error, display error
        message.reply(`${kickedmember.user.username} has been kicked by ${message.author.username} because: ${kickreason}`); // sends a message saying he was kicked
    }

});

bot.login(BOT_TOKEN); // connects to the bot

It is the only file in my bot folder except the package.json, package-lock.json and all the node_modules.

What I'm trying to do is type in discord *purge [number of messages I want to purge] and get the bot to delete the amount of the messages I asked it to delete, PLUS the command I entered (for example, if I ask the bot to delete 5 messages, he deletes 6 including the *purge 5 message.

Any help would be much appreciated, thanks!

Body:
note sure if this is still relevant but this what i use in my bots

     if (!suffix) {
    var newamount = "2";
  } else {
    var amount = Number(suffix);
    var adding = 1;
    var newamount = amount + adding;
  }
  let messagecount = newamount.toString();
  msg.channel
    .fetchMessages({
      limit: messagecount
    })
    .then(messages => {
      msg.channel.bulkDelete(messages);
      // Logging the number of messages deleted on both the channel and console.
      msg.channel
        .send(
          "Deletion of messages successful. \n Total messages deleted including command: " +
            newamount
        )
        .then(message => message.delete(5000));
      console.log(
        "Deletion of messages successful. \n Total messages deleted including command: " +
          newamount
      );
    })
    .catch(err => {
      console.log("Error while doing Bulk Delete");
      console.log(err);
    });

basic function is to specify number of messages to purge and it will delete that many plus the command used, the full example is here


问:
Hystrix and Connection Pooling
Please excuse this - it could well be a dumb newbie question.

We're using Hystrix as a Circuit Breaker between two services. To speed up performance we're using Connection Pooling. We're using the PoolingHttpClientConnectionManager from Apache HttpClient to handle the Connection Pool.

We're also using Hystrix's 'timeoutInMilliseconds' property to catch issues.

The 'problem' we have is that in normal operation it takes c130ms to create a new HTTPS connection, but once pooled the read time on those connections is c12ms.

So, we've had to set our 'timeoutInMilliseconds' threshold to be higher than we'd like so that Hystrix doesn't kick in whenever our Connection Pool decides to create a new connection. Our Non-Functional Requirements want the latency to the service to be nearer 12ms than 130ms.

Are we using Hystrix correctly? Are there other patterns we could follow when using Hystrix and Connection Pooling?

Many thanks,

Mike

答: You should configure Hystrix to timeout based on your TP99  + buffer latency. In your case, the TP99 latency is 130 ms. Add the median latency of ~20 ms, and configure the Hystrix to timeout at 150 ms.</p>

Title: Hystrix and Connection Pooling


问:
How to perform padding operation if the kernel stride is greater than the input shape dimensions in case of Maxpooling
I am trying to perform Maxpooling operation in caffe.

Input size is 6 x 6 x 1 x 1024 whereas the kernel size is 7 x 7.

Am i supposed to do padding inorder to perform MaxPooling.

答:
First, you haven't specified the stride; the kernel dimensions are 7x7, larger than your input, but that's the size, not the stride.  Stride is how far you move between iterations, such as shifting 2 pixels (which effectively halves the size of the output).

You probably want to pad so that the center of the kernel (element (3, 3) with 0-based indexing) can be over each pixel of your input.  This means that you need a 3-pixel pad ( (7-1)/2 ) in each direction.

Is that what you needed?


问:
How to make the page not reload clicking a button
I just learn html and css and I need to do a project that build a robot and control the robot using website.

When I click the button it will go to other page or reload

How do I pass the value in the button without reloading the page?

This is my code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>RPOC</title>
    </head>

    <body>
        <form action="welcome.php" method="post" type='submit'>
            <button>FORWARD
            <input type="hidden" name="value" value="1"><br></button>
        </form>

        <form action="welcome.php" method="post" type='submit'>
            <button>BACKWARD
            <input type="hidden" name="value" value="2"><br></button>
        </form>

    </body>
</html>
</code>```

答:
Looks like you need a ajax call...

Try something like this, but you will have to make a ajax.page.php file.
You can learn more at: http://api.jquery.com/jquery.ajax/

$('#btoForward01').click(function(e){
    var value01 = $('#value01').val();
    var fullURL = "ajax.page.php?value01=" + value01;
    //console.log(urlCompleta);
    e.preventDefault();
    $.ajax({
        url: fullURL,
        success: function(result){
            console.log('evething alright');
        },
        statusCode: {
            404: function(){alert( "Page not found" );},
            500: function(){alert( "PHP Error" );}
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="1" id="value01">
        <button type="submit" id="btoForward01">FORWARD</button>
    </form>
</body></code>```

Body:
I just learn html and css and I need to do a project that build a robot and control the robot using website.

When I click the button it will go to other page or reload

How do I pass the value in the button without reloading the page?

This is my code:

<!DOCTYPE html>

        <title>RPOC</title>

        <form action="welcome.php" method="post" type='submit'>
            <button>FORWARD
            <input type="hidden" name="value" value="1">
</button>
        </form>

        <form action="welcome.php" method="post" type='submit'>
            <button>BACKWARD
            <input type="hidden" name="value" value="2">
</button>
        </form>

Body:
Looks like you need a ajax call...

Try something like this, but you will have to make a ajax.page.php file.
You can learn more at: http://api.jquery.com/jquery.ajax/

$('#btoForward01').click(function(e){
    var value01 = $('#value01').val();
    var fullURL = "ajax.page.php?value01=" + value01;
    //console.log(urlCompleta);
    e.preventDefault();
    $.ajax({
        url: fullURL,
        success: function(result){
            console.log('evething alright');
        },
        statusCode: {
            404: function(){alert( "Page not found" );},
            500: function(){alert( "PHP Error" );}
        }
    });
});

<body>
    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="1" id="value01">
        <button type="submit" id="btoForward01">FORWARD</button>
    </form>
</body>


问:
RSSService item with the same key multiple times
I have a RSSService with an item like the one show below

```<code><item>
        <title>Accessori per la cura della persona</title>
        <link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
        <comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
        <pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
        <dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
                <category><![CDATA[News]]></category>
        <category><![CDATA[Offerte]]></category>
        <category><![CDATA[Callifugo]]></category>
        <category><![CDATA[Raspa piedi]]></category>
        <category><![CDATA[Spazzola ceramica]]></category>
        <category><![CDATA[Spazzola piatta]]></category>
        <category><![CDATA[Spazzola tonda]]></category>
        <category><![CDATA[Spazzole capelli]]></category>

        <guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
        <description>.....
</code>```

To read all the content I use this:

```<code>List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
                    b.setIcon(iconStar);
                } else {
                    b.setIcon(iconNews);
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }
</code>```

When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:

```<code>String[] mc = (String[]) m.get("category");
</code>```

Thank's in advance for any help.
Davide.

答:
This is my idea

```<code>protected void textElement(String text) {
                if(lastTag != null && current != null) {
                    // make "ATOM" seem like RSS
                    if("summary".equals(lastTag)) {
                        current.put("details", text);
                    } else {
                        if("content".equals(lastTag)) {
                            current.put("description", text);
                        } else {
                            if(current.get(lastTag) != null){
                                try {
                                    List list = (List) current.get(lastTag);
                                    list.add(text);
                                    current.put(lastTag, list);
                                } catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
                                    List list = new ArrayList();
                                    list.add((String)current.get(lastTag));
                                    list.add(text);
                                    current.put(lastTag, list);
                                }
                            } else {
                                current.put(lastTag, text);
                            }
                        }
                    }
                }
            }
</code>```

Used in my Form like this:

```<code>for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                try{
                    String category = (String)m.get("category");
                    if(category.equals(CATEGORY_OFFERTE)){
                        b.setIcon(iconStar);
                    } else {
                        b.setIcon(iconNews);
                    }
                } catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
                    b.setIcon(iconNews);
                    List list = (List) m.get("category");
                    for(int i=0; i < list.size(); i++){
                        if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
                            b.setIcon(iconStar);
                        }
                    }
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }
</code>```

Body:
I have a RSSService with an item like the one show below

<item>
        <title>Accessori per la cura della persona</title>
        <link>http://www.myurl.it/accessori-per-la-cura-della-persona/</link>
        <comments>http://www.myurl.it/accessori-per-la-cura-della-persona/#comments</comments>
        <pubDate>Tue, 24 Oct 2017 09:29:44 +0000</pubDate>
        <dc:creator><![CDATA[Farmacia Rizzo Davide]]></dc:creator>
                <category><![CDATA[News]]></category>
        <category><![CDATA[Offerte]]></category>
        <category><![CDATA[Callifugo]]></category>
        <category><![CDATA[Raspa piedi]]></category>
        <category><![CDATA[Spazzola ceramica]]></category>
        <category><![CDATA[Spazzola piatta]]></category>
        <category><![CDATA[Spazzola tonda]]></category>
        <category><![CDATA[Spazzole capelli]]></category>

        <guid isPermaLink="false">http://www.myurl.it/?p=3982</guid>
        <description>.....

To read all the content I use this:

List<Map> records;
...
records = rss.getResults();
...
for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                if(((String)m.get("category")).equals(CATEGORY_OFFERTE)){
                    b.setIcon(iconStar);
                } else {
                    b.setIcon(iconNews);
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }

When I read the key "category" I always get the last entry (in this item "Spazzole capelli").
There is a way to read a key like an array? Something like that:

String[] mc = (String[]) m.get("category");

Thank's in advance for any help.
Davide.

Body:
This is my idea

protected void textElement(String text) {
                if(lastTag != null && current != null) {
                    // make "ATOM" seem like RSS
                    if("summary".equals(lastTag)) {
                        current.put("details", text);
                    } else {
                        if("content".equals(lastTag)) {
                            current.put("description", text);
                        } else {
                            if(current.get(lastTag) != null){
                                try {
                                    List list = (List) current.get(lastTag);
                                    list.add(text);
                                    current.put(lastTag, list);
                                } catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
                                    List list = new ArrayList();
                                    list.add((String)current.get(lastTag));
                                    list.add(text);
                                    current.put(lastTag, list);
                                }
                            } else {
                                current.put(lastTag, text);
                            }
                        }
                    }
                }
            }

Used in my Form like this:

for (Map m : records) {
                Button b = new Button((String)m.get("title"));
                try{
                    String category = (String)m.get("category");
                    if(category.equals(CATEGORY_OFFERTE)){
                        b.setIcon(iconStar);
                    } else {
                        b.setIcon(iconNews);
                    }
                } catch (ClassCastException e){ // java.lang.String cannot be cast to java.util.List
                    b.setIcon(iconNews);
                    List list = (List) m.get("category");
                    for(int i=0; i < list.size(); i++){
                        if(((String)list.get(i)).equals(CATEGORY_OFFERTE)){
                            b.setIcon(iconStar);
                        }
                    }
                }
                b.addActionListener((l)->{
                    Boolean can = Display.getInstance().canExecute((String)m.get("link"));
                    if(can != null && can) {
                      Display.getInstance().execute((String)m.get("link"));
                    } else {
                      ToastBar.Status status = ToastBar.getInstance().createStatus();
                      status.setMessage("Non riesco a connettermi");
                      status.setExpires(3000);
                      status.show();
                    }
                });
                recordsContainer.addComponent(b);
            }


问:
How to convert a list of characters to ASCII in python?
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

```<code>string = input(“Enter a line of text: “)
l = list(string)
return(l)
</code>```

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

答:
You need to make a for loop to loop over each character and convert them to ASCII.

You already have l which is a list of each character in the string. So loop over l and convert each character in the list to the ASCII value using ord().

Body:
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

string = input(“Enter a line of text: “)
l = list(string)
return(l)

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?


答:
```<code>string = input("enter string: ")
for i in string:
    if i != ' ':            # ignoring space char
        print(i, ord(i))
</code>```

Input

```<code>sample string
</code>```

Output

```<code>s 115
a 97
m 109
p 112
l 108
e 101
s 115
t 116
r 114
i 105
n 110
g 103
</code>```

The output can even be saved to another list.

Title: How to convert a list of characters to ASCII in python?

Body:
string = input("enter string: ")
for i in string:
    if i != ' ':            # ignoring space char
        print(i, ord(i))

Input

sample string

Output

s 115
a 97
m 109
p 112
l 108
e 101
s 115
t 116
r 114
i 105
n 110
g 103

The output can even be saved to another list.


问:
When/How to solve this PLY Shift-Reduce conflict in parser generator for COOL language?
I am making a compiler for the Cool: the Classroom Object-Oriented Language. I followed the manual Cool-manual.pdf to create a grammar and using PLY 3.10 in python 3.5.2 I managed to create a lexer and a parser, but somehow it found a Shift-Reduce conflict on this production:

```<code>expr : LET ID COLON TYPE assign_optional let_assignments IN expr
</code>```

expr is a Non-terminal symbol that produces several things, among them is the "LET...." above but, as this LET production ends with "...IN expr" that means that the LALR(1) parser from yacc do not know if it should SHIFT after that last expr with what comes after or REDUCE  that expr.

For instance:

That last expr could be something like:

```<code>a + 2
</code>```

and as COOL allows I could also do this:

```<code>expr : expr + expr #that means expr produces expr PLUS expr
</code>```

and therefore, after that last expr in the LET I could have a + (or anything allowed). For instance, in this line

```<code>LET a:Int <- 3 IN a + 2 + c
</code>```

could mean to add a + 2 + c as the expression inside of the LET or to add c to the result of the LET expression.

My main issue is:

Should I redo the grammar to avoid this conflict? If i should, how would I do it? cause I think I am not doing anything wrong following the COOL specifications.

Else, Should I handle this on the Semantic Analysis Phase? Any thoughts on how to do it?

Thanks in advance.
I hope I explained myself. If not, please let me know and I will try to explain better.

答:
I don't know why let is not in the list of expression precedences in section 11 of the manual, but section 7 says

The <expr> of a let extends as far (encompasses as many tokens) as the grammar allows.

which is tantamount to saying that it has the lowest possible precedence (the same as assignment).

I presume you are using precedence declarations for your expr rules, so just add let to the list.

Body:
I am making a compiler for the Cool: the Classroom Object-Oriented Language. I followed the manual Cool-manual.pdf to create a grammar and using PLY 3.10 in python 3.5.2 I managed to create a lexer and a parser, but somehow it found a Shift-Reduce conflict on this production:

expr : LET ID COLON TYPE assign_optional let_assignments IN expr

expr is a Non-terminal symbol that produces several things, among them is the "LET...." above but, as this LET production ends with "...IN expr" that means that the LALR(1) parser from yacc do not know if it should SHIFT after that last expr with what comes after or REDUCE  that expr.

For instance:

That last expr could be something like:

a + 2

and as COOL allows I could also do this:

expr : expr + expr #that means expr produces expr PLUS expr

and therefore, after that last expr in the LET I could have a + (or anything allowed). For instance, in this line

LET a:Int <- 3 IN a + 2 + c

could mean to add a + 2 + c as the expression inside of the LET or to add c to the result of the LET expression.

My main issue is:

Should I redo the grammar to avoid this conflict? If i should, how would I do it? cause I think I am not doing anything wrong following the COOL specifications.

Else, Should I handle this on the Semantic Analysis Phase? Any thoughts on how to do it?

Thanks in advance.
I hope I explained myself. If not, please let me know and I will try to explain better.


问:
How to convert two-letter country codes to flag emojis?
I have ISO 3166-1 (alpha-2) country codes, which are two-letter codes, such as "US" and "NL". How do I get the corresponding flag emoji?

EDIT: Preferably I would like to do this without using an explicit mapping between country codes and their corresponding emojis. It has been done in JavaScript but I'm not sure how to do it in C#.

答:
XXXXXXXX SKIP THIS SECTION WHICH CONTAINS MY ORIGINAL ANSWER XXXXXXXX

You will need to generate a cross-reference table or dictionary that allows you to look up the corresponding emoji. Luckily it looks like you've already found a great source for the information you need!

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You can go here to find a chart of the appropriate unicode symbols for each letter. Basically, you just use the regional indicator symbol for each letter. For example, NZ would be U+1F1F3 (N) + U+1F1FF (Z). These two symbols are interpreted as the NZ flag if support is there for that emoji.

Because these letters are all contiguous, you can calculate the appropriate code for a given letter by using an offset from the normal upper case letters. You may have seen it in the code repository you referenced: it is 127397. Thus, 'A'+127397 is the regional indicator symbol for A.

Thanks for teaching me something new today, and good luck!