问:
Reference all commits between master branch-tip and HEAD in git
I currently am branched out of master (call it branchA). I have made a couple of commits to branchA and would now like to squash commits together on my branch prior to merging to master. Usually I do something like this in my branchA repo:

```<code>git rebase -i HEAD~n
</code>```

I would get n by doing a git log and manually counting the commits from (not including) the master branch tip until (and including) the branch's HEAD. For now the count has been easy as the commits are few.

Is there a simple way to reference all commits on current branch after master branch-tip commit?

答:
Is there a simple way to reference all commits on current branch after master branch-tip commit?

Yes, just do this:

```<code>git rebase -i master
</code>```

Body:
I currently am branched out of master (call it branchA). I have made a couple of commits to branchA and would now like to squash commits together on my branch prior to merging to master. Usually I do something like this in my branchA repo:

git rebase -i HEAD~n

I would get n by doing a git log and manually counting the commits from (not including) the master branch tip until (and including) the branch's HEAD. For now the count has been easy as the commits are few.

Is there a simple way to reference all commits on current branch after master branch-tip commit?

Body:
Is there a simple way to reference all commits on current branch after master branch-tip commit?

Yes, just do this:

git rebase -i master


来源: stackexchange

问:
How do you iterate objects in array?
I'm doing a quiz with only jquery and I need to get data from the JSON API through ajax, the data from the JSON API is randomly selected how do I get access properties of the objects?

I did it in this way but is there any other way I can do it instead of writing every single question down.

I'm new to Jquery:) please help

```<code>    $("p:eq(0)").text(data.results[0].question);
    $("p:eq(1)").text(data.results[1].question);
    $("p:eq(2)").text(data.results[2].question);
    $("p:eq(3)").text(data.results[3].question);
    $("p:eq(4)").text(data.results[4].question);
    $("p:eq(5)").text(data.results[5].question);
</code>```

答:
You can use a for loop:

```<code>for (var i = 0; i < data.results.length; i++) {
    $("p:eq(" + i + ")").text(data.results[i].question);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do you iterate objects in array?

Body:
I'm doing a quiz with only jquery and I need to get data from the JSON API through ajax, the data from the JSON API is randomly selected how do I get access properties of the objects?

I did it in this way but is there any other way I can do it instead of writing every single question down.

I'm new to Jquery:) please help

    $("p:eq(0)").text(data.results[0].question);
    $("p:eq(1)").text(data.results[1].question);
    $("p:eq(2)").text(data.results[2].question);
    $("p:eq(3)").text(data.results[3].question);
    $("p:eq(4)").text(data.results[4].question);
    $("p:eq(5)").text(data.results[5].question);

Body:
You can use a for loop:

for (var i = 0; i < data.results.length; i++) {
    $("p:eq(" + i + ")").text(data.results[i].question);
}


问:
Use attributes to avoid invalid input arguments
I have a Method which Takes Int as Input

public void GetMonth(int Month)
  {
  }

Now when I call this method I want to make sure that Compiler generates and Error Message when someone enters number which does not fall between 1-12.

e.g

obj.GetMonth(14)--Here it should give error and does not compile

Is it possible ?

答:
That will be a feature in 4.0, thanks to code-contracts, which allow you to declare exactly that. But not yet. You'll need to have validation code at runtime:</p>

```<code>if(month < 1 || month > 12) throw new ArgumentOutOfRangeException("month");
</code>```

OwnerDisplayName: SandHurst

LastEditorDisplayName: Marc Gravell

ContentLicense: CC BY-SA 2.5

Body:
That will be a feature in 4.0, thanks to code-contracts, which allow you to declare exactly that. But not yet. You'll need to have validation code at runtime:

if(month < 1 || month > 12) throw new ArgumentOutOfRangeException("month");

OwnerDisplayName: Marc Gravell


问:
Multiple Switch components are changing order in a List element when being pressed
I have a screen where the user is able to enable/disable specific push notifications. When a user presses on a toggle the correct toggle is changed and the state is being updated.

The issue that I have is that after the switch happened it does some strange ordering. See the video here (I'm sorry about the video quality, tried to execute it with this command: xcrun simctl io booted recordVideo toggle.mp4).

Component state

```<code>state = {
    defaultNotifications: {
      config_error: { active: true, normalized: 'Notifiy on configuration error' },
      on_first_start: { active: true, normalized: 'Notifiy on first start' },
      on_trigger: { active: true, normalized: 'Notifiy on trigger' },
      on_panic_start: { active: true, normalized: 'Notifiy on panic start' },
      on_panic_end: { active: true, normalized: 'Notifiy on panic sell end' },
      order_placed: { active: true, normalized: 'Notifiy on order placed' },
      trade_completed: { active: true, normalized: 'Notifiy on trade completed' },
      order_cancelled: { active: true, normalized: 'Notifiy on order cancelled' },
    }
  }
</code>```

Toggle function

```<code>const enabledNotifications = [];
const stateNotifications = this.state.defaultNotifications;
Object.keys(stateNotifications).forEach((notification) => {
  if (stateNotifications[notification].active) {
    enabledNotifications.push(notification);
  }
});
</code>```

I needed a comma separated string with the 'active' notification names for a POST request later:

```<code>const requestBody = qs.stringify({
  player_id: this.state.playerId,
  permissions: enabledNotifications.toString()
}, { arrayFormat: 'comma', encode: false });
</code>```

Change the toggle to !active

```<code>toggleNotification = (notification) => {
    this.setState({ defaultNotifications: {
      ...this.state.defaultNotifications,
      [notification]: {
        ...this.state.defaultNotifications[notification],
        active: !this.state.defaultNotifications[notification].active,
      }
    } });
  };
</code>```

Toggle in JSX

```<code>    const userNotifications = this.state.defaultNotifications;

    return (
      Object.keys(userNotifications).map((notification) =>
        <ListItem
        key={notification}
        >
          <Image
            style={{ width: 24, height: 24 }}
            source={require('../../../assets/more_icons/notify_green.png')}
          />
          <Text style={styles.notificationText}>
            { userNotifications[notification].normalized }
          </Text>
          <Switch
             onValueChange={() => this.toggleNotification(notification)}
             value={userNotifications[notification].active}
             style={{ marginLeft: 'auto' }}
           />
        </ListItem>
      )
    );
</code>```

I remember that I did clear my XCode Simulator cache with xcrun simctl erase all, a few minutes before this error occurred. But I can't think of any reason why that would cause any related issues.

答:
JavaScript does not guarantee the order of properties when iterating through an objects's properties. See this answer. So you cannot be sure that the keys are returned in the way you anticipate right now, and that can lead to random changes while rendering.

So my recommendation is to order the object keys actively prior to displaying them. For example, to sort them alphabetically:

```<code>Object.keys(userNotifications).sort().map((notification) => ...
</code>```

Alternatively, you could use an ordered array you set yourself:

```<code>['config_error', 'on_first_start', 'on_trigger', 'on_panic_start', 'on_panic_end', 'order_placed', 'trade_completed', 'order_cancelled'].map(key => userNotifications[key]).map((notification) => ...
</code>```

Body:
I have a screen where the user is able to enable/disable specific push notifications. When a user presses on a toggle the correct toggle is changed and the state is being updated.

The issue that I have is that after the switch happened it does some strange ordering. See the video here (I'm sorry about the video quality, tried to execute it with this command: xcrun simctl io booted recordVideo toggle.mp4).

Component state

state = {
    defaultNotifications: {
      config_error: { active: true, normalized: 'Notifiy on configuration error' },
      on_first_start: { active: true, normalized: 'Notifiy on first start' },
      on_trigger: { active: true, normalized: 'Notifiy on trigger' },
      on_panic_start: { active: true, normalized: 'Notifiy on panic start' },
      on_panic_end: { active: true, normalized: 'Notifiy on panic sell end' },
      order_placed: { active: true, normalized: 'Notifiy on order placed' },
      trade_completed: { active: true, normalized: 'Notifiy on trade completed' },
      order_cancelled: { active: true, normalized: 'Notifiy on order cancelled' },
    }
  }

Toggle function

const enabledNotifications = [];
const stateNotifications = this.state.defaultNotifications;
Object.keys(stateNotifications).forEach((notification) => {
  if (stateNotifications[notification].active) {
    enabledNotifications.push(notification);
  }
});

I needed a comma separated string with the 'active' notification names for a POST request later:

const requestBody = qs.stringify({
  player_id: this.state.playerId,
  permissions: enabledNotifications.toString()
}, { arrayFormat: 'comma', encode: false });

Change the toggle to !active

toggleNotification = (notification) => {
    this.setState({ defaultNotifications: {
      ...this.state.defaultNotifications,
      [notification]: {
        ...this.state.defaultNotifications[notification],
        active: !this.state.defaultNotifications[notification].active,
      }
    } });
  };

Toggle in JSX

    const userNotifications = this.state.defaultNotifications;

    return (
      Object.keys(userNotifications).map((notification) =>
        <ListItem
        key={notification}
        >
          <Image
            style={{ width: 24, height: 24 }}
            source={require('../../../assets/more_icons/notify_green.png')}
          />
          <Text style={styles.notificationText}>
            { userNotifications[notification].normalized }
          </Text>
          <Switch
             onValueChange={() => this.toggleNotification(notification)}
             value={userNotifications[notification].active}
             style={{ marginLeft: 'auto' }}
           />
        </ListItem>
      )
    );

I remember that I did clear my XCode Simulator cache with xcrun simctl erase all, a few minutes before this error occurred. But I can't think of any reason why that would cause any related issues.

Body:
JavaScript does not guarantee the order of properties when iterating through an objects's properties. See this answer. So you cannot be sure that the keys are returned in the way you anticipate right now, and that can lead to random changes while rendering.

So my recommendation is to order the object keys actively prior to displaying them. For example, to sort them alphabetically:

Object.keys(userNotifications).sort().map((notification) => ...

Alternatively, you could use an ordered array you set yourself:

['config_error', 'on_first_start', 'on_trigger', 'on_panic_start', 'on_panic_end', 'order_placed', 'trade_completed', 'order_cancelled'].map(key => userNotifications[key]).map((notification) => ...


问:
How to make PyCharm get type hints from function definition and populate type values in docstrings?
I always use type hints in function definitions, for example:

def foo(a: int, b: str) -> bool:
    pass
```

<p>When I use PyCharm auto docstring generator to make docstrings in my code, I get this:</p>

```def foo(a: int, b: str) -> bool:
    """
    :param a:
    :type a:
    :param b:
    :type b:
    """
    pass
```

<p>As you can see, the type values which I defined in the function itself have not been recognized by PyCharm, and I should write them in docstring again. How I can make PyCharm to auto-generate something like this for me (read type values from first line and insert them in the docstring):</p>

```def foo(a: int, b: str) -> bool:
    """
    :param a:
    :type a: int
    :param b:
    :type b: str
    :rtype: bool
    """
    pass
```

答:
Go to Settings -> Editor -> Intentions. There, under the category Python, tick in the box Specify type for reference in docstring.

Once this is activated you can use the debugger and its functionality: Insert documentation string stub to populate the docstring of the function. (Note that you will need to activate the option Collect runtime information for code insight located Settings -> Build, Execution, Deployment -> Python Debugger)

The process is a bit long to detail so, I will give the link of the official PyCharm tutorial about this: https://www.jetbrains.com/help/pycharm/using-docstrings-to-specify-types.html

Body:
I always use type hints in function definitions, for example:

def foo(a: int, b: str) -> bool:
    pass

When I use PyCharm auto docstring generator to make docstrings in my code, I get this:

def foo(a: int, b: str) -> bool:
    """
    :param a:
    :type a:
    :param b:
    :type b:
    """
    pass

As you can see, the type values which I defined in the function itself have not been recognized by PyCharm, and I should write them in docstring again. How I can make PyCharm to auto-generate something like this for me (read type values from first line and insert them in the docstring):

def foo(a: int, b: str) -> bool:
    """
    :param a:
    :type a: int
    :param b:
    :type b: str
    :rtype: bool
    """
    pass


问:
Make image inside div take the always the same amount of space
```<code><div id=“parent”>
    <div id = "child1">
       <img src="123"/>
   </div>
   <div id = "child2">
      <p> Some text1 </p>
      <p> Some text2 </p>
   </div>
</div>
</code>```

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

答:
Give #child and #child2 width, then make the img element's width 100% of the parent.

.parent {
  height: 400px;
  width: 500px;
}

.child {
  width: 49%;
  display: inline-block;
}

.child img {
 width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=“parent”>
    <div class="child">
       <img src="https://thumbor.forbes.com/thumbor/1280x868/https%3A%2F%2Fspecials-images.forbesimg.com%2Fdam%2Fimageserve%2F42977075%2F960x0.jpg%3Ffit%3Dscale"/>
   </div>
   <div class="child">
      <p> Some text1 </p>
      <p> Some text2 </p>
   </div>
</div></code>```

Body:
 Some text1

 Some text2

I have parent div with fixed height. Parent div always have 2 child containers:

1 clild - div with image

2 child - div with some data

The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1 and my #child2 with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".

How can I make my image inside #child1 take always same % of space inside #parent? (Probably, by zooming it in)

Body:
Give #child and #child2 width, then make the img element's width 100% of the parent.

.parent {
  height: 400px;
  width: 500px;
}

.child {
  width: 49%;
  display: inline-block;
}

.child img {
 width: 100%;
}

<div class=“parent”>
    <div class="child">
       <img src="https://thumbor.forbes.com/thumbor/1280x868/https%3A%2F%2Fspecials-images.forbesimg.com%2Fdam%2Fimageserve%2F42977075%2F960x0.jpg%3Ffit%3Dscale"/>
   </div>
   <div class="child">
      <p> Some text1 </p>
      <p> Some text2 </p>
   </div>
</div>


问:
UCanAccess exception "Unsupported newer version: 5"
I'm trying to access MS Access 2016 (.accdb) file using ucanaccess(4.0.2) jar with the code:

```<code>public class Test {
    static String path ="*****/src/main/resources/TestDatabase.accdb";  //absolute path to my access file
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
       Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
       Connection conn = DriverManager.getConnection("jdbc:ucanaccess://"+path);
}
</code>```

I'm getting the below exception :

```<code>Exception in thread "main" net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.2 Unsupported newer version: 5
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:264)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at db.Test.main(Test.java:29)
Caused by: java.io.IOException: Unsupported newer version: 5
at com.healthmarketscience.jackcess.impl.JetFormat.getFormat(JetFormat.java:293)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.<init>(DatabaseImpl.java:517)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:400)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:252)
at net.ucanaccess.jdbc.DefaultJackcessOpener.open(DefaultJackcessOpener.java:35)
at net.ucanaccess.jdbc.DBReference.<init>(DBReference.java:161)
at net.ucanaccess.jdbc.DBReferenceSingleton.loadReference(DBReferenceSingleton.java:51)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:98)
... 3 more
</code>```

Maven Dependencies used :

Any help would be appreciated.

Thanks.

答: I was facing same error. I've upgraded to jackcess-3.0.1 and it is solved now.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to access MS Access 2016 (.accdb) file using ucanaccess(4.0.2) jar with the code:

public class Test {
    static String path ="*****/src/main/resources/TestDatabase.accdb";  //absolute path to my access file
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
       Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
       Connection conn = DriverManager.getConnection("jdbc:ucanaccess://"+path);
}

I'm getting the below exception :

Exception in thread "main" net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.2 Unsupported newer version: 5
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:264)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at db.Test.main(Test.java:29)
Caused by: java.io.IOException: Unsupported newer version: 5
at com.healthmarketscience.jackcess.impl.JetFormat.getFormat(JetFormat.java:293)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.<init>(DatabaseImpl.java:517)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:400)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:252)
at net.ucanaccess.jdbc.DefaultJackcessOpener.open(DefaultJackcessOpener.java:35)
at net.ucanaccess.jdbc.DBReference.<init>(DBReference.java:161)
at net.ucanaccess.jdbc.DBReferenceSingleton.loadReference(DBReferenceSingleton.java:51)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:98)
... 3 more

Maven Dependencies used :

Any help would be appreciated.

Thanks.


问:
How can solve error in autopytoexe to compile python program to exe?
when I try to compile program in python 3.7
with:

auto-py-to-exe v2.6.0

Selenium

The code is:

from selenium import webdriver
import pathlib
import resource

fn = pathlib.Path(__file__).parent / 'chromedriver.exe'

browser = webdriver.Chrome(fn)
browser.get('website')

# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')

password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')

nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()

browser.get('website')

nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()

nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()

nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()
```

<p>error in compile</p>

```An error occurred, traceback follows:
Traceback (most recent call last):
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\auto_py_to_exe-2.6.0-py3.7.egg\auto_py_to_exe\__main__.py", line 259, in convert
    pyi.run() # Execute PyInstaller
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 29, in <module>
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 424, in __init__
    strip_binaries=self.strip, upx_binaries=self.upx,
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 196, in __init__
    self.__postinit__()
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 273, in assemble
    pylib_name = os.path.basename(bindepend.get_python_library_path())
  File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 214, in basename
    return split(p)[1]
  File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 183, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType
```

all log

i expect correct compile

i try

install windows sdk

install visual c++ libraries

need help to resolve the problem
this is the code from my python program

答:
One problem with your code is that you are trying to load chromedriver.exe which can be found in your current directory but after freezing it cannot be loaded anymore. When you want to freeze your app with Pyinstaller you first need to add that file to your output executable and then load it from the temp directory.

I'm not sure about auto-py-to-exe but you can use the below code and then use

pyinstaller -F --add-data "chromedriver.exe;." yourscript.py

```<code>from selenium import webdriver
import resource
import sys
import os

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

fn = resource_path('chromedriver.exe')

browser = webdriver.Chrome(fn)
browser.get('website')

# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')

password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')

nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()

browser.get('website')

nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()

nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()

nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()
</code>```

Body:
when I try to compile program in python 3.7
with:

auto-py-to-exe v2.6.0

Selenium

The code is:

from selenium import webdriver
import pathlib
import resource

fn = pathlib.Path(__file__).parent / 'chromedriver.exe'

browser = webdriver.Chrome(fn)
browser.get('website')

# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')

password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')

nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()

browser.get('website')

nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()

nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()

nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()

error in compile

An error occurred, traceback follows:
Traceback (most recent call last):
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\auto_py_to_exe-2.6.0-py3.7.egg\auto_py_to_exe\__main__.py", line 259, in convert
    pyi.run() # Execute PyInstaller
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 111, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\__main__.py", line 63, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 838, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\build_main.py", line 784, in build
    exec(text, spec_namespace)
  File "<string>", line 29, in <module>
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 424, in __init__
    strip_binaries=self.strip, upx_binaries=self.upx,
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 196, in __init__
    self.__postinit__()
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\datastruct.py", line 158, in __postinit__
    self.assemble()
  File "e:\documentos\proyectos\synctango2woocomerce\venv\lib\site-packages\PyInstaller\building\api.py", line 273, in assemble
    pylib_name = os.path.basename(bindepend.get_python_library_path())
  File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 214, in basename
    return split(p)[1]
  File "C:\Users\Jesus-NewPC\AppData\Local\Programs\Python\Python37\lib\ntpath.py", line 183, in split
    p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not NoneType

all log

i expect correct compile

i try

install windows sdk

install visual c++ libraries

need help to resolve the problem
this is the code from my python program

Body:
One problem with your code is that you are trying to load chromedriver.exe which can be found in your current directory but after freezing it cannot be loaded anymore. When you want to freeze your app with Pyinstaller you first need to add that file to your output executable and then load it from the temp directory.

I'm not sure about auto-py-to-exe but you can use the below code and then use

pyinstaller -F --add-data "chromedriver.exe;." yourscript.py

from selenium import webdriver
import resource
import sys
import os

def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

fn = resource_path('chromedriver.exe')

browser = webdriver.Chrome(fn)
browser.get('website')

# fill in username and hit the next button
username = browser.find_element_by_id('user_login')
username.send_keys('xxxxxxx')

password = browser.find_element_by_id('user_pass')
password.send_keys('xxxxxxxxxx')

nextButton1 = browser.find_element_by_id('wp-submit')
nextButton1.click()

browser.get('website')

nextButton2 = browser.find_element_by_class_name('add-new-h2')
nextButton2.click()

nextButton3 = browser.find_element_by_id('is_continue_no')
nextButton3.click()

nextButton4 = browser.find_element_by_class_name('rad10')
nextButton4.click()


问:
When should I generate a mix umbrella vs a phoenix umbrella?
I'm not sure when to use mix and when to use phoenix for creating umbrella applications.

I have read a lot of articles online but they are not clear of the reasoning for using mix over phoenix and vis versa.

mix gives:

```<code>- apps/
- config/
</code>```

phoenix gives:

```<code>- build/dev/(consolidated/lib)
- apps/(app_name/app_name_web)
- config/(configs for different envs)
- deps/(stuffffff)
</code>```

mix new [UMBRELLA NAME] --umbrella VS mix phx.new [UMBRELLA NAME] --umbrella

If I want to generate an umbrella that has an application that will serve html/json, how should I look at these commands?

答: At the end of the day, they are both the same thing. The difference is that Phoenix already generates an umbrella with two applications, one for your domain and another for the web, and if you ran mix new you would have to assemble everything by hand. So if you are building a web application, use Phoenix, because it will give you a head start on setting everything up.

Body:
I'm not sure when to use mix and when to use phoenix for creating umbrella applications.

I have read a lot of articles online but they are not clear of the reasoning for using mix over phoenix and vis versa.

mix gives:

- apps/
- config/

phoenix gives:

- build/dev/(consolidated/lib)
- apps/(app_name/app_name_web)
- config/(configs for different envs)
- deps/(stuffffff)

mix new [UMBRELLA NAME] --umbrella VS mix phx.new [UMBRELLA NAME] --umbrella

If I want to generate an umbrella that has an application that will serve html/json, how should I look at these commands?


问:
Rails - No route matches [POST]
Why does my test:

```<code>feature "Manage todos" do
  scenario "create a new todo" do
    visit root_path
    fill_in 'Email address', with: 'junk@snap2web.com'
    click_button 'Sign in'
    click_link('Add a new todo')
    fill_in 'Description', with: 'Buy some milk'
    click_button 'Create todo'
    expect(page).to have_css 'li.todo', text: 'Buy some Milk'
  end
end
</code>```

error with:

```<code>1) Manage todos create a new todo
  Failure/Error: click_button 'Create todo'
  ActionController::RoutingError:
    No route matches [POST] "/todos/new"
</code>```

When my routes has:

```<code>Todos::Application.routes.draw do
  root 'high_voltage/pages#show', id: 'homepage'
  resource :session, only: [:create]
  resources :todos
end
</code>```

and rake routes shows:

```<code>   Prefix Verb   URI Pattern               Controller#Action
     root GET    /                         high_voltage/pages#show {:id=>"homepage"}
  session POST   /session(.:format)        sessions#create
    todos GET    /todos(.:format)          todos#index
          POST   /todos(.:format)          todos#create
 new_todo GET    /todos/new(.:format)      todos#new
edit_todo GET    /todos/:id/edit(.:format) todos#edit
     todo GET    /todos/:id(.:format)      todos#show
          PATCH  /todos/:id(.:format)      todos#update
          PUT    /todos/:id(.:format)      todos#update
          DELETE /todos/:id(.:format)      todos#destroy
     page GET    /pages/*id                high_voltage/pages#show
</code>```

and my controller has:

```<code>$ cat app/controllers/todos_controller.rb
class TodosController < ApplicationController
  def index
  end

  def new
  end

end
</code>```

and the form has:

```<code>$ cat app/views/todos/new.html.erb
Add a new todo
<%= form_for :todo do |f| %>
  <%= f.label :description %>
  <%= f.text_field :description %>
  <%= f.submit 'Create todo' %>
<% end %>
</code>```

答:
Adding the path in the form field will redirect to the post path</p>

```<code><%= form_for :todo do, url: todos_path  |f| %>
</code>```

Title: Rails - No route matches [POST]

Body:
Why does my test:

feature "Manage todos" do
  scenario "create a new todo" do
    visit root_path
    fill_in 'Email address', with: 'junk@snap2web.com'
    click_button 'Sign in'
    click_link('Add a new todo')
    fill_in 'Description', with: 'Buy some milk'
    click_button 'Create todo'
    expect(page).to have_css 'li.todo', text: 'Buy some Milk'
  end
end

error with:

1) Manage todos create a new todo
  Failure/Error: click_button 'Create todo'
  ActionController::RoutingError:
    No route matches [POST] "/todos/new"

When my routes has:

Todos::Application.routes.draw do
  root 'high_voltage/pages#show', id: 'homepage'
  resource :session, only: [:create]
  resources :todos
end

and rake routes shows:

   Prefix Verb   URI Pattern               Controller#Action
     root GET    /                         high_voltage/pages#show {:id=>"homepage"}
  session POST   /session(.:format)        sessions#create
    todos GET    /todos(.:format)          todos#index
          POST   /todos(.:format)          todos#create
 new_todo GET    /todos/new(.:format)      todos#new
edit_todo GET    /todos/:id/edit(.:format) todos#edit
     todo GET    /todos/:id(.:format)      todos#show
          PATCH  /todos/:id(.:format)      todos#update
          PUT    /todos/:id(.:format)      todos#update
          DELETE /todos/:id(.:format)      todos#destroy
     page GET    /pages/*id                high_voltage/pages#show

and my controller has:

$ cat app/controllers/todos_controller.rb
class TodosController < ApplicationController
  def index
  end

  def new
  end

end

and the form has:

$ cat app/views/todos/new.html.erb
Add a new todo
<%= form_for :todo do |f| %>
  <%= f.label :description %>
  <%= f.text_field :description %>
  <%= f.submit 'Create todo' %>
<% end %>

Body:
Adding the path in the form field will redirect to the post path

<%= form_for :todo do, url: todos_path  |f| %>


问:
RegEx for matching yaml files
I have the next directory path which contains yaml files:

```<code>test/1.yaml
test/dev.yaml
test/dev0_r.yaml
</code>```

etc.

How can I match all yaml files which are exactly in test/ directory but not in sub directories like test/test1/dev.yaml

I was trying to use globing:

```<code>test/*.yaml
</code>```

but it didn't work on https://regex101.com/

How can I achieve it?

答:
Here, we would be adding a non-slash char class condition after the test dir to only pass the first directory, with an expression similar to:

```<code>^test\/[^\/]+\.yaml$
</code>```

We can add/reduce our boundaries, if we wish so. We could for instance drop the start and end anchors and it might still work:

```<code>test\/[^\/]+\.yaml
</code>```

Demo

const regex = /^test\/[^\/]+\.yaml$/gm;
const str = `test/1.yaml
test/dev.yaml
test/dev0_r.yaml
test/test1/dev.yaml`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

Title: RegEx for matching yaml files

Body:
I have the next directory path which contains yaml files:

test/1.yaml
test/dev.yaml
test/dev0_r.yaml

etc.

How can I match all yaml files which are exactly in test/ directory but not in sub directories like test/test1/dev.yaml

I was trying to use globing:

test/*.yaml

but it didn't work on https://regex101.com/

How can I achieve it?

Body:
Here, we would be adding a non-slash char class condition after the test dir to only pass the first directory, with an expression similar to:

^test\/[^\/]+\.yaml$

We can add/reduce our boundaries, if we wish so. We could for instance drop the start and end anchors and it might still work:

test\/[^\/]+\.yaml

Demo

const regex = /^test\/[^\/]+\.yaml$/gm;
const str = `test/1.yaml
test/dev.yaml
test/dev0_r.yaml
test/test1/dev.yaml`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
Docker - No executable found matching command "dotnet-/bin/MyApp.dll"
I'm learning Docker. I have a Console app created with .NET Core. This console app has a Dockerfile in it. That Dockerfile looks like this:

```<code>FROM microsoft/dotnet:2.1-runtime AS base
FROM microsoft/dotnet:2.1-sdk

# Copy the compiled files
COPY . ./bin

ENTRYPOINT ["dotnet", "/bin/MyApp.dll"]
</code>```

I intentionally want to copy the compiled files into the Docker images. I do NOT want to build the code on the Docker image due to issues with the dependencies. Still, when I select the play button in Visual Studio that says "Docker" I can see that the image gets successfully created via the "Output" window. In addition, my console app writes messages to the "Output" window as expected. For these reasons, I'm assuming my Dockerfile is correct.

Now, I try to run the build image from a command line outside of Visual Studio. From the directory where my .csproj file is located, I run docker build .. When I do this, I see the following:

```<code>Sending build context to Docker daemon   11.8MB
Step 1/4 : FROM microsoft/dotnet:2.1-runtime AS base
 ---> 59184f8be664
 ---> Using cache
 ---> 3a64d221c7f1
Step 2/4 : FROM microsoft/dotnet:2.1-sdk
 ---> 6691c7a1e6c7
Step 3/4 : COPY . ./app
 ---> e3e894ef7997
Step 4/4 : ENTRYPOINT ["dotnet", "/bin/MyApp.dll"]
 ---> Running in 355713fb3562
Removing intermediate container 355713fb3562
 ---> 88d4918847b9
Successfully built 78d4918847b8
</code>```

I then run docker container run 78d4918847b8 from the command line and I see the message:

```<code>No executable found matching command "dotnet-/bin/MyApp.dll"
</code>```

I don't understand why I can run the image from Visual Studio but not from the command line myself. What am I doing wrong?

答:
The error message actually means File not found (see https://github.com/dotnet/core-setup/issues/1126 as suggested by @oneturkmen).

The reason the file is not found is because you are copying the files to  ./bin  which is a relative path but the ENTRYPOINT is looking in /bin which is an absolute path, related to the root folder.

If you change your DOCKERFILE to:

```<code>FROM microsoft/dotnet:2.1-runtime AS base
FROM microsoft/dotnet:2.1-sdk

# Copy the compiled files
COPY . ./bin

ENTRYPOINT ["dotnet", "./bin/MyApp.dll"]
</code>```

then it should work. Please note the  ./bin in the entrypoint

Body:
I'm learning Docker. I have a Console app created with .NET Core. This console app has a Dockerfile in it. That Dockerfile looks like this:

FROM microsoft/dotnet:2.1-runtime AS base
FROM microsoft/dotnet:2.1-sdk

# Copy the compiled files
COPY . ./bin

ENTRYPOINT ["dotnet", "/bin/MyApp.dll"]

I intentionally want to copy the compiled files into the Docker images. I do NOT want to build the code on the Docker image due to issues with the dependencies. Still, when I select the play button in Visual Studio that says "Docker" I can see that the image gets successfully created via the "Output" window. In addition, my console app writes messages to the "Output" window as expected. For these reasons, I'm assuming my Dockerfile is correct.

Now, I try to run the build image from a command line outside of Visual Studio. From the directory where my .csproj file is located, I run docker build .. When I do this, I see the following:

Sending build context to Docker daemon   11.8MB
Step 1/4 : FROM microsoft/dotnet:2.1-runtime AS base
 ---> 59184f8be664
 ---> Using cache
 ---> 3a64d221c7f1
Step 2/4 : FROM microsoft/dotnet:2.1-sdk
 ---> 6691c7a1e6c7
Step 3/4 : COPY . ./app
 ---> e3e894ef7997
Step 4/4 : ENTRYPOINT ["dotnet", "/bin/MyApp.dll"]
 ---> Running in 355713fb3562
Removing intermediate container 355713fb3562
 ---> 88d4918847b9
Successfully built 78d4918847b8

I then run docker container run 78d4918847b8 from the command line and I see the message:

No executable found matching command "dotnet-/bin/MyApp.dll"

I don't understand why I can run the image from Visual Studio but not from the command line myself. What am I doing wrong?

Body:
The error message actually means File not found (see https://github.com/dotnet/core-setup/issues/1126 as suggested by @oneturkmen).

The reason the file is not found is because you are copying the files to  ./bin  which is a relative path but the ENTRYPOINT is looking in /bin which is an absolute path, related to the root folder.

If you change your DOCKERFILE to:

FROM microsoft/dotnet:2.1-runtime AS base
FROM microsoft/dotnet:2.1-sdk

# Copy the compiled files
COPY . ./bin

ENTRYPOINT ["dotnet", "./bin/MyApp.dll"]

then it should work. Please note the  ./bin in the entrypoint


问:
Is it possible to query in mongodb with field appended with randomid
I have a field priority which is appended with randomid generated ex":

```<code>"priority_123":"HIGH" ,"priority_234"..."HIGH"
</code>```

I want query the value of priority field somehow using regex on field like
{"priority_":"HIGH"}

Is it possible or do i need to change my structure of saving the field?

Please help me

答:
One (and perhaps the only) way I think this could be achieved, is by using the $where operator.

```<code>db.collection.find({
    $where: function() {
        for (var key in this) {
            if (key.indexOf('priority_') === 0 && this[key] === 'HIGH') {
                 return true
            }
        }

        return false
    }
})
</code>```

Although, as you can tell, it's much slower than a regular query, since it makes the database execute JavaScript for each document. I'd not recommend using this, especially if there can be a large amount of documents in your collection.

A better approach would be to change your structure, as you have already mentioned.
Maybe something like this?

```<code>[{
    priority: {
        salt: '123',
        value: 'HIGH',
    }
}, {
    priority: {
        salt: '234',
        value: 'HIGH',
    }
}]

db.collection.find({
    'priority.value': 'HIGH'
})
</code>```

Body:
I have a field priority which is appended with randomid generated ex":

"priority_123":"HIGH" ,"priority_234"..."HIGH"

I want query the value of priority field somehow using regex on field like
{"priority_":"HIGH"}

Is it possible or do i need to change my structure of saving the field?

Please help me

Body:
One (and perhaps the only) way I think this could be achieved, is by using the $where operator.

db.collection.find({
    $where: function() {
        for (var key in this) {
            if (key.indexOf('priority_') === 0 && this[key] === 'HIGH') {
                 return true
            }
        }

        return false
    }
})

Although, as you can tell, it's much slower than a regular query, since it makes the database execute JavaScript for each document. I'd not recommend using this, especially if there can be a large amount of documents in your collection.

A better approach would be to change your structure, as you have already mentioned.
Maybe something like this?

[{
    priority: {
        salt: '123',
        value: 'HIGH',
    }
}, {
    priority: {
        salt: '234',
        value: 'HIGH',
    }
}]

db.collection.find({
    'priority.value': 'HIGH'
})


问:
Led matrix row bits don't shift
I am new to VHDL and I am trying to do a simple application with a led matrix (8x8). My goal is to turn on the leds of the matrix so I can see a smiley face. For some reason none of the leds turn on.

In order to see what's wrong I tried to turn on all leds on each line at a time by commenting the case statement and giving cols<="00000000" before the statement, the result is that the only line that turns on is the first, it keeps turning on and off each second.

I made the frequency divider for 1 second just to see if the code works correctly.

```<code>use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.std_logic_unsigned.all;

entity main is
    Port ( clk : in STD_LOGIC;
           rows : out STD_LOGIC_VECTOR (7 downto 0);
           cols : out STD_LOGIC_VECTOR (7 downto 0));
end main;

architecture Behavioral of main is

signal count: std_logic_vector(7 downto 0):= "00000001";
signal clk1Hz: std_logic_vector(26 downto 0);

begin

process(clk)
begin
    if rising_edge(clk) then
        if clk1Hz = X"5F5E0FF" then
            clk1Hz <= "000" & X"000000";
        else
            clk1Hz <= clk1Hz + 1;
        end if;

        if clk1Hz(26) = '1' then
            if count = "10000000" then
                count <= "00000001";
             else
                count(7 downto 1) <= count(6 downto 0);
                count(0) <= '0';
            end if;

         rows <= count;

        case count is
            when "00000001" => cols <= "11111111";
            when "00000010" => cols <= "11011011";
            when "00000100" => cols <= "11011011";
            when "00001000" => cols <= "11111111";
            when "00010000" => cols <= "00111100";
            when "00100000" => cols <= "10000001";
            when "01000000" => cols <= "11000011";
            when "10000000" => cols <= "11111111";
            when others => cols <= "11111111";
         end case;
     end if;

    end if;

end process;
end Behavioral;
</code>```

答:
I can tell you didn't simulate this.  The clk1Hz signal wasn't initialized and wasn't reset.  It won't spin in sim without this, since it initializes to X.  However, on hardware it will work just fine.

So, when your clk counter hits x400_0000, bit (26) is set and your row/col shifters start going like mad for 1/3 of a second. Then when the clk counter resets, all activity stops.
Is this really what you want?  I can see from simulating this that rows and cols are both shifting correctly, albeit for only a third of a second.

During the pause, rows stops at 0x80, and cols at 0xFF.

Title: Led matrix row bits don't shift

Body:
I am new to VHDL and I am trying to do a simple application with a led matrix (8x8). My goal is to turn on the leds of the matrix so I can see a smiley face. For some reason none of the leds turn on.

In order to see what's wrong I tried to turn on all leds on each line at a time by commenting the case statement and giving cols<="00000000" before the statement, the result is that the only line that turns on is the first, it keeps turning on and off each second.

I made the frequency divider for 1 second just to see if the code works correctly.

use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.std_logic_unsigned.all;

entity main is
    Port ( clk : in STD_LOGIC;
           rows : out STD_LOGIC_VECTOR (7 downto 0);
           cols : out STD_LOGIC_VECTOR (7 downto 0));
end main;

architecture Behavioral of main is

signal count: std_logic_vector(7 downto 0):= "00000001";
signal clk1Hz: std_logic_vector(26 downto 0);

begin

process(clk)
begin
    if rising_edge(clk) then
        if clk1Hz = X"5F5E0FF" then
            clk1Hz <= "000" & X"000000";
        else
            clk1Hz <= clk1Hz + 1;
        end if;

        if clk1Hz(26) = '1' then
            if count = "10000000" then
                count <= "00000001";
             else
                count(7 downto 1) <= count(6 downto 0);
                count(0) <= '0';
            end if;

         rows <= count;

        case count is
            when "00000001" => cols <= "11111111";
            when "00000010" => cols <= "11011011";
            when "00000100" => cols <= "11011011";
            when "00001000" => cols <= "11111111";
            when "00010000" => cols <= "00111100";
            when "00100000" => cols <= "10000001";
            when "01000000" => cols <= "11000011";
            when "10000000" => cols <= "11111111";
            when others => cols <= "11111111";
         end case;
     end if;

    end if;

end process;
end Behavioral;


问:
Passing a column name as an argument for KDB select query?
I would like to pass a column name into a Q function to query a loaded table.

Example:

```<code>getDistinct:{[x] select count x from raw}
getDistinct "HEADER"
</code>```

This doesn't work as the Q documentation says I cannot pass column as arguments. Is there a way to bypass this?

答: To get the functional form of a select statement, I recommend using buildSelect. Also, reduce the scope of parenthesis, i.e. use enlist[`countDistinct]</code> instead of <code>(enlist `countDistinct).

Body:
I would like to pass a column name into a Q function to query a loaded table.

Example:

getDistinct:{[x] select count x from raw}
getDistinct "HEADER"

This doesn't work as the Q documentation says I cannot pass column as arguments. Is there a way to bypass this?


问:
CSS transform does not get applied on elements selected by :nth-child()
Consider the following HTML:

```<code><p>
  <span> A </span>
  <span> A </span>
  <span> A </span>
</p>
</code>```

Now try applying this CSS on it:

```<code>p span:nth-of-type(2) {transform: rotateX( 180deg ) ; color: blue }
</code>```

You will see that the color has been changed on the second span, but the transform property has not. Could anyone explain why this is the case?

答:
:nth-child won't apply to the class, just the element only it works. You need to apply to the children first then it works fine.

p span:nth-of-type(3) {
  display: inline-block;
  transform: rotateX( 180deg);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <span> A </span>
  <span> A </span>
  <span> A </span>
</p></code>```

Body:
Consider the following HTML:

   A
   A
   A

Now try applying this CSS on it:

p span:nth-of-type(2) {transform: rotateX( 180deg ) ; color: blue }

You will see that the color has been changed on the second span, but the transform property has not. Could anyone explain why this is the case?

Body:
:nth-child won't apply to the class, just the element only it works. You need to apply to the children first then it works fine.

p span:nth-of-type(3) {
  display: inline-block;
  transform: rotateX( 180deg);
 }

<p>
  <span> A </span>
  <span> A </span>
  <span> A </span>
</p>


问:
floating hint text not disappear after typing something
i want to make a register fragment with text input layout. But my problem is hint property. when typing, hint's copy goes up. I have two hints when typing.And also I don't have this problem in activity page. How can i solve this in fragment?

https://imgur.com/a/S7evtIO

```<code><android.support.design.widget.TextInputLayout
        android:id="@+id/floating_hint_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintTextAppearance="@style/FloatingHintStyle">

        <EditText
            android:id="@+id/etEmail"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ems="10"
            android:hint="Emailinizi giriniz"
            android:inputType="textEmailAddress" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/floating_hint_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintEnabled="true"
        app:hintTextAppearance="@style/FloatingHintStyle">

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Şifrenizi giriniz"
            android:inputType="textPassword" />
    </android.support.design.widget.TextInputLayout>
</code>```

答:
You need to use TextInputEditText instead of EditText, your code should be like

```<code><android.support.design.widget.TextInputLayout
    android:id="@+id/floating_hint_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/etEmail"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:ems="10"
        android:hint="Emailinizi giriniz"
        android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/floating_hint_pass"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Şifrenizi giriniz"
        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
</code>```

Body:
i want to make a register fragment with text input layout. But my problem is hint property. when typing, hint's copy goes up. I have two hints when typing.And also I don't have this problem in activity page. How can i solve this in fragment?

https://imgur.com/a/S7evtIO

<android.support.design.widget.TextInputLayout
        android:id="@+id/floating_hint_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintTextAppearance="@style/FloatingHintStyle">

        <EditText
            android:id="@+id/etEmail"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:ems="10"
            android:hint="Emailinizi giriniz"
            android:inputType="textEmailAddress" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/floating_hint_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:hintEnabled="true"
        app:hintTextAppearance="@style/FloatingHintStyle">

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="Şifrenizi giriniz"
            android:inputType="textPassword" />
    </android.support.design.widget.TextInputLayout>

Body:
You need to use TextInputEditText instead of EditText, your code should be like

<android.support.design.widget.TextInputLayout
    android:id="@+id/floating_hint_email"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/etEmail"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:ems="10"
        android:hint="Emailinizi giriniz"
        android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:id="@+id/floating_hint_pass"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Şifrenizi giriniz"
        android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>


问:
How to call a function when its arguments come from different places
I want to call a function (showResult), but each of its required arguments comes from different places. I have to wait until an event handler (server sends a response) for the price, but don't know how I'm supposed to pass the other required argument (product).

EDIT: To clarify, server.onResponse is referring to websocket connection's "onmessage" event handler ( reference )

```<code>function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product);
}

server.onResponse(function(response) {
   //response contains only information about the price, but not
   //what product its for

   showResult( , response.price);

});

function showResult (product, cost) {
   alert(product + " costs " + response + "dollars");
}

</code>```

答:
Declare the response function within the requestPhoneCost function, so it can access product in the closure.

```<code>function requestPhoneCost() {
  var product = "iPhone 7";
  server.requestPrice(product);
  server.onResponse(function(response) {
    showResult(product, response.price);
  });
}

function showResult(product, cost) {
  alert(product + " costs " + response + "dollars");
}
</code>```

This assumes that server.onResponse() replaces the response event listener, rather than adding an additional listener.

Body:
I want to call a function (showResult), but each of its required arguments comes from different places. I have to wait until an event handler (server sends a response) for the price, but don't know how I'm supposed to pass the other required argument (product).

EDIT: To clarify, server.onResponse is referring to websocket connection's "onmessage" event handler ( reference )

function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product);
}

server.onResponse(function(response) {
   //response contains only information about the price, but not
   //what product its for

   showResult( , response.price);

});

function showResult (product, cost) {
   alert(product + " costs " + response + "dollars");
}

Body:
Declare the response function within the requestPhoneCost function, so it can access product in the closure.

function requestPhoneCost() {
  var product = "iPhone 7";
  server.requestPrice(product);
  server.onResponse(function(response) {
    showResult(product, response.price);
  });
}

function showResult(product, cost) {
  alert(product + " costs " + response + "dollars");
}

This assumes that server.onResponse() replaces the response event listener, rather than adding an additional listener.


问:
Implementing Multitenancy Using Namespaces (Python 3+)
How to implement multitenancy in GAE using namespaces?

We can implement using namespace_manager in Python 2.7 but there is no documentation available on how to use it in Python 3.7.

Is there any other approach to achieve multitenancy in GAE?

答:
The Namespaces API is only supported in the Python 2.7 runtime. If you need a multi-tenant app in the Python 3.7 runtime, you'll need to implement it via your web framework of choice.

For example, see "optimal architecture for multitenant application on django
".


问:
Recursive function in Clojure
I have written a recursive function in java and want to implement the same for Clojure.

The java code snippet is below.

```<code>private boolean solve(int i, int j) {
    // some other code
    if ((solve(i - 1, j)) == true) {
        return true;
    }
    if ((solve(i, j + 1)) == true) {
        return true;
    }
    // some code!!!!
    return false;
}
</code>```

How can this be implemented in Clojure?

答:
an almost direct equivalent is

```<code>(defn solve [i j]
  (or ;; some other code
      (solve (dec i) j)
      (solve i (inc j))
      ;; some code
      ))
</code>```

Notice the absence of a return statement - everything is an expression.

In your java snippet "some other code" must have the ability to return truthy, otherwise you end up with a stack overflow (in place of "endless recursion").

The reason the code can be so short is that the or macro short-circuits evaluation (ie. it stops evaluation as soon as a meaningful result can be deduced).

In the clojure example "some other code" must be an expression that could evaluate to false or nil.

If you need to "return false immediately" from "some other code" your expression needs to be a bit more convoluted.

Title: Recursive function in Clojure

Body:
I have written a recursive function in java and want to implement the same for Clojure.

The java code snippet is below.

private boolean solve(int i, int j) {
    // some other code
    if ((solve(i - 1, j)) == true) {
        return true;
    }
    if ((solve(i, j + 1)) == true) {
        return true;
    }
    // some code!!!!
    return false;
}

How can this be implemented in Clojure?

Body:
an almost direct equivalent is

(defn solve [i j]
  (or ;; some other code
      (solve (dec i) j)
      (solve i (inc j))
      ;; some code
      ))

Notice the absence of a return statement - everything is an expression.

In your java snippet "some other code" must have the ability to return truthy, otherwise you end up with a stack overflow (in place of "endless recursion").

The reason the code can be so short is that the or macro short-circuits evaluation (ie. it stops evaluation as soon as a meaningful result can be deduced).

In the clojure example "some other code" must be an expression that could evaluate to false or nil.

If you need to "return false immediately" from "some other code" your expression needs to be a bit more convoluted.


问:
How to select (slice) in Pandas multiple rows and multiple non continuous columns?
I have a dataFrame and I want a range of specific rows and at the same time a range that is composed of a continuous range of columns plus an additional one.  Included is a piece of code that produces such a dataFrame

```<code>import pandas as pd
import numpy as np
np.random.seed(5)
dF = pd.DataFrame(np.random.randint(100, size=(100, 6)),
              columns=list('ABCDEF'),
              index=['R{}'.format(i) for i in range(100)])
dF.head()
</code>```

This works fine:

```<code>dF.loc[:, 'C':'E']
</code>```

But I need something like this, that produces an error:

```<code>dF.loc['R95':, ['A':'C', 'F']]
</code>```

The expected result has to include from row 'R95' onwards and columns 'A', 'C' and 'F'

答:
This is an ugly solution but it still has a colon in it</p>

```<code>df.loc['R95':, df.loc[:,'A':'C'].columns.tolist()+['F']]
</code>```

Body:
I have a dataFrame and I want a range of specific rows and at the same time a range that is composed of a continuous range of columns plus an additional one.  Included is a piece of code that produces such a dataFrame

import pandas as pd
import numpy as np
np.random.seed(5)
dF = pd.DataFrame(np.random.randint(100, size=(100, 6)),
              columns=list('ABCDEF'),
              index=['R{}'.format(i) for i in range(100)])
dF.head()

This works fine:

dF.loc[:, 'C':'E']

But I need something like this, that produces an error:

dF.loc['R95':, ['A':'C', 'F']]

The expected result has to include from row 'R95' onwards and columns 'A', 'C' and 'F'

Body:
This is an ugly solution but it still has a colon in it

df.loc['R95':, df.loc[:,'A':'C'].columns.tolist()+['F']]


问:
How do you run CMD.exe under the Local System Account?
I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.

I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively."  Here's a sample command:

```<code>AT 12:00 /interactive cmd.exe
</code>```

Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe.

```<code>C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact
C:\sc start RunCMDAsLSA
</code>```

In this case the service fails to start and results it the following error message:

```<code>FAILED 1053: The service did not respond to the start or control request in a timely fashion.
</code>```

The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.

I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.

Thus far, each of my attempts have ended in failure. Any suggestions?

答:
Using task scheduler, schedule a run of CMDKEY running under SYSTEM with the appropriate arguments of /add: /user: and /pass:

No need to install anything.

OwnerDisplayName: Ben Griswold

Body:
I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.

I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively."  Here's a sample command:

AT 12:00 /interactive cmd.exe

Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe.

C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact
C:\sc start RunCMDAsLSA

In this case the service fails to start and results it the following error message:

FAILED 1053: The service did not respond to the start or control request in a timely fashion.

The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.

I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.

Thus far, each of my attempts have ended in failure. Any suggestions?


问:
jenkins pipeline nodeJs
My JenkinsFile script started throwing npm not found error. (it is working for maven but failing at npm)

```<code>    pipeline {
    environment {
    JENKINS='true'
     }
       agent any
       stages{
    stage('change permissions') {
    steps {
        sh "chmod 777 ./mvnw "
    }
}

    stage('clean') {
    steps {
        sh './mvnw clean install'
    }
    }

    stage('yarn install') {
    steps{
        sh 'npm install -g yarn'
        sh 'yarn install'
    }
    }
    stage('yarn webpack:build') {
    steps {
        sh 'yarn webpack:build'
    }
    }

    stage('backend tests') {
    steps {
        sh './mvnw test'
    }
    }

    stage('frontend tests') {
    steps {
        sh 'yarn test'
    }
    }

    }
}
</code>```

To fix that
I am trying to setup NodeJs on my jenkins node. I installed the nodejs plugin and wrote the script

```<code>pipeline {
agent any

stages {
    stage('Build') {
        steps {
            nodejs(nodeJSInstallationName: 'Node 6.x', configId: '<config-file-provider-id>') {
                sh 'npm config ls'
            }
        }
    }
}
}
</code>```

as shown in the https://wiki.jenkins.io/display/JENKINS/NodeJS+Plugin
I also setup nodejs on global tools config

I also tried the solution in the installing node on jenkins 2.0 using the pipeline plugin

and it throws
Expected to find ‘someKey "someValue"’ @ line 4, column 7.
    node {
error.
but I am still getting npm not found error on jenkins. I am new to jenkins so any help is appreciated.
Thanks in advance

I was able to fix the issues. Followed the following link and was able to fix the issue. https://medium.com/@gustavo.guss/jenkins-starting-with-pipeline-doing-a-node-js-test-72c6057b67d4

答:
Its a puzzle. ;)

Has a little reference trick.

You need to configure your jenkins to see your nodejs config name.

At Global Tool Configuration, you need define your node config name. It has reference to your Jenkinsfile reference.

Look an Jenkingsfile adapted example with reference:

```<code>pipeline {
  agent any

  tools {nodejs "node"}

  stages {
    stage('Cloning Git') {
      steps {
        git 'https://github.com/xxxx'
      }
    }
    stage('Install dependencies') {
      steps {
        sh 'npm i -save express'
      }
    }
    stage('Test') {
      steps {
         sh 'node server.js'
      }
    }
  }
}
</code>```

Complete case to study: Post at Medium by Gustavo Apolinario

Hope it helps!

Title: jenkins pipeline nodeJs

Body:
My JenkinsFile script started throwing npm not found error. (it is working for maven but failing at npm)

    pipeline {
    environment {
    JENKINS='true'
     }
       agent any
       stages{
    stage('change permissions') {
    steps {
        sh "chmod 777 ./mvnw "
    }
}

    stage('clean') {
    steps {
        sh './mvnw clean install'
    }
    }

    stage('yarn install') {
    steps{
        sh 'npm install -g yarn'
        sh 'yarn install'
    }
    }
    stage('yarn webpack:build') {
    steps {
        sh 'yarn webpack:build'
    }
    }

    stage('backend tests') {
    steps {
        sh './mvnw test'
    }
    }

    stage('frontend tests') {
    steps {
        sh 'yarn test'
    }
    }

    }
}

To fix that
I am trying to setup NodeJs on my jenkins node. I installed the nodejs plugin and wrote the script

pipeline {
agent any

stages {
    stage('Build') {
        steps {
            nodejs(nodeJSInstallationName: 'Node 6.x', configId: '<config-file-provider-id>') {
                sh 'npm config ls'
            }
        }
    }
}
}

as shown in the https://wiki.jenkins.io/display/JENKINS/NodeJS+Plugin
I also setup nodejs on global tools config

I also tried the solution in the installing node on jenkins 2.0 using the pipeline plugin

and it throws
Expected to find ‘someKey "someValue"’ @ line 4, column 7.
    node {
error.
but I am still getting npm not found error on jenkins. I am new to jenkins so any help is appreciated.
Thanks in advance

I was able to fix the issues. Followed the following link and was able to fix the issue. https://medium.com/@gustavo.guss/jenkins-starting-with-pipeline-doing-a-node-js-test-72c6057b67d4

Body:
Its a puzzle. ;)

Has a little reference trick.

You need to configure your jenkins to see your nodejs config name.

At Global Tool Configuration, you need define your node config name. It has reference to your Jenkinsfile reference.

Look an Jenkingsfile adapted example with reference:

pipeline {
  agent any

  tools {nodejs "node"}

  stages {
    stage('Cloning Git') {
      steps {
        git 'https://github.com/xxxx'
      }
    }
    stage('Install dependencies') {
      steps {
        sh 'npm i -save express'
      }
    }
    stage('Test') {
      steps {
         sh 'node server.js'
      }
    }
  }
}

Complete case to study: Post at Medium by Gustavo Apolinario

Hope it helps!


问:
ScalaTest can't verify mock function invocations inside Future
I'm trying to use Scala's Future together with ScalaTest and Mockito, but with a very simple test case, I'm not able to verify any of the invocations on a mocked function inside the Future.

```<code>import org.mockito.Mockito.{timeout, verify}
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class FutureTest extends FunSpec with MockitoSugar {
  it("future test") {
    val mockFunction = mock[() => Unit]

    Future {
      mockFunction()
    }

    verify(mockFunction, timeout(1000)).apply()
  }
}
</code>```

This fails everytime with the following error:

```<code>Wanted but not invoked:
function0.apply$mcV$sp();
-> at test.FutureTest.$anonfun$new$1(FutureTest.scala:18)

However, there was exactly 1 interaction with this mock:
function0.apply();
-> at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:658)
</code>```

I have tested that it works without the Future.

Most surprising to me is that if I include a print statement inside the Future block as well, it succeeds every time, as such:

```<code>Future {
  mockFunction()
  println("test")
}
</code>```

Any idea of what the issue is and why print statement matters here?

I'm using:

Scala 2.12.8

scalatest_2.12 3.0.5

mockito 2.27.0

running the tests inside IntelliJ 2019.1.3 with Scala plugin 2019.1.8

答:
try below.

val f: Future = Future {
      mockFunction()
 }

f onComplete {
   verify(mockFunction, timeout(1000)).apply()
}
```

Body:
I'm trying to use Scala's Future together with ScalaTest and Mockito, but with a very simple test case, I'm not able to verify any of the invocations on a mocked function inside the Future.

import org.mockito.Mockito.{timeout, verify}
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class FutureTest extends FunSpec with MockitoSugar {
  it("future test") {
    val mockFunction = mock[() => Unit]

    Future {
      mockFunction()
    }

    verify(mockFunction, timeout(1000)).apply()
  }
}

This fails everytime with the following error:

Wanted but not invoked:
function0.apply$mcV$sp();
-> at test.FutureTest.$anonfun$new$1(FutureTest.scala:18)

However, there was exactly 1 interaction with this mock:
function0.apply();
-> at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:658)

I have tested that it works without the Future.

Most surprising to me is that if I include a print statement inside the Future block as well, it succeeds every time, as such:

Future {
  mockFunction()
  println("test")
}

Any idea of what the issue is and why print statement matters here?

I'm using:

Scala 2.12.8

scalatest_2.12 3.0.5

mockito 2.27.0

running the tests inside IntelliJ 2019.1.3 with Scala plugin 2019.1.8


答:
The fundamental problem here is server. It's apparently a shared resource, but it has just a single callback that is called with responses. That design won't work.

Instead, have server accept the callback for a specific call with the request. Then doing what you're looking for is trivial:

```<code>function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product, cost => showResult(product, cost));
}
</code>```

In today's world, I would use promises rather than a manually-coded callback:

```<code>function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product)
    .then(cost => showResult(product, cost))
    .catch(error => { /* handle/report error */);
}
</code>```

In both cases this requires changing server so it keeps track of which callbacks relate to which requests. That sounds a lot harder than it is (it's actually really easy), but we can't help you with code we can't see (e.g., server's code).

You've said you have a central onResponse set up in the constructor of a websocket connection. IIRC, every message on a websocket has a unique ID (and if not, presumably you can add one). You can then store information about the promise you returned for the request in a Map keyed by that ID:

```<code>this.id = 0; // If you need to assign your own IDs
this.settlersById = new Map();
</code>```

Here's a conceptual requestPrice method in your server class:

```<code>requestPrice(product) {
    const id = ++this.id;
    const promise = new Promise((resolve, reject) => {
        sendRequest({id, product});
        this.settlersById.set(id, {resolve, reject});
    });
}
</code>```

then in onResponse

```<code>onResponse(response) {
    const {id} = response;
    const settlers = this.settlersById.get(id;
    if (settlers) {
        this.settlersById.delete(id);
        if (/* response is a success */) {
            resolve(response.data);
        } else {
            reject(/*...appropriate error...*/);
        }
    }
}
</code>```

Again, this is all conceptual, since we don't have your server class. And it's using its own ID, whereas websockets may provide one for you.

Title: How to call a function when its arguments come from different places

Body:
The fundamental problem here is server. It's apparently a shared resource, but it has just a single callback that is called with responses. That design won't work.

Instead, have server accept the callback for a specific call with the request. Then doing what you're looking for is trivial:

function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product, cost => showResult(product, cost));
}

In today's world, I would use promises rather than a manually-coded callback:

function requestPhoneCost () {
    var product = "iPhone 7";
    server.requestPrice(product)
    .then(cost => showResult(product, cost))
    .catch(error => { /* handle/report error */);
}

In both cases this requires changing server so it keeps track of which callbacks relate to which requests. That sounds a lot harder than it is (it's actually really easy), but we can't help you with code we can't see (e.g., server's code).

You've said you have a central onResponse set up in the constructor of a websocket connection. IIRC, every message on a websocket has a unique ID (and if not, presumably you can add one). You can then store information about the promise you returned for the request in a Map keyed by that ID:

this.id = 0; // If you need to assign your own IDs
this.settlersById = new Map();

Here's a conceptual requestPrice method in your server class:

requestPrice(product) {
    const id = ++this.id;
    const promise = new Promise((resolve, reject) => {
        sendRequest({id, product});
        this.settlersById.set(id, {resolve, reject});
    });
}

then in onResponse

onResponse(response) {
    const {id} = response;
    const settlers = this.settlersById.get(id;
    if (settlers) {
        this.settlersById.delete(id);
        if (/* response is a success */) {
            resolve(response.data);
        } else {
            reject(/*...appropriate error...*/);
        }
    }
}

Again, this is all conceptual, since we don't have your server class. And it's using its own ID, whereas websockets may provide one for you.


问:
Bing Maps - Can't set a custom map style
I'm trying to use a custom style on my map, but no matter what I do, I can't them them working.  My initialize function is:

```<code>this.init = (mapSelector, api, title = '', poi = false, prefix = '', cache = true) => {
      return new Promise((r, j) => {
        if (api.slice(-1) !== '/')
          this.setPrefix(prefix);

        this.setCache(cache);
        this.setPOI(poi);
        this.setTitle(title);

        try {
          getMapKey().then(key => {
            if(mapSelector) {
              _map = new Microsoft.Maps.Map(mapSelector, {
                credentials: key,
                center: new Microsoft.Maps.Location(_latitude, _longitude),
                zoom: 13,
                disableBirdseye: true,
                disableStreetside: true,
                showDashboard: false,
                customMapStyle: JSON.parse(sampleStyle),
              });
            } else {
              j('error');
            }
          });
        } catch (error) {
          console.log(error);
        }
      });
    };
</code>```

It currently renders the standard map just fine.  but no matter what I pass into customMapStyle nothing works, JSON.parse was added to make sure the data was in JSON format, because I'm running out of ideas..  I've copied the JSON from the examples on:

https://bingmapsv8samples.azurewebsites.net/#Set%20Custom%20Map%20Style

Some of the styles I've tried to use are:

```<code>const darkMode = {
  "version": "1.0",
  "settings": {
    "landColor": "#0B334D"
  },
  "elements": {
    "mapElement": {
      "labelColor": "#FFFFFF",
      "labelOutlineColor": "#000000"
    },
    "political": {
      "borderStrokeColor": "#144B53",
      "borderOutlineColor": "#00000000"
    },
    "point": {
      "iconColor": "#0C4152",
      "fillColor": "#000000",
      "strokeColor": "#0C4152"
    },
    "transportation": {
      "strokeColor": "#000000",
      "fillColor": "#000000"
    },
    "highway": {
      "strokeColor": "#158399",
      "fillColor": "#000000"
    },
    "controlledAccessHighway": {
      "strokeColor": "#158399",
      "fillColor": "#000000"
    },
    "arterialRoad": {
      "strokeColor": "#157399",
      "fillColor": "#000000"
    },
    "majorRoad": {
      "strokeColor": "#157399",
      "fillColor": "#000000"
    },
    "railway": {
      "strokeColor": "#146474",
      "fillColor": "#000000"
    },
    "structure": {
      "fillColor": "#115166"
    },
    "water": {
      "fillColor": "#021019"
    },
    "area": {
      "fillColor": "#115166"
    }
  }
};

const sampleStyle = {
  "elements": {
    "park": { "fillColor": "#A9A9D4BE" },
    "controlledAccessHighway": { "fillColor": "#e6c317", "strokeColor": "#D3B300", "labelColor": "#444444", "labelOutlineColor": "#60ffffff" },
    "highway": { "fillColor": "#e6c317", "strokeColor": "#D3B300", "labelColor": "#444444", "labelOutlineColor": "#60ffffff" },
    "water": { "fillColor": "#B7CDDE" },
    "medicalBuilding": { "fillColor": "#fceced" },
    "majorRoad": { "fillColor": "#f0d85a" },
    "education": { "fillColor": "#f0e8f8" },
    "arterialRoad": { "fillColor": "#ffed91" },
    "structure": { "fillColor": "#faf8ed" },
    "buildinglobal": { "fillColor": "#e5e0d8" },
    "forest": { "fillColor": "#deebdd" },
    "vegetation": { "fillColor": "#deebdd" },
    "reserve": { "fillColor": "#deebdd" },
    "street": { "fillColor": "#ffffff", "strokeColor": "#e6e3df" },
    "roadShield": { "fillColor": "#ffffff" },
    "medical": { "fillColor": "#ffddee" },
    "educationBuildinglobal": { "fillColor": "#f6f0f1" },
    "golfCourse": { "fillColor": "#c5dabb" }
  },
  "settings": { "landColor": "#F6F4E3" }
};
</code>```

Does anyone know how to get a custom style activated?  If that's not possible, is there a dark mode that I can activate, which is what I'm trying to do.

Thanks

答:
I would suggest taking a look at the map style sheet editor app - it will allow you to interactively adjust the style and shows sample code for how to initialize that style in all of the Bing maps controls (HTML, UWP and Static maps).
https://www.microsoft.com/en-us/p/map-style-sheet-editor/9nbhtcjt72ft</p>

Body:
I'm trying to use a custom style on my map, but no matter what I do, I can't them them working.  My initialize function is:

this.init = (mapSelector, api, title = '', poi = false, prefix = '', cache = true) => {
      return new Promise((r, j) => {
        if (api.slice(-1) !== '/')
          this.setPrefix(prefix);

        this.setCache(cache);
        this.setPOI(poi);
        this.setTitle(title);

        try {
          getMapKey().then(key => {
            if(mapSelector) {
              _map = new Microsoft.Maps.Map(mapSelector, {
                credentials: key,
                center: new Microsoft.Maps.Location(_latitude, _longitude),
                zoom: 13,
                disableBirdseye: true,
                disableStreetside: true,
                showDashboard: false,
                customMapStyle: JSON.parse(sampleStyle),
              });
            } else {
              j('error');
            }
          });
        } catch (error) {
          console.log(error);
        }
      });
    };

It currently renders the standard map just fine.  but no matter what I pass into customMapStyle nothing works, JSON.parse was added to make sure the data was in JSON format, because I'm running out of ideas..  I've copied the JSON from the examples on:

https://bingmapsv8samples.azurewebsites.net/#Set%20Custom%20Map%20Style

Some of the styles I've tried to use are:

const darkMode = {
  "version": "1.0",
  "settings": {
    "landColor": "#0B334D"
  },
  "elements": {
    "mapElement": {
      "labelColor": "#FFFFFF",
      "labelOutlineColor": "#000000"
    },
    "political": {
      "borderStrokeColor": "#144B53",
      "borderOutlineColor": "#00000000"
    },
    "point": {
      "iconColor": "#0C4152",
      "fillColor": "#000000",
      "strokeColor": "#0C4152"
    },
    "transportation": {
      "strokeColor": "#000000",
      "fillColor": "#000000"
    },
    "highway": {
      "strokeColor": "#158399",
      "fillColor": "#000000"
    },
    "controlledAccessHighway": {
      "strokeColor": "#158399",
      "fillColor": "#000000"
    },
    "arterialRoad": {
      "strokeColor": "#157399",
      "fillColor": "#000000"
    },
    "majorRoad": {
      "strokeColor": "#157399",
      "fillColor": "#000000"
    },
    "railway": {
      "strokeColor": "#146474",
      "fillColor": "#000000"
    },
    "structure": {
      "fillColor": "#115166"
    },
    "water": {
      "fillColor": "#021019"
    },
    "area": {
      "fillColor": "#115166"
    }
  }
};

const sampleStyle = {
  "elements": {
    "park": { "fillColor": "#A9A9D4BE" },
    "controlledAccessHighway": { "fillColor": "#e6c317", "strokeColor": "#D3B300", "labelColor": "#444444", "labelOutlineColor": "#60ffffff" },
    "highway": { "fillColor": "#e6c317", "strokeColor": "#D3B300", "labelColor": "#444444", "labelOutlineColor": "#60ffffff" },
    "water": { "fillColor": "#B7CDDE" },
    "medicalBuilding": { "fillColor": "#fceced" },
    "majorRoad": { "fillColor": "#f0d85a" },
    "education": { "fillColor": "#f0e8f8" },
    "arterialRoad": { "fillColor": "#ffed91" },
    "structure": { "fillColor": "#faf8ed" },
    "buildinglobal": { "fillColor": "#e5e0d8" },
    "forest": { "fillColor": "#deebdd" },
    "vegetation": { "fillColor": "#deebdd" },
    "reserve": { "fillColor": "#deebdd" },
    "street": { "fillColor": "#ffffff", "strokeColor": "#e6e3df" },
    "roadShield": { "fillColor": "#ffffff" },
    "medical": { "fillColor": "#ffddee" },
    "educationBuildinglobal": { "fillColor": "#f6f0f1" },
    "golfCourse": { "fillColor": "#c5dabb" }
  },
  "settings": { "landColor": "#F6F4E3" }
};

Does anyone know how to get a custom style activated?  If that's not possible, is there a dark mode that I can activate, which is what I'm trying to do.

Thanks


问:
How Can I Get MinTTY (Cygwin Terminal) to Open Emacs in a New Window?
I can't figure out why this isn't easy to find on Google, but after searching for about 10 minutes, I just decided to give up and post here.

The subject basically says it all. I'm running MinTTY as a cygwin terminal on a Windows XP desktop. All I want to do is have emacs open up in a new window rather than inside my terminal. What would be best is a switch for this, so I could toggle it depending on my current needs. This seems like something that would be useful to a lot of people, and I know I've done it before on Linux boxes, so I imagine there must be a way to do this in cygwin too. Anyone know how?

答:
There are a couple of scenarios that you might clarify:

Running the cygwin version of emacs within a standard windows environment will call emacs within the current shell

If the Cygwin X-Windows server (i.e., “XWin Server”) has been started and the DISPLAY environment variable has been set in the mintty terminal (e.g., export DISPLAY=":0"), calling emacs will start it in its own window.

running the Windows version of emacs within the cygwin terminal should launch the new frame you are seeking.

If you want a separate emacs 'window', you would be best served by installing the Windows native version of emacs (I use the gnu emacs precompiled binaries), and calling it from the cygwin terminal.


问:
How to do a multi-table join in Django with aliases
Ok, i'm having some trouble understanding on Django does joining and aliasing.  I have four tables defined as such in my models: (i've removed un-pertinent columns)

```<code>class Field(models.Model):
    name = models.CharField(max_length=200, default='')

class Survey(models.Model):
    name = models.CharField(max_length=200, default='')

class Question(models.Model):
    text = models.CharField(max_length=200, default='')
    survey = models.ForeignKey(Survey)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    field = models.ForeignKey(Field)
</code>```

Now I can write a very simple and easy to understand sql query to get exactly what I want. which would look like this:

```<code>SELECT s.id, s.name,
  q.id as q_id, q.text,
  f.id as f_id, f.name as answer
FROM "App_survey" s
JOIN "App_question" q
  ON q.survey_id = s.id
JOIN "App_answer" a
  ON a.question_id = q.id
JOIN "App_field" f
  ON a.field_id = f.id;
</code>```

But I can't for the life of me figure out how to do this using the orm.  I can't even get two tables joined and select the data from both let alone deal with the aliasing.  This is as far as I've gotten:

```<code>questions = Question.objects.prefetch_related('survey')
questions_dict = [{'form':x.name, 'id':x.id, 'question':x.text} for x in questions]
</code>```

This gives me a 'Question' object has no attribute 'name' error.

Note: this is postgres and python and I am new to both.

Update:  This is the final code which i used that works:

```<code>answers = Answer.objects.annotate(
    s_id=F('question__survey__id'),
    s_name=F('question__survey__name'),
    q_id=F('question__id'),
    text=F('question__text'),
    f_id=F('field__id'),
    answer=F('field__name')
)

surveys_dict = [{
    'id': x.s_id,
    'name':x.s_name,
    'q_id':x.q_id,
    'text':x.text,
    'f_id':x.f_id,
    'answer':x.answer
} for x in answers]
</code>```

thanks to both answerers, they were enlightening.

答:
The reason this does not work is because you a Question has no name attribute. .prefetch_related will only populated the related models automatically.

What you can do is annotating the Question objects, like:

```<code>from django.db.models import F

Question.objects.annotate(
    answer_text=F('answer__field__name'),
    s_name=F('survey__name')
)</code>```

Now the Questions from this QuerySet will have two extra fields answer_text and s_name with the name of the Field of the related Answer(s), and s_name the name of the Survey.

Body:
Ok, i'm having some trouble understanding on Django does joining and aliasing.  I have four tables defined as such in my models: (i've removed un-pertinent columns)

class Field(models.Model):
    name = models.CharField(max_length=200, default='')

class Survey(models.Model):
    name = models.CharField(max_length=200, default='')

class Question(models.Model):
    text = models.CharField(max_length=200, default='')
    survey = models.ForeignKey(Survey)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    field = models.ForeignKey(Field)

Now I can write a very simple and easy to understand sql query to get exactly what I want. which would look like this:

SELECT s.id, s.name,
  q.id as q_id, q.text,
  f.id as f_id, f.name as answer
FROM "App_survey" s
JOIN "App_question" q
  ON q.survey_id = s.id
JOIN "App_answer" a
  ON a.question_id = q.id
JOIN "App_field" f
  ON a.field_id = f.id;

But I can't for the life of me figure out how to do this using the orm.  I can't even get two tables joined and select the data from both let alone deal with the aliasing.  This is as far as I've gotten:

questions = Question.objects.prefetch_related('survey')
questions_dict = [{'form':x.name, 'id':x.id, 'question':x.text} for x in questions]

This gives me a 'Question' object has no attribute 'name' error.

Note: this is postgres and python and I am new to both.

Update:  This is the final code which i used that works:

answers = Answer.objects.annotate(
    s_id=F('question__survey__id'),
    s_name=F('question__survey__name'),
    q_id=F('question__id'),
    text=F('question__text'),
    f_id=F('field__id'),
    answer=F('field__name')
)

surveys_dict = [{
    'id': x.s_id,
    'name':x.s_name,
    'q_id':x.q_id,
    'text':x.text,
    'f_id':x.f_id,
    'answer':x.answer
} for x in answers]

thanks to both answerers, they were enlightening.

Body:
The reason this does not work is because you a Question has no name attribute. .prefetch_related will only populated the related models automatically.

What you can do is annotating the Question objects, like:

from django.db.models import F

Question.objects.annotate(
    answer_text=F('answer__field__name'),
    s_name=F('survey__name')
)

Now the Questions from this QuerySet will have two extra fields answer_text and s_name with the name of the Field of the related Answer(s), and s_name the name of the Survey.