问:
How to bypass python function definition with decorator?
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

```<code>@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return
</code>```

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

答:
The code below works by conditionally defining a decorated function based on the value of platform.system. If platform.system matches a chosen string, the function will be passed through as-is. But when platform.system doesn't match up, and if no valid definition has been given yet, the function gets replaced by one that raises a NotImplemented error.

I've only tested this code on Linux systems, so be sure to test it yourself before using it on a different platform.

```<code>import platform
from functools import wraps
from typing import Callable, Optional

def implement_for_os(os_name: str):
    """
    Produce a decorator that defines a function only if the
    platform returned by `platform.system` matches the given `os_name`.
    Otherwise, replace the function with one that raises `NotImplementedError`.
    """
    def decorator(previous_definition: Optional[Callable]):
        def _decorator(func: Callable):
            if previous_definition and hasattr(previous_definition, '_implemented_for_os'):
                # This function was already implemented for this platform. Leave it unchanged.
                return previous_definition
            elif platform.system() == os_name:
                # The current function is the correct impementation for this platform.
                # Mark it as such, and return it unchanged.
                func._implemented_for_os = True
                return func
            else:
                # This function has not yet been implemented for the current platform
                @wraps(func)
                def _not_implemented(*args, **kwargs):
                    raise NotImplementedError(
                        f"The function {func.__name__} is not defined"
                        f" for the platform {platform.system()}"
                    )

                return _not_implemented
        return _decorator

    return decorator

implement_linux = implement_for_os('Linux')

implement_windows = implement_for_os('Windows')
</code>```

Note that implement_for_os isn't a decorator itself. Its job is to build decorators when given a string matching the platform you want to the decorator to respond to.

A complete example looks like the following:

```<code>@implement_linux(None)
def some_function():
    print('Linux')

@implement_windows(some_function)
def some_function():
   print('Windows')

implement_other_platform = implement_for_os('OtherPlatform')

@implement_other_platform(some_function)
def some_function():
   print('Other platform')

</code>```

Body:
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

Body:
The code below works by conditionally defining a decorated function based on the value of platform.system. If platform.system matches a chosen string, the function will be passed through as-is. But when platform.system doesn't match up, and if no valid definition has been given yet, the function gets replaced by one that raises a NotImplemented error.

I've only tested this code on Linux systems, so be sure to test it yourself before using it on a different platform.

import platform
from functools import wraps
from typing import Callable, Optional

def implement_for_os(os_name: str):
    """
    Produce a decorator that defines a function only if the
    platform returned by `platform.system` matches the given `os_name`.
    Otherwise, replace the function with one that raises `NotImplementedError`.
    """
    def decorator(previous_definition: Optional[Callable]):
        def _decorator(func: Callable):
            if previous_definition and hasattr(previous_definition, '_implemented_for_os'):
                # This function was already implemented for this platform. Leave it unchanged.
                return previous_definition
            elif platform.system() == os_name:
                # The current function is the correct impementation for this platform.
                # Mark it as such, and return it unchanged.
                func._implemented_for_os = True
                return func
            else:
                # This function has not yet been implemented for the current platform
                @wraps(func)
                def _not_implemented(*args, **kwargs):
                    raise NotImplementedError(
                        f"The function {func.__name__} is not defined"
                        f" for the platform {platform.system()}"
                    )

                return _not_implemented
        return _decorator

    return decorator

implement_linux = implement_for_os('Linux')

implement_windows = implement_for_os('Windows')

Note that implement_for_os isn't a decorator itself. Its job is to build decorators when given a string matching the platform you want to the decorator to respond to.

A complete example looks like the following:

@implement_linux(None)
def some_function():
    print('Linux')

@implement_windows(some_function)
def some_function():
   print('Windows')

implement_other_platform = implement_for_os('OtherPlatform')

@implement_other_platform(some_function)
def some_function():
   print('Other platform')


来源: stackexchange

问:
Why can't I read this registry key in C#
Problem

I cannot read from the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen.

Using Code:

```<code>Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen", "", null);
</code>```

Diagnostics of problem

I get a System.NullReferenceException when executing code like the key does not exits, but I know it exist because I can view it in regedit.

I have tried to take ownership of the key.

I have tried viewing subkeys of parent key (CurrentVersion). The parent scan never even showed the key SystemProtectedUserData key same with the key right under TabletPC.

I am guessing this is some permission problem but I dont know how to fix it.

Any help is appreciated.

答:
You didn't define the valueName thus it returns the default value, which you set to null.

Check the documentation. (More specifically, you defined it to string.Empty which is not a valid name. Maybe LockScreen is the name of the value/registry-variable? - I don't speak android)

ContentLicense: CC BY-SA 4.0

Body:
Problem

I cannot read from the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen.

Using Code:

Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen", "", null);

Diagnostics of problem

I get a System.NullReferenceException when executing code like the key does not exits, but I know it exist because I can view it in regedit.

I have tried to take ownership of the key.

I have tried viewing subkeys of parent key (CurrentVersion). The parent scan never even showed the key SystemProtectedUserData key same with the key right under TabletPC.

I am guessing this is some permission problem but I dont know how to fix it.

Any help is appreciated.


问:
What does this block of JS code mean?

Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

```<code>   (function(window){
              // some codes here
                    })(window);
</code>```

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

答: It's a closure. The code in question is a an anonymous function, which will execute with the "window" parameter (end of your snippet). It won't pollute the global namespace.</p>

Title: What does this block of JS code mean?

Body:
Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

ContentLicense: CC BY-SA 3.0


问:
How to skip the first n batch documents during an aggregate command?
I run this command :

```<code>db.runCommand(

  {
    aggregate:"myColl",
    pipeline:[
      {
        $group:{
          _id:{_id:"$_id"},
          count:{$sum:NumberInt(1)}}
      }
    ],
    cursor:{}
  }

 )
</code>```

it's return me something like:

```<code>{
    "cursor" : {
        "firstBatch" : [
            {
                "_id" : {
                    "_id" : NumberLong(-9223365602644598416)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223363178405875157)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223350896770545240)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223338355283447904)
                },
                "count" : 1.0
            },
            ....
        ],
        "id" : NumberLong(4379399839731469797),
        "ns" : "myDatabase.myColl"
    },
    "ok" : 1.0
}
</code>```

now I would like the instruct to the command the number of batch documents to skip and also the number of batch documents to returns. Is it possible?

答:
You can try this :</p>

```<code>db.runCommand(

    {
        aggregate: "myColl",
        pipeline: [
            {
                $group: {
                    _id: { _id: "$_id" },
                    count: { $sum: NumberInt(1) }
                }
            },
            { $skip: n } // n should be a positive integer, where n documents are skipped
        ],
        cursor: { "batchSize": n } // n should be a number, it denotes the batch size.
    }
)
</code>```

Body:
I run this command :

db.runCommand(

  {
    aggregate:"myColl",
    pipeline:[
      {
        $group:{
          _id:{_id:"$_id"},
          count:{$sum:NumberInt(1)}}
      }
    ],
    cursor:{}
  }

 )

it's return me something like:

{
    "cursor" : {
        "firstBatch" : [
            {
                "_id" : {
                    "_id" : NumberLong(-9223365602644598416)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223363178405875157)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223350896770545240)
                },
                "count" : 1.0
            },
            {
                "_id" : {
                    "_id" : NumberLong(-9223338355283447904)
                },
                "count" : 1.0
            },
            ....
        ],
        "id" : NumberLong(4379399839731469797),
        "ns" : "myDatabase.myColl"
    },
    "ok" : 1.0
}

now I would like the instruct to the command the number of batch documents to skip and also the number of batch documents to returns. Is it possible?

Body:
You can try this :

db.runCommand(

    {
        aggregate: "myColl",
        pipeline: [
            {
                $group: {
                    _id: { _id: "$_id" },
                    count: { $sum: NumberInt(1) }
                }
            },
            { $skip: n } // n should be a positive integer, where n documents are skipped
        ],
        cursor: { "batchSize": n } // n should be a number, it denotes the batch size.
    }
)


问:
Efficient way to broadcast/iterate over dictionary values
I am trying use dictionary values in a calculation such as this:

```<code>mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)
</code>```

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
```

<p>Or if I do,</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)
</code>```

```<code>TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'
</code>```

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)
```

```[16 25 36]
```

<p>Or I can do</p>

<pre class="lang-py prettyprint-override"><code>newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)
</code>```

[16 25 36]
```

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

答:
This should solve it for you.</p>

```<code>for key, value in mydict.items():
    mydict[key] = (value + 3) ** 2
</code>```

Body:
I am trying use dictionary values in a calculation such as this:

mydict = dict(zip(['key1', 'key2', 'key3'],
                  [1, 2, 3]))
print(mydict)

newvals = (mydict.values() + 3) ** 2
print(newvals)

{'key1': 1, 'key2': 2, 'key3': 3}
TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

Or if I do,

import numpy as np
newvals = (np.array(mydict.values()) + 3) ** 2
print(newvals)

TypeError: unsupported operand type(s) for +: 'dict_values' and 'int'

It appears I have to convert the dictionary values to a list first, or iterate with a list comprehension.

newvals = (np.array(list(mydict.values())) + 3) ** 2
print(newvals)

[16 25 36]

Or I can do

newvals = np.array([(val + 3) ** 2 for val in mydict.values()])
print(newvals)

[16 25 36]

Is there an easier or more efficient way to do this?
Or is there an inbuilt method for dictionaries that I can employ so that I don't have to use a list comprehension or for loop?

Thank you.

Body:
This should solve it for you.

for key, value in mydict.items():
    mydict[key] = (value + 3) ** 2


问:
How to pass ARG value to ENTRYPOINT?
Docker 1.9 allows to pass arguments to a dockerfile. See link: https://docs.docker.com/engine/reference/builder/#arg

How can i pass the same arugments within ENTRYPOINT Instruction??

My dockerfile has

ARG $Version=3.1

  ENTRYPOINT /tmp/folder-$Version/sample.sh start

I am getting an error while creating container with above dockerfile.
Please suggest what is the correct way to specify the argument within ENTRYPOINT instruction??

答:
I'm struggling with this for a day, thanks for @Rotareti for mentioning. It needs to be in ENV before it can be used to the ENTRYPOINT.

```<code>ENV variable=$from_ARG_variable
ENTRYPOINT exec your_exec_sh_file $variable
</code>```

Hope this helps.

Title: How to pass ARG value to ENTRYPOINT?

Body:
I'm struggling with this for a day, thanks for @Rotareti for mentioning. It needs to be in ENV before it can be used to the ENTRYPOINT.

ENV variable=$from_ARG_variable
ENTRYPOINT exec your_exec_sh_file $variable

Hope this helps.


问:
Is it better practice to restart threads in an app, or have the server restart the whole application?
I have a python app that tracks busses in my city for certain data using their arrivals api. I have a limited amount of calls I can make and I don't want to overload them anyways, so I am currently running 30 threads to track data on certain bus stops every day. Each thread randomly selects a bus stop, and continually tracks data for busses that arrive to that stop.

The idea is that I want to have at least a day's worth of data on every bus stop eventually, but I think going in order of the bus stops might lead to problems with getting data from the same drivers. My solution is that every time I start a thread, I randomly select a bus stop from the full list of bus stops, and then put it in another list of ones I've already tracked (it keeps randomly selecting until it gets one that hasn't been tracked yet). When the list is the same length as the full list, it clears (meaning there has now been a day's worth of data tracked from every stop) and we repeat the cycle until it gets full again, etc.

tldr here's the part I'm wondering about:  I want to stop my current running threads, and get new threads at 2:00 AM every night. If I want to achieve this, would it be better practice to write something in my app that does this, or to do a cron job or something to just restart the app on the server at 2:00 AM every night?

Here's the code for reference:

if __name__ == "__main__":

    numstops = 30
    stops_to_track = make_stop_list(numstops)

    for stop in stops_to_track:
        _thread.start_new_thread(track_data, (stop,))
        time.sleep(10)

    while True:
        pass
```

答: Actually, nevermind. I did some research and it seems like it would be better just to change the parameters at 2 AM.</p>


问:
How to restrict the creation of instance of class to one in dart?
I have a class Data:

```<code>class Data {
  int a;
  int b;
  Data({this.a, this.b})
}
</code>```

I want to create just one object of this class for the entire app.

And all the other classes should be able to instantiate the Data class but internally it should return same object which should be constant.

Is there any way to apply the above restriction to class in Dart?

答:
There are a couple ways to achieve this. One is with regular old constants:

class Data {
  final int a;
  final int b;

  const Data({this.a, this.b});
}
```

<p>This may look like it doesn't apply the constraits you are looking for, but actually there is a subtle feature of Dart constants called <em>canonical instances</em>. This means that every <code>const</code> value declared in a program with the same values for fields gets turned into a single known value at compile time. This value is then referenced everywhere the constant gets "instantiated" in code:</p>

<pre class="lang-dart prettyprint-override"><code>const a = Data(a: 1, b: 3);
const b = Data(a: 1, b: 3);
const c = Data(a: 2, b: 4);
// Both `a` and `b` here point to the same object in memory.
// `c` is a different object because the values passed as parameters are different.
</code>```

Another way is with a singleton. This basically takes a normal instance and treats it like a static value for the entire class. The simplest way to do it in Dart would be with a non-named factory constructor:

class Data {
  int a;
  int b;

  Data _instance;
  Data._({this.a, this.b});
  factory Data({int a, int b}) {
    _instance ??= new Data._(a: a, b: b);
    return _instance;
  }
}
```

<p>The above code creates what is known as a <em>lazily instantiated</em> singleton, which basically means the instance doesn't get created until it is actually needed. Using a factory method means that you get to specify which instance actually gets returned, which here means we can just return <code>_instance</code> every time. This means that all code that creates a new <code>Data</code> instance is just returned the same value of <code>_instance</code>:</p>

<pre class="lang-dart prettyprint-override"><code>Foo a = Data(a: 1, b: 3);
Foo b = Data(a: 1, b: 3);
Foo c = Data(a: 2, b: 4);
// a, b, and c are all the same instance of Foo
</code>```

(One thing to be wary of in this approach, though, is that _instance is only created on the first time the factory constructor is called, and that's when the values for a and b are taken. This means that from that point on, every time the constructor is called, the parameters for a and b are ignored, such as in the above example where different values are passed for a and b. This is why singletons aren't a good choice for service classes that take parameters.)

There are more advisable ways of doing this, though. One is to use a service locator like the get_it package to create a normal instance and then expose it to the entire package in a decoupled way:

import 'package:get_it/get_it.dart';

void createSingleton() {
  GetIt.instance.registerSingleton(Data(a: 1, b: 3));
}
```

<p>Now you can retrieve that same value calling <code>get</code>:</p>

<pre class="lang-dart prettyprint-override"><code>final data = GetIt.instance.get<Data>();
</code>```

This might seem like it's more work, but it makes your code more flexible by not tying your code to a particular type or implementation. This comes in handy when implementing things like dependency injection and unit testing.

Body:
I have a class Data:

class Data {
  int a;
  int b;
  Data({this.a, this.b})
}

I want to create just one object of this class for the entire app.

And all the other classes should be able to instantiate the Data class but internally it should return same object which should be constant.

Is there any way to apply the above restriction to class in Dart?

Body:
There are a couple ways to achieve this. One is with regular old constants:

class Data {
  final int a;
  final int b;

  const Data({this.a, this.b});
}

This may look like it doesn't apply the constraits you are looking for, but actually there is a subtle feature of Dart constants called canonical instances. This means that every const value declared in a program with the same values for fields gets turned into a single known value at compile time. This value is then referenced everywhere the constant gets "instantiated" in code:

const a = Data(a: 1, b: 3);
const b = Data(a: 1, b: 3);
const c = Data(a: 2, b: 4);
// Both `a` and `b` here point to the same object in memory.
// `c` is a different object because the values passed as parameters are different.

Another way is with a singleton. This basically takes a normal instance and treats it like a static value for the entire class. The simplest way to do it in Dart would be with a non-named factory constructor:

class Data {
  int a;
  int b;

  Data _instance;
  Data._({this.a, this.b});
  factory Data({int a, int b}) {
    _instance ??= new Data._(a: a, b: b);
    return _instance;
  }
}

The above code creates what is known as a lazily instantiated singleton, which basically means the instance doesn't get created until it is actually needed. Using a factory method means that you get to specify which instance actually gets returned, which here means we can just return _instance every time. This means that all code that creates a new Data instance is just returned the same value of _instance:

Foo a = Data(a: 1, b: 3);
Foo b = Data(a: 1, b: 3);
Foo c = Data(a: 2, b: 4);
// a, b, and c are all the same instance of Foo

(One thing to be wary of in this approach, though, is that _instance is only created on the first time the factory constructor is called, and that's when the values for a and b are taken. This means that from that point on, every time the constructor is called, the parameters for a and b are ignored, such as in the above example where different values are passed for a and b. This is why singletons aren't a good choice for service classes that take parameters.)

There are more advisable ways of doing this, though. One is to use a service locator like the get_it package to create a normal instance and then expose it to the entire package in a decoupled way:

import 'package:get_it/get_it.dart';

void createSingleton() {
  GetIt.instance.registerSingleton(Data(a: 1, b: 3));
}

Now you can retrieve that same value calling get:

final data = GetIt.instance.get<Data>();

This might seem like it's more work, but it makes your code more flexible by not tying your code to a particular type or implementation. This comes in handy when implementing things like dependency injection and unit testing.


问:
Lua - Concatinate several arguments passed into a function, until condition is met, then pass string to next function
pvMessage is sent from another function, the message often comes in a few parts almost instantly.  I am looking to store the pvMessages and concatinate the message to the last.  Therefore a master string is created with all parts.

```<code>Example.
pvMessage #1 = thisispart1msg
pvMessage #2 = now part two is being received
pvMessage #3 = Part 3

MasterMessage = thisispart1msgnow part two is being receivedPart 3
</code>```

I have tried several attempts at solving this issue.  The storing of the message outside the function is proving harder then I though, I keep overwriting the previous message.

```<code>    function ProcessClientMessage( pvMessage )
         if StartMessage == "" then
            StartMessage = pvMessage
            pvMessage = ""
         end

         if pvMessage ~= "" then
             if MiddleMessage == "" then
                MiddleMessage = pvMessage
                pvMessage = StartMessage .. MiddleMessage
                pvMessage = ""
             end
          end

         if pvMessage ~= "" then
            if EndMessage == "" then
                EndMessage = pvMessage
                pvMessage = StartMessage .. MiddleMessage .. EndMessage
                pvMessage = ""
             end
         end

         if pvMessage ~= "" then
            ProcessClientMessageReset()
         end
    end
</code>```

答:
You can make use of the "or" assignment to simplify initialization of the global variable and then concatenate the string to the result. Consider:

```<code>function ProcessClientMessage(msg)
    msg_global_ = (msg_global_ or "")..msg
    print(msg_global_) -- Just for debug purposes so we can print each step
end

do
    ProcessClientMessage("thisispart1msg")
    ProcessClientMessage("now part two is being received")
    ProcessClientMessage("Part 3")
end
</code>```

The variable msg_global_ contains the string being built. If it has not been added too yet, then it will be nil. In this case the or "" will be executed and default the string empty.

We then simply append the string msg.

The output looks like:

```<code>thisispart1msg
thisispart1msgnow part two is being received
thisispart1msgnow part two is being receivedPart 3
</code>```

When you actually process the message, just set the global variable to nil and you are good to go again.

Body:
pvMessage is sent from another function, the message often comes in a few parts almost instantly.  I am looking to store the pvMessages and concatinate the message to the last.  Therefore a master string is created with all parts.

Example.
pvMessage #1 = thisispart1msg
pvMessage #2 = now part two is being received
pvMessage #3 = Part 3

MasterMessage = thisispart1msgnow part two is being receivedPart 3

I have tried several attempts at solving this issue.  The storing of the message outside the function is proving harder then I though, I keep overwriting the previous message.

    function ProcessClientMessage( pvMessage )
         if StartMessage == "" then
            StartMessage = pvMessage
            pvMessage = ""
         end

         if pvMessage ~= "" then
             if MiddleMessage == "" then
                MiddleMessage = pvMessage
                pvMessage = StartMessage .. MiddleMessage
                pvMessage = ""
             end
          end

         if pvMessage ~= "" then
            if EndMessage == "" then
                EndMessage = pvMessage
                pvMessage = StartMessage .. MiddleMessage .. EndMessage
                pvMessage = ""
             end
         end

         if pvMessage ~= "" then
            ProcessClientMessageReset()
         end
    end

Body:
You can make use of the "or" assignment to simplify initialization of the global variable and then concatenate the string to the result. Consider:

function ProcessClientMessage(msg)
    msg_global_ = (msg_global_ or "")..msg
    print(msg_global_) -- Just for debug purposes so we can print each step
end

do
    ProcessClientMessage("thisispart1msg")
    ProcessClientMessage("now part two is being received")
    ProcessClientMessage("Part 3")
end

The variable msg_global_ contains the string being built. If it has not been added too yet, then it will be nil. In this case the or "" will be executed and default the string empty.

We then simply append the string msg.

The output looks like:

thisispart1msg
thisispart1msgnow part two is being received
thisispart1msgnow part two is being receivedPart 3

When you actually process the message, just set the global variable to nil and you are good to go again.


问:
How to interpret Tortoise Git Revision Graph?
I have a very small development effort as shown in the attached revision graph.  At the top (end) of the graph are three branches (master FrontDist, and DRV8871), but they are all in the same block.

I have used the 'browse references' utility to compare 'master' with each of the other branches, and TG tells me there were no differences found.  I know in the past I have merged development branches back into 'master', but I've never subsequently looked at the revision graph.  Is this depiction trying to tell me that both 'FrontDist' and 'DRV8871' have already been merged back into 'master' but I currently have the 'FrontDist' branch checked out?

TIA,

Frank

答:
Never mind - answered my own question.  I created a new branch from 'master', made some trivial comment changes, and then committed the new branch.  Now the revision graph shows all three of the previous branches (DRV8871, FrontDist, and master) all in the same green block, with 'FindParallel' (the new branch) in red at the top.

Frank


问:
Loading context from within a Jar
I need some clarification; I have a jar that I built and inside of the jar it has a custom application-context.xml file that I need to load. I load the file within a class inside of the jar. When I am setting the url of this application-context.xml, is the directory specific to my jar's classpath, or still the project that is using the jar-'s classpath?

For example --

Jar's classpath:

```<code>src > main > META-INF > application-custom-context.xml
</code>```

Project's classpath:

```<code>src > Libraries > myjar.jar > src > main > META-INF > application-custom-context.xml
</code>```

I know these url's aren't accurate :P -- But, inside of my context creation, which directory structure would I follow. This is all theoretical. Somebody asked me this today, and I have no clue how to answer it. I would think that if you call a class from a jar, the classpath should be relative to the contents of that jar.. But, what I think is far from always right :)

答:
The "path" to the Spring context is relative to the classpath.  If the jar is included in your classpath (it's in web-inf/lib for example), then it would be treated just as if it was in your project (web-inf/classes).

In other words, if your context file is in "META-INF\spring\context.xml" inside your jar file, anyone who includes your jar file can reference it in the same manner.

Title: Loading context from within a Jar

Body:
I need some clarification; I have a jar that I built and inside of the jar it has a custom application-context.xml file that I need to load. I load the file within a class inside of the jar. When I am setting the url of this application-context.xml, is the directory specific to my jar's classpath, or still the project that is using the jar-'s classpath?

For example --

Jar's classpath:

src > main > META-INF > application-custom-context.xml

Project's classpath:

src > Libraries > myjar.jar > src > main > META-INF > application-custom-context.xml

I know these url's aren't accurate :P -- But, inside of my context creation, which directory structure would I follow. This is all theoretical. Somebody asked me this today, and I have no clue how to answer it. I would think that if you call a class from a jar, the classpath should be relative to the contents of that jar.. But, what I think is far from always right :)


问:
How can I trigger an action when a swiftUI toggle() is toggled?
In my SwiftUI view I have to trigger an action when a Toggle() changes its state. The toggle itself only takes a Binding.
I therefore tried to trigger the action in the didSet of the @State variable. But the didSet never gets called.

Is there any (other) way to trigger an action? Or any way to observe the value change of a @State variable?

My code looks like this:

struct PWSDetailView : View {

    @ObjectBinding var station: PWS
    @State var isDisplayed: Bool = false {
        didSet {
            if isDisplayed != station.isDisplayed {
                PWSStore.shared.toggleIsDisplayed(station)
            }
        }
    }

    var body: some View {
            VStack {
                ZStack(alignment: .leading) {
                    Rectangle()
                        .frame(width: UIScreen.main.bounds.width, height: 50)
                        .foregroundColor(Color.lokalZeroBlue)
                    Text(station.displayName)
                        .font(.title)
                        .foregroundColor(Color.white)
                        .padding(.leading)
                }

                MapView(latitude: station.latitude, longitude: station.longitude, span: 0.05)
                    .frame(height: UIScreen.main.bounds.height / 3)
                    .padding(.top, -8)

                Form {
                    Toggle(isOn: $isDisplayed)
                    { Text("Wetterstation anzeigen") }
                }

                Spacer()
            }.colorScheme(.dark)
    }
}
```

The desired behaviour would be that the action "PWSStore.shared.toggleIsDisplayed(station)" is triggered when the Toggle() changes its state.

答:
I found a simpler solution, just use onTapGesture:D</p>

```<code>Toggle(isOn: $stateChange) {
  Text("...")
}
.onTapGesture {
  // Any actions here.
}
</code>```

Body:
In my SwiftUI view I have to trigger an action when a Toggle() changes its state. The toggle itself only takes a Binding.
I therefore tried to trigger the action in the didSet of the @State variable. But the didSet never gets called.

Is there any (other) way to trigger an action? Or any way to observe the value change of a @State variable?

My code looks like this:

struct PWSDetailView : View {

    @ObjectBinding var station: PWS
    @State var isDisplayed: Bool = false {
        didSet {
            if isDisplayed != station.isDisplayed {
                PWSStore.shared.toggleIsDisplayed(station)
            }
        }
    }

    var body: some View {
            VStack {
                ZStack(alignment: .leading) {
                    Rectangle()
                        .frame(width: UIScreen.main.bounds.width, height: 50)
                        .foregroundColor(Color.lokalZeroBlue)
                    Text(station.displayName)
                        .font(.title)
                        .foregroundColor(Color.white)
                        .padding(.leading)
                }

                MapView(latitude: station.latitude, longitude: station.longitude, span: 0.05)
                    .frame(height: UIScreen.main.bounds.height / 3)
                    .padding(.top, -8)

                Form {
                    Toggle(isOn: $isDisplayed)
                    { Text("Wetterstation anzeigen") }
                }

                Spacer()
            }.colorScheme(.dark)
    }
}

The desired behaviour would be that the action "PWSStore.shared.toggleIsDisplayed(station)" is triggered when the Toggle() changes its state.

Body:
I found a simpler solution, just use onTapGesture:D

Toggle(isOn: $stateChange) {
  Text("...")
}
.onTapGesture {
  // Any actions here.
}


问:
How to join variable-length parameters as a string
I want to pass variable-length parameters in the function, concatenate these parameters with commas, and finally return the form of the string with parentheses. If the parameter type is a string or char *, then automatically With single quotes, how does this work? Thank you!
For example: join (1, 2, "hello", 3, "world") returns the string "(1, 2, \"hello\", 3, \"world\")"</p>

答:
You could create some function templates to do the job.

```<code>#include <iostream>
#include <sstream>
#include <type_traits>

// a function that takes a variable amount of arguments
template<typename T, class... Args >
std::string join_helper(const T& t, Args...args) {
    std::ostringstream ss;
    using type = std::remove_cv_t<std::remove_reference_t<T>>;

    // check if " should be added
    if constexpr(std::is_same_v<type, const char*> ||
                 std::is_same_v<type, std::string> ||
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    ss << t; // stream out the current value

    if constexpr(std::is_same_v<type, const char*> ||
                 std::is_same_v<type, std::string> ||
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    // do we have more arguments? if so, add ", " and call join_helper again
    if constexpr (sizeof...(args) > 0) {
        ss << ", ";
        ss << join_helper(args...);
    }
    return ss.str();
}

// the function you will use that adds ( and ) around the return value from join_helper
template<class... Args>
std::string join(Args...args) {
    if constexpr(sizeof...(args) > 0)
        return '(' + join_helper(args...) + ')';
    else
        return "()";
}

int main() {
    std::cout
        << join(1, 2.3, "hello", 4, std::string("world")) << '\n'
        << join() << '\n'
    ;
}
</code>```

Output:

```<code>(1, 2.3, "hello", 4, "world")
()
</code>```

Body:
You could create some function templates to do the job.

#include <iostream>
#include <sstream>
#include <type_traits>

// a function that takes a variable amount of arguments
template<typename T, class... Args >
std::string join_helper(const T& t, Args...args) {
    std::ostringstream ss;
    using type = std::remove_cv_t<std::remove_reference_t<T>>;

    // check if " should be added
    if constexpr(std::is_same_v<type, const char*> ||
                 std::is_same_v<type, std::string> ||
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    ss << t; // stream out the current value

    if constexpr(std::is_same_v<type, const char*> ||
                 std::is_same_v<type, std::string> ||
                 std::is_same_v<type, std::string_view>)
    {
        ss << '"';
    }

    // do we have more arguments? if so, add ", " and call join_helper again
    if constexpr (sizeof...(args) > 0) {
        ss << ", ";
        ss << join_helper(args...);
    }
    return ss.str();
}

// the function you will use that adds ( and ) around the return value from join_helper
template<class... Args>
std::string join(Args...args) {
    if constexpr(sizeof...(args) > 0)
        return '(' + join_helper(args...) + ')';
    else
        return "()";
}

int main() {
    std::cout
        << join(1, 2.3, "hello", 4, std::string("world")) << '\n'
        << join() << '\n'
    ;
}

Output:

(1, 2.3, "hello", 4, "world")
()


问:
UnassignedReferenceException in camera

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLock : MonoBehaviour
{

    public float mouseSensetivity = 100f;

    public Transform playerBody;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensetivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensetivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }
}
```

I really don't see any problem and you can see the code it's only on one object and it's the camera i got it from a tutorial.

the console

答: Did you drag your playerBody transform from the hierarchy into the playerBody variable slot in your MouseLock component?</p>

Title: UnassignedReferenceException in camera

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLock : MonoBehaviour
{

    public float mouseSensetivity = 100f;

    public Transform playerBody;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensetivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensetivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }
}

I really don't see any problem and you can see the code it's only on one object and it's the camera i got it from a tutorial.

the console


问:
How to center my asp.NET panels?
I've got panels containing tables to organize textboxes/labels, and I'd like to center them, but I can't figure out what attribute to use. I've tried to justify them in the design view, and horizontalalign:center in html, but to no avail. What's the best way to center panels containing tables?</p>

答: You can generally center a table by using margin: auto;.

Title: How to center my asp.NET panels?


问:
Improve Efficiency of Pandas URL Data Extraction
Right now I've got a process to extract a large amount of data (~1.5m rows) from multiple URLs. The current process works flawlessly but it is extremely slow (~4 mins) and inefficient so I was looking for help.

The way I'm extracting the data is by having a list of dates in a list and plugging them into a URL template to extract. The following is an example, actual list contains 52 elements.

```<code>list =  ['121229','121222','121215','121208','121201','121124','121117','121110']
</code>```

the current code is as follows:

```<code>def dataPull(year):

    columnsName = ['C/A','UNIT','SCP','DATE1','TIME1','DESC1','ENTRIES1','EXITS1','DATE2','TIME2','ESC2',\
                     'ENTRIES2','EXITS2','DATE3','TIME3','DESC3','ENTRIES3','EXITS3','DATE4','TIME4','DESC4',\
                     'ENTRIES4','EXITS4','DATE5','TIME5','DESC5','ENTRIES5','EXITS5','DATE6','TIME6','DESC6',\
                     'ENTRIES6','EXITS6','DATE7','TIME7','DESC7','ENTRIES7','EXITS7','DATE8','TIME8','DESC8',\
                     'ENTRIES8','EXITS8']

    df = pd.DataFrame(columns=columnsName)

    for i in dateList:
        if str(year)[2:5] == str(i)[:2]:
            tempUrl ='http://web.mta.info/developers/data/nyct/turnstile/turnstile_'+str(i)+'.txt'
            tempDf = pd.read_csv(tempUrl, header=None, engine = 'python', error_bad_lines=False, warn_bad_lines=False)
            tempDf.columns = columnsName
            df= pd.concat([df, tempDf])

    return df
</code>```

output looks as such:

```<code>     C/A        UNIT    SCP     DATE1   TIME1   DESC1   ENTRIES1    EXITS1  DATE2   TIME2   ESC2    ENTRIES2    EXITS2  DATE3   TIME3   DESC3   ENTRIES3    EXITS3  DATE4   TIME4   DESC4   ENTRIES4    EXITS4  DATE5   TIME5   DESC5   ENTRIES5    EXITS5  DATE6   TIME6   DESC6   ENTRIES6    EXITS6  DATE7   TIME7   DESC7   ENTRIES7    EXITS7  DATE8   TIME8   DESC8   ENTRIES8    EXITS8
0   A002    R051    02-00-00    04-20-13    00:00:00    REGULAR 4084276 1405308 04-20-13    04:00:00    REGULAR 4084308.0   1405312.0   04-20-13    08:00:00    REGULAR 4084332.0   1405348.0   04-20-13    12:00:00    REGULAR 4084429.0   1405441.0   04-20-13    16:00:00    REGULAR 4084714.0   1405494.0   04-20-13    20:00:00    REGULAR 4085107.0   1405550.0   04-21-13    00:00:00    REGULAR 4085286.0   1405578.0   04-21-13    04:00:00    REGULAR 4085317.0   1405582.0
1   A002    R051    02-00-00    04-21-13    08:00:00    REGULAR 4085336 1405603 04-21-13    12:00:00    REGULAR 4085421.0   1405673.0   04-21-13    16:00:00    REGULAR 4085543.0   1405725.0   04-21-13    20:00:00    REGULAR 4085543.0   1405781.0   04-22-13    00:00:00    REGULAR 4085669.0   1405820.0   04-22-13    04:00:00    REGULAR 4085684.0   1405825.0   04-22-13    08:00:00    REGULAR 4085715.0   1405929.0   04-22-13    12:00:00    REGULAR 4085878.0   1406175.0
2   A002    R051    02-00-00    04-22-13    16:00:00    REGULAR 4086116 1406242 04-22-13    20:00:00    REGULAR 4086986.0   1406310.0   04-23-13    00:00:00    REGULAR 4087164.0   1406335.0   04-23-13    04:00:00    REGULAR 4087172.0   1406339.0   04-23-13    08:00:00    REGULAR 4087214.0   1406441.0   04-23-13    12:00:00    REGULAR 4087390.0   1406685.0   04-23-13    16:00:00    REGULAR 4087738.0   1406741.0   04-23-13    20:00:00    REGULAR 4088682.0   1406813.0
3   A002    R051    02-00-00    04-24-13    00:00:00    REGULAR 4088879 1406839 04-24-13    04:00:00    REGULAR 4088890.0   1406845.0   04-24-13    08:00:00    REGULAR 4088934.0   1406951.0   04-24-13    12:00:00    REGULAR 4089105.0   1407209.0   04-24-13    16:00:00    REGULAR 4089378.0   1407269.0   04-24-13    20:00:00    REGULAR 4090319.0   1407336.0   04-25-13    00:00:00    REGULAR 4090535.0   1407365.0   04-25-13    04:00:00    REGULAR 4090550.0   1407370.0
4   A002    R051    02-00-00    04-25-13    08:00:00    REGULAR 4090589 1407469 04-25-13    08:57:03    DOOR OPEN   4090629.0   1407591.0   04-25-13    08:58:01    LOGON   4090629.0   1407591.0   04-25-13    09:01:08    LGF-MAN 4090629.0   1407591.0   04-25-13    09:01:53    LOGON   4090629.0   1407591.0   04-25-13    09:02:02    DOOR CLOSE  4090629.0   1407591.0   04-25-13    09:02:04    DOOR OPEN   4090629.0   1407591.0   04-25-13    09:02:31    DOOR CLOSE  4090629.0   1407591.0
5   A002    R051    02-00-00    04-25-13    09:02:32    DOOR OPEN   4090629 1407591 04-25-13    09:07:21    LOGON   4090629.0   1407591.0   04-25-13    09:12:12    LGF-MAN 4090642.0   1407592.0   04-25-13    09:12:20    DOOR CLOSE  4090642.0   1407592.0   04-25-13    12:00:00    REGULAR 4090743.0   1407723.0   04-25-13    16:00:00    REGULAR 4091064.0   1407793.0   04-25-13    20:00:00    REGULAR 4092044.0   1407840.0   04-26-13    00:00:00    REGULAR 4092314.0   1407859.0
6   A002    R051    02-00-00    04-26-13    04:00:00    REGULAR 4092325 1407861 04-26-13    08:00:00    REGULAR 4092363.0   1407958.0   04-26-13    12:00:00    REGULAR 4092541.0   1408225.0   04-26-13    16:00:00    REGULAR 4092837.0   1408285.0   04-26-13    20:00:00    REGULAR 4093823.0   1408341.0   None    None    None    NaN NaN None    None    None    NaN NaN None    None    None    NaN NaN
</code>```

Any help is greatly appreciated!

答:
Don't use string concatenation, because it is slow. Use one of two other approaches:

Use str.join, i.e.

```<code>"".join([str1, str2, str3])
</code>```

In your case,

```<code>"".join(['http://web.mta.info/developers/data/nyct/turnstile/turnstile_', str(i), '.txt'])
</code>```

That should improve your speed pretty significantly.

Look at this post for some context.

Or, what consists of even less instructions, use an f-string, like this:

```<code>f'http://web.mta.info/developers/data/nyct/turnstile/turnstile_{str(i)}.txt'
</code>```

Body:
Right now I've got a process to extract a large amount of data (~1.5m rows) from multiple URLs. The current process works flawlessly but it is extremely slow (~4 mins) and inefficient so I was looking for help.

The way I'm extracting the data is by having a list of dates in a list and plugging them into a URL template to extract. The following is an example, actual list contains 52 elements.

list =  ['121229','121222','121215','121208','121201','121124','121117','121110']

the current code is as follows:

def dataPull(year):

    columnsName = ['C/A','UNIT','SCP','DATE1','TIME1','DESC1','ENTRIES1','EXITS1','DATE2','TIME2','ESC2',\
                     'ENTRIES2','EXITS2','DATE3','TIME3','DESC3','ENTRIES3','EXITS3','DATE4','TIME4','DESC4',\
                     'ENTRIES4','EXITS4','DATE5','TIME5','DESC5','ENTRIES5','EXITS5','DATE6','TIME6','DESC6',\
                     'ENTRIES6','EXITS6','DATE7','TIME7','DESC7','ENTRIES7','EXITS7','DATE8','TIME8','DESC8',\
                     'ENTRIES8','EXITS8']

    df = pd.DataFrame(columns=columnsName)

    for i in dateList:
        if str(year)[2:5] == str(i)[:2]:
            tempUrl ='http://web.mta.info/developers/data/nyct/turnstile/turnstile_'+str(i)+'.txt'
            tempDf = pd.read_csv(tempUrl, header=None, engine = 'python', error_bad_lines=False, warn_bad_lines=False)
            tempDf.columns = columnsName
            df= pd.concat([df, tempDf])

    return df

output looks as such:

     C/A        UNIT    SCP     DATE1   TIME1   DESC1   ENTRIES1    EXITS1  DATE2   TIME2   ESC2    ENTRIES2    EXITS2  DATE3   TIME3   DESC3   ENTRIES3    EXITS3  DATE4   TIME4   DESC4   ENTRIES4    EXITS4  DATE5   TIME5   DESC5   ENTRIES5    EXITS5  DATE6   TIME6   DESC6   ENTRIES6    EXITS6  DATE7   TIME7   DESC7   ENTRIES7    EXITS7  DATE8   TIME8   DESC8   ENTRIES8    EXITS8
0   A002    R051    02-00-00    04-20-13    00:00:00    REGULAR 4084276 1405308 04-20-13    04:00:00    REGULAR 4084308.0   1405312.0   04-20-13    08:00:00    REGULAR 4084332.0   1405348.0   04-20-13    12:00:00    REGULAR 4084429.0   1405441.0   04-20-13    16:00:00    REGULAR 4084714.0   1405494.0   04-20-13    20:00:00    REGULAR 4085107.0   1405550.0   04-21-13    00:00:00    REGULAR 4085286.0   1405578.0   04-21-13    04:00:00    REGULAR 4085317.0   1405582.0
1   A002    R051    02-00-00    04-21-13    08:00:00    REGULAR 4085336 1405603 04-21-13    12:00:00    REGULAR 4085421.0   1405673.0   04-21-13    16:00:00    REGULAR 4085543.0   1405725.0   04-21-13    20:00:00    REGULAR 4085543.0   1405781.0   04-22-13    00:00:00    REGULAR 4085669.0   1405820.0   04-22-13    04:00:00    REGULAR 4085684.0   1405825.0   04-22-13    08:00:00    REGULAR 4085715.0   1405929.0   04-22-13    12:00:00    REGULAR 4085878.0   1406175.0
2   A002    R051    02-00-00    04-22-13    16:00:00    REGULAR 4086116 1406242 04-22-13    20:00:00    REGULAR 4086986.0   1406310.0   04-23-13    00:00:00    REGULAR 4087164.0   1406335.0   04-23-13    04:00:00    REGULAR 4087172.0   1406339.0   04-23-13    08:00:00    REGULAR 4087214.0   1406441.0   04-23-13    12:00:00    REGULAR 4087390.0   1406685.0   04-23-13    16:00:00    REGULAR 4087738.0   1406741.0   04-23-13    20:00:00    REGULAR 4088682.0   1406813.0
3   A002    R051    02-00-00    04-24-13    00:00:00    REGULAR 4088879 1406839 04-24-13    04:00:00    REGULAR 4088890.0   1406845.0   04-24-13    08:00:00    REGULAR 4088934.0   1406951.0   04-24-13    12:00:00    REGULAR 4089105.0   1407209.0   04-24-13    16:00:00    REGULAR 4089378.0   1407269.0   04-24-13    20:00:00    REGULAR 4090319.0   1407336.0   04-25-13    00:00:00    REGULAR 4090535.0   1407365.0   04-25-13    04:00:00    REGULAR 4090550.0   1407370.0
4   A002    R051    02-00-00    04-25-13    08:00:00    REGULAR 4090589 1407469 04-25-13    08:57:03    DOOR OPEN   4090629.0   1407591.0   04-25-13    08:58:01    LOGON   4090629.0   1407591.0   04-25-13    09:01:08    LGF-MAN 4090629.0   1407591.0   04-25-13    09:01:53    LOGON   4090629.0   1407591.0   04-25-13    09:02:02    DOOR CLOSE  4090629.0   1407591.0   04-25-13    09:02:04    DOOR OPEN   4090629.0   1407591.0   04-25-13    09:02:31    DOOR CLOSE  4090629.0   1407591.0
5   A002    R051    02-00-00    04-25-13    09:02:32    DOOR OPEN   4090629 1407591 04-25-13    09:07:21    LOGON   4090629.0   1407591.0   04-25-13    09:12:12    LGF-MAN 4090642.0   1407592.0   04-25-13    09:12:20    DOOR CLOSE  4090642.0   1407592.0   04-25-13    12:00:00    REGULAR 4090743.0   1407723.0   04-25-13    16:00:00    REGULAR 4091064.0   1407793.0   04-25-13    20:00:00    REGULAR 4092044.0   1407840.0   04-26-13    00:00:00    REGULAR 4092314.0   1407859.0
6   A002    R051    02-00-00    04-26-13    04:00:00    REGULAR 4092325 1407861 04-26-13    08:00:00    REGULAR 4092363.0   1407958.0   04-26-13    12:00:00    REGULAR 4092541.0   1408225.0   04-26-13    16:00:00    REGULAR 4092837.0   1408285.0   04-26-13    20:00:00    REGULAR 4093823.0   1408341.0   None    None    None    NaN NaN None    None    None    NaN NaN None    None    None    NaN NaN

Any help is greatly appreciated!

Body:
Don't use string concatenation, because it is slow. Use one of two other approaches:

Use str.join, i.e.

"".join([str1, str2, str3])

In your case,

"".join(['http://web.mta.info/developers/data/nyct/turnstile/turnstile_', str(i), '.txt'])

That should improve your speed pretty significantly.

Look at this post for some context.

Or, what consists of even less instructions, use an f-string, like this:

f'http://web.mta.info/developers/data/nyct/turnstile/turnstile_{str(i)}.txt'


问:
In JS6 web component how to find a slotted element's 3d transform context?
In the new JS6 Web Component, you can use <slot> to include light dom's element into shaodow dom without losing its parent-child relationships in the light dom. If an element is slotted into a wrapper inside shadowRoot like this:

```<code><Custom-Element>
    <shadowRoot>
       <div id="some-inner-wrapper">
           <slot name="some-slot"></slot>
       </div>
    </shadowRoot>

    <span slot="some-slot">Who is my context?</span>
</Custom-Element>
</code>```

And now I'd like to set transform-style: preserve-3d on 's parent, should that property go to <Custom-Element>(its immediate parent), or to
? And why so?

答:
The preserve-3d value shoud be set to the parent element.

In your case I suppose you want to position the slotted  element relative to the
, so you need to apply preserve-3d to the the
.

See the example below:

btn.onclick = () => {
customElements.define( 'custom-element', class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow( {mode: 'open' } )
        .innerHTML = `

             Horizontal <slot name="some-slot"></slot> Rotation

        `
  }
} ), btn.disabled=true
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
    display: inline-block ;
    transition: transform 1s ;
    padding: 20px ;
    border: 1px solid black ;
    background-color: yellow ;
    cursor: pointer ;
}

span:hover {
    transform: rotateX(40deg) ;
}</code>```

<custom-element>
    Vertical Rotation
</custom-element>

  <button id="btn">Upgrade</button>```

Of course if you apply transformation rules to the Custom Element itself it could also work (because it's a parent too).

Code above was inspired by W3schools example.

Body:
In the new JS6 Web Component, you can use <slot> to include light dom's element into shaodow dom without losing its parent-child relationships in the light dom. If an element is slotted into a wrapper inside shadowRoot like this:

<Custom-Element>
    <shadowRoot>

           <slot name="some-slot"></slot>

    </shadowRoot>

    Who is my context?
</Custom-Element>

And now I'd like to set transform-style: preserve-3d on 's parent, should that property go to <Custom-Element>(its immediate parent), or to
? And why so?

Body:
The preserve-3d value shoud be set to the parent element.

In your case I suppose you want to position the slotted <span> element relative to the <div id="inner-wrapper">, so you need to apply preserve-3d to the the <div>.

See the example below:

btn.onclick = () => {
customElements.define( 'custom-element', class extends HTMLElement {
  constructor() {
    super()
    this.attachShadow( {mode: 'open' } )
        .innerHTML = `
          <style>
            #some-inner-wrapper {
              display: inline-block ;
              padding: 10px ;
              background-color: rgb(255,0,0,0.5) ;
              transition: transform 1s ;
              transform-style: preserve-3d ;
            }
            #some-inner-wrapper:hover {
              transform: rotateY(55deg) ;
            }
          </style>
          <div id="some-inner-wrapper">
             Horizontal <slot name="some-slot"></slot> Rotation
          </div>
        `
  }
} ), btn.disabled=true
}

span {
    display: inline-block ;
    transition: transform 1s ;
    padding: 20px ;
    border: 1px solid black ;
    background-color: yellow ;
    cursor: pointer ;
}

span:hover {
    transform: rotateX(40deg) ;
}

<custom-element>
    <span slot="some-slot">Vertical Rotation</span>
</custom-element>

<div>
  <button id="btn">Upgrade</button>

Of course if you apply transformation rules to the Custom Element itself it could also work (because it's a parent too).

Code above was inspired by W3schools example.


问:
How to scale svg background for react.js app?
I have a problem with scaling my background svg image. I would expect it to scale to every browser window size, but right now it doesn't scale vertically no matter what params I set. I already tried removing width and height directly in svg file as stated in Why don't my SVG images scale using the CSS "width" property? and attempted to adjust viewBox and preserveAspectRatio manually, but the image at some point of scaling always ends up with messed up height (for example 1/3 of the full height for mobile devices). Am I doing something wrong with the image or should I simply create another one for different ratios?

My SVG background

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 960 560" enable-background="new 0 0 960 560" xml:space="preserve">
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="162.3691" y1="646.5293" x2="893.0117" y2="646.5293" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_1_)" points="822.948,62.45 1303.946,548.438 674.11,919.56 259.071,124.032 "/>
<polyline fill="none" points="111.374,570.263 560.868,-4.484 -31.051,-20.646 -66.404,551.071 -30.041,569.253 111.374,570.263
    -338.119,1145.007 "/>
<polyline fill="#11102F" points="1398,-193 696,-193 258.103,-46.896 763.579,458.579 1008.067,314.586 "/>
<polyline fill="#410069" points="1035.566,291.588 334.097,701.066 1301.061,943.584 1213.131,524.346 "/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="-247.6929" y1="273.7153" x2="482.9502" y2="273.7153" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_2_)" points="276.948,-32.55 757.946,453.438 128.11,824.56 -286.929,29.032 "/>
</svg>
</code>```

答:
Have you tried adding it as a background image via CSS?

.mainElement {
    width: 100vw;
    height: 100vh;
    background: url("https://pixabay.com/get/57e7d0424a50a914ea9d8578c52f317a123ec3e45659704174267cd495/witch-1751025.svg") no-repeat center center;
    background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mainElement"></div></code>```

You might want to look into this post https://css-tricks.com/perfect-full-page-background-image/

Body:
I have a problem with scaling my background svg image. I would expect it to scale to every browser window size, but right now it doesn't scale vertically no matter what params I set. I already tried removing width and height directly in svg file as stated in Why don't my SVG images scale using the CSS "width" property? and attempted to adjust viewBox and preserveAspectRatio manually, but the image at some point of scaling always ends up with messed up height (for example 1/3 of the full height for mobile devices). Am I doing something wrong with the image or should I simply create another one for different ratios?

My SVG background

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 960 560" enable-background="new 0 0 960 560" xml:space="preserve">
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="162.3691" y1="646.5293" x2="893.0117" y2="646.5293" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_1_)" points="822.948,62.45 1303.946,548.438 674.11,919.56 259.071,124.032 "/>
<polyline fill="none" points="111.374,570.263 560.868,-4.484 -31.051,-20.646 -66.404,551.071 -30.041,569.253 111.374,570.263
    -338.119,1145.007 "/>
<polyline fill="#11102F" points="1398,-193 696,-193 258.103,-46.896 763.579,458.579 1008.067,314.586 "/>
<polyline fill="#410069" points="1035.566,291.588 334.097,701.066 1301.061,943.584 1213.131,524.346 "/>
<linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="-247.6929" y1="273.7153" x2="482.9502" y2="273.7153" gradientTransform="matrix(0.8443 -0.5359 0.5359 0.8443 -42.54 93.5288)">
    <stop  offset="0" style="stop-color:#4C0082"/>
    <stop  offset="0.385" style="stop-color:#4C0382"/>
    <stop  offset="0.6165" style="stop-color:#4D0B81"/>
    <stop  offset="0.8074" style="stop-color:#4F1980"/>
    <stop  offset="0.9753" style="stop-color:#522D7E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
    <stop  offset="1" style="stop-color:#52317E"/>
</linearGradient>
<polyline fill="url(#SVGID_2_)" points="276.948,-32.55 757.946,453.438 128.11,824.56 -286.929,29.032 "/>
</svg>

Body:
Have you tried adding it as a background image via CSS?

.mainElement {
    width: 100vw;
    height: 100vh;
    background: url("https://pixabay.com/get/57e7d0424a50a914ea9d8578c52f317a123ec3e45659704174267cd495/witch-1751025.svg") no-repeat center center;
    background-size: cover;
}

<div class="mainElement"></div>

You might want to look into this post https://css-tricks.com/perfect-full-page-background-image/


问:
Unity 5.1 Animator Controller not transitioning
I have created an Animator Controller (called Player) and assigned it to the Animator field of my humanoid avatar, as well as simple animation states with suitable transitions. Please see the two attached images.

I have attached a script, containing the following code, to my avatar game object, but I wonder what I am missing or doing wrong that the transition from Idle to Walk does not take place, even though I can see that the speed variable increases when I press W.

Could someone please help me understand the problem?

```<code>using UnityEngine;
using System.Collections;

public class CharAnim : MonoBehaviour
{
    private Animator animator;
    float speed;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
      animator.SetFloat( "speed", Input.GetAxis("Vertical") );

      if ( Input.GetKeyDown( KeyCode.W ) && ( speed > 0.5f ) )
      {
          animator.SetTrigger("Walk");
      }
      else
      {
          animator.SetTrigger("Idle");
      }
    }
}
</code>```

x

答:
<pre class="lang-html prettyprint-override"><code>{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
    }
    else
        animator.SetTrigger("Idle");
}{
    if(Input.GetKey(KeyCode.W))
    {
        animator.SetTrigger("Walk");
</code>```

Body:
I have created an Animator Controller (called Player) and assigned it to the Animator field of my humanoid avatar, as well as simple animation states with suitable transitions. Please see the two attached images.

I have attached a script, containing the following code, to my avatar game object, but I wonder what I am missing or doing wrong that the transition from Idle to Walk does not take place, even though I can see that the speed variable increases when I press W.

Could someone please help me understand the problem?

using UnityEngine;
using System.Collections;

public class CharAnim : MonoBehaviour
{
    private Animator animator;
    float speed;

    void Start()
    {
        animator = GetComponent<Animator>();
    }

    void Update()
    {
      animator.SetFloat( "speed", Input.GetAxis("Vertical") );

      if ( Input.GetKeyDown( KeyCode.W ) && ( speed > 0.5f ) )
      {
          animator.SetTrigger("Walk");
      }
      else
      {
          animator.SetTrigger("Idle");
      }
    }
}

x


问:
Postgis disconnecting during some queries
I have two tables one in SRID 4326 (containing MULTIPOLYGON) and the other in SRID 32188 (containing MULTILINESTRING).

I am trying to select all polygons from t1 which are within 100 meters from any lines in t2.

This is the query I am making:

SELECT * FROM table1 AS t1, table2 AS t2
WHERE ST_DWithin(
        ST_Transform(t1.geom, 3857),
        ST_Transform(t2.geom, 3857),
        100);
```

<p>Unfortunately, it doesn't work, and pgAdmin4 doesn't give me a useful error. Instead, it disconnects from the DB as soon as I run the query (so it's not a time out situation):</p>

<p><img src="https://i.stack.imgur.com/bjr4z.png" alt="enter image description here"></p>

<p>I also tried with two tables in the same SRID, but I still have the problem... What am I doing wrong here?</p>

<p><em>EDIT</em>: In order to try an narrow down the problem, I took @JGH suggestion and adapted it to test ST_DWITHIN against a point instead of the multilinestrings of table2, and it works fine.</p>

```SELECT * FROM table1 t1
WHERE EXISTS (
    SELECT FROM table2 t2
    WHERE ST_DWithin(t1.geom, ST_MakePoint(-73.63,45.52)::geography,100)
);
```

However, I tested with table2 containing only one straight line (still a multilinestrings geometry though), and the client crashes. Could it bee related to this: https://gis.stackexchange.com/questions/31923/why-is-the-database-connection-lost-on-every-query ?

答:
Your client is probably timing out.

As it is, you are doing a cross-join between the two tables, so if a polygon from t1 is within 100m of 10 features in t2, it will be returned 10 times. You likely want distinct polygons from t1. to do so, you would select only on t1 and keep the row when the condition applied on t2 is satisfied.

The second issue - which won't trigger any error unfortunately - is that it is wrong to compute distances using 3857. In Québec the length distortion is about 40%, which is huge. You would have to either use a suitable local projection (like MTM or UTM) for both geometries, or, if not possible, to cast to geography to do the distance computation.

And because you do transform both geometries to a new CRS, no spatial index solely on the geometries can be used and the distance computation will take a long, long time, causing your client to time out.

SELECT *
FROM   table1 t1
WHERE  EXISTS (
   SELECT FROM table2 t2
   WHERE  ST_DWithin(t1.geom::geography, ST_Transform(t2.geom, 4326)::geography, 100)
   );
```

<p>Don't forget to create a spatial index on the geography (and/or on the transformed geometry)</p>

```CREATE INDEX t1_geog ON t1 USING gist(geography(t1.geom);
```

<p>or</p>

```CREATE INDEX t1_32188 ON t1 USING gist(st_transform(geom,32188));
```

Body:
I have two tables one in SRID 4326 (containing MULTIPOLYGON) and the other in SRID 32188 (containing MULTILINESTRING).

I am trying to select all polygons from t1 which are within 100 meters from any lines in t2.

This is the query I am making:

SELECT * FROM table1 AS t1, table2 AS t2
WHERE ST_DWithin(
        ST_Transform(t1.geom, 3857),
        ST_Transform(t2.geom, 3857),
        100);

Unfortunately, it doesn't work, and pgAdmin4 doesn't give me a useful error. Instead, it disconnects from the DB as soon as I run the query (so it's not a time out situation):

I also tried with two tables in the same SRID, but I still have the problem... What am I doing wrong here?

EDIT: In order to try an narrow down the problem, I took @JGH suggestion and adapted it to test ST_DWITHIN against a point instead of the multilinestrings of table2, and it works fine.

SELECT * FROM table1 t1
WHERE EXISTS (
    SELECT FROM table2 t2
    WHERE ST_DWithin(t1.geom, ST_MakePoint(-73.63,45.52)::geography,100)
);

However, I tested with table2 containing only one straight line (still a multilinestrings geometry though), and the client crashes. Could it bee related to this: https://gis.stackexchange.com/questions/31923/why-is-the-database-connection-lost-on-every-query ?

Body:
Your client is probably timing out.

As it is, you are doing a cross-join between the two tables, so if a polygon from t1 is within 100m of 10 features in t2, it will be returned 10 times. You likely want distinct polygons from t1. to do so, you would select only on t1 and keep the row when the condition applied on t2 is satisfied.

The second issue - which won't trigger any error unfortunately - is that it is wrong to compute distances using 3857. In Québec the length distortion is about 40%, which is huge. You would have to either use a suitable local projection (like MTM or UTM) for both geometries, or, if not possible, to cast to geography to do the distance computation.

And because you do transform both geometries to a new CRS, no spatial index solely on the geometries can be used and the distance computation will take a long, long time, causing your client to time out.

SELECT *
FROM   table1 t1
WHERE  EXISTS (
   SELECT FROM table2 t2
   WHERE  ST_DWithin(t1.geom::geography, ST_Transform(t2.geom, 4326)::geography, 100)
   );

Don't forget to create a spatial index on the geography (and/or on the transformed geometry)

CREATE INDEX t1_geog ON t1 USING gist(geography(t1.geom);

or

CREATE INDEX t1_32188 ON t1 USING gist(st_transform(geom,32188));


问:
cant plot seaborn graphs side by side
I have done research here in SO and all the answers that i have found do not solve my issue.
I have 4 histograms that i want to plot over 2 rows and 2 columns.

If i just want to plot 2 histograms over 1 row then it works fine but the moment i add more histograms then the whole thing dies!
this is the code:

```<code>`fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
sns.distplot(iot['opex_euro'],ax=ax1)
sns.distplot(iot['cost_of_delay'],ax=ax2)
sns.distplot(iot['customer_commitment_value'],ax=ax3)
sns.distplot(iot['ktlo_value'],ax=ax4)
plt.show()`
</code>```

and this is the error message that i get:

```<code>`ValueError Traceback (most recent call last)
<ipython-input-115-5b6d5d693b20> in <module>()
1 #plotParams()
2
----> 3 fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
4 sns.distplot(iot['opex_euro'],ax=ax1)
5 sns.distplot(iot['cost_of_delay'],ax=ax2)
ValueError: not enough values to unpack (expected 4, got 2)`
</code>```

can i please get steered in the right direction?

答:
Check this out: Here I am first defining how many subplots I want to make using plt.subplots(nrows, ncols). Also I have put sharex=True, which means you will share x axis. If you want to have separate x axis for all 4 subplots then make it sharex=False (default)

Here I used randomly generated data to generate the plot, you can use your own data.

```<code>import seaborn as sns
import matplotlib.pyplot as plt

f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)

sns.despine(left=True)

# Plot a simple distribution of the desired columns
sns.distplot(df['col1'], color="b", ax=axes[0, 0])
sns.distplot(df['col2'], color="m", ax=axes[0, 1])
sns.distplot(df['col3'], color="r", ax=axes[1, 0])
sns.distplot(df['col4'], color="g", ax=axes[1, 1])

plt.setp(axes, yticks=[])
plt.tight_layout()

plt.savefig("sample.png")

</code>```

Title: cant plot seaborn graphs side by side

Body:
I have done research here in SO and all the answers that i have found do not solve my issue.
I have 4 histograms that i want to plot over 2 rows and 2 columns.

If i just want to plot 2 histograms over 1 row then it works fine but the moment i add more histograms then the whole thing dies!
this is the code:

`fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
sns.distplot(iot['opex_euro'],ax=ax1)
sns.distplot(iot['cost_of_delay'],ax=ax2)
sns.distplot(iot['customer_commitment_value'],ax=ax3)
sns.distplot(iot['ktlo_value'],ax=ax4)
plt.show()`

and this is the error message that i get:

`ValueError Traceback (most recent call last)
<ipython-input-115-5b6d5d693b20> in <module>()
1 #plotParams()
2
----> 3 fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)
4 sns.distplot(iot['opex_euro'],ax=ax1)
5 sns.distplot(iot['cost_of_delay'],ax=ax2)
ValueError: not enough values to unpack (expected 4, got 2)`

can i please get steered in the right direction?

Body:
Check this out: Here I am first defining how many subplots I want to make using plt.subplots(nrows, ncols). Also I have put sharex=True, which means you will share x axis. If you want to have separate x axis for all 4 subplots then make it sharex=False (default)

Here I used randomly generated data to generate the plot, you can use your own data.

import seaborn as sns
import matplotlib.pyplot as plt

f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)

sns.despine(left=True)

# Plot a simple distribution of the desired columns
sns.distplot(df['col1'], color="b", ax=axes[0, 0])
sns.distplot(df['col2'], color="m", ax=axes[0, 1])
sns.distplot(df['col3'], color="r", ax=axes[1, 0])
sns.distplot(df['col4'], color="g", ax=axes[1, 1])

plt.setp(axes, yticks=[])
plt.tight_layout()

plt.savefig("sample.png")


问:
What does this block of JS code mean?

Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

```<code>   (function(window){
              // some codes here
                    })(window);
</code>```

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

答:
This is called a immediately-invoked anonymous function. (IIAF for short.)

In this case, you are defining a function that takes in a parameter called "window" that overrides the global window object inside of that scope.

The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window object, so it is as if you used the global reference within the function closure!

Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.

Title: What does this block of JS code mean?

Body:
Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?


问:
Using Scanner class to compute average from a CSV file in Java
I'm trying to read grade data from a .csv file and then compute the average grade. The data in the file looks like:

```<code>Arthur Albert,74%
Melissa Hay,72%
William Jones,85%
Rachel Lee,68%
Joshua Planner,75%
Jennifer Ranger,76%
Richard Rock,80%
Jerry Rose,80%
Dorothy Smith,76%
Jon Smith,60%
Lisa Smith,90%
Michael Stone,13%
Josephine Trenton,75%
Franklin Williams,58%
</code>```

Other posts recommend using a CSV library to do this, but I'm determined to do this via the Scanner class. I'm having issues doing this, so I've first tried to do something simpler, which is just to print the grade total. My idea is this:

```<code>public class GradeAvg {

    public static void main(String[] args) throws FileNotFoundException{

        Scanner scanner = new Scanner (new File("grades.csv"));

        int total = 0;
        int count = 1;

        while(scanner.hasNext()) {
            if(scanner.hasNextInt()) {
                int grade = scanner.nextInt();
                total += grade;
                count++;
            } else {
                scanner.next();
            }
        }
        System.out.println(total);
        scanner.close();
    }

}
</code>```

What I get is 0. I'm guessing that the scanner is not finding any integers, as is. What do I do next?

答:
Try this ::

```<code>        int total = 0;
        int count = 1;

        while(scanner.hasNext()) {
            if(scanner.hasNextLine()){
                String data=scanner.nextLine();
                String numberData=data.substring(data.indexOf(",") +1);
                numberData = numberData.substring(0, numberData.indexOf("%"));
                total=total+Integer.parseInt(numberData);
            }
        }
        System.out.println(total);
        scanner.close();
    }
</code>```

Let me know if it helps. Not a very elegant solution but gets the job done.

Body:
I'm trying to read grade data from a .csv file and then compute the average grade. The data in the file looks like:

Arthur Albert,74%
Melissa Hay,72%
William Jones,85%
Rachel Lee,68%
Joshua Planner,75%
Jennifer Ranger,76%
Richard Rock,80%
Jerry Rose,80%
Dorothy Smith,76%
Jon Smith,60%
Lisa Smith,90%
Michael Stone,13%
Josephine Trenton,75%
Franklin Williams,58%

Other posts recommend using a CSV library to do this, but I'm determined to do this via the Scanner class. I'm having issues doing this, so I've first tried to do something simpler, which is just to print the grade total. My idea is this:

public class GradeAvg {

    public static void main(String[] args) throws FileNotFoundException{

        Scanner scanner = new Scanner (new File("grades.csv"));

        int total = 0;
        int count = 1;

        while(scanner.hasNext()) {
            if(scanner.hasNextInt()) {
                int grade = scanner.nextInt();
                total += grade;
                count++;
            } else {
                scanner.next();
            }
        }
        System.out.println(total);
        scanner.close();
    }

}

What I get is 0. I'm guessing that the scanner is not finding any integers, as is. What do I do next?

Body:
Try this ::

        int total = 0;
        int count = 1;

        while(scanner.hasNext()) {
            if(scanner.hasNextLine()){
                String data=scanner.nextLine();
                String numberData=data.substring(data.indexOf(",") +1);
                numberData = numberData.substring(0, numberData.indexOf("%"));
                total=total+Integer.parseInt(numberData);
            }
        }
        System.out.println(total);
        scanner.close();
    }

Let me know if it helps. Not a very elegant solution but gets the job done.


问:
How to display value prop of react Ace Editor onClick?
I'm looking to display the value prop from the React Ace Editor. Just looking to console.log it for now.

I'm not sure how to access it and display it when the "see code" button is clicked.

Here is the code I'm currently working on at the moment:

```<code>import React, { Component } from "react";
import AceEditor from "react-ace";

import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-github";

function onChange(newValue) {
  console.log("change", newValue);
}

class Code extends Component {
  constructor(props) {
    super(props);
    this.state = { code: `console.log("Hello World")` };
  }

  runCode = () => {
    console.log(this.props.aceEditor.value);
  };

  render() {
    return (
      <>
        <AceEditor
          mode="javascript"
          theme="github"
          fontSize={16}
          value={this.state.code}
          onChange={onChange}
          name="UNIQUE_ID_OF_DIV"
          editorProps={{ $blockScrolling: true }}
        />
        <div>
          <h2>Controls:</h2>
          <button onClick={this.runCode}>see code</button>
        </div>
      </>
    );
  }
}

export default Code;
</code>```

答:
```<code>constructor(props) {
 super(props);
 this.state = { code: `console.log("Hello World")` };
 this.runCode = this.runCode.bind(this);
}
</code>```

You need to bind the runCode function to your class. You can do this in your constructor as shown above.

Body:
I'm looking to display the value prop from the React Ace Editor. Just looking to console.log it for now.

I'm not sure how to access it and display it when the "see code" button is clicked.

Here is the code I'm currently working on at the moment:

import React, { Component } from "react";
import AceEditor from "react-ace";

import "ace-builds/src-noconflict/mode-javascript";
import "ace-builds/src-noconflict/theme-github";

function onChange(newValue) {
  console.log("change", newValue);
}

class Code extends Component {
  constructor(props) {
    super(props);
    this.state = { code: `console.log("Hello World")` };
  }

  runCode = () => {
    console.log(this.props.aceEditor.value);
  };

  render() {
    return (
      <>
        <AceEditor
          mode="javascript"
          theme="github"
          fontSize={16}
          value={this.state.code}
          onChange={onChange}
          name="UNIQUE_ID_OF_DIV"
          editorProps={{ $blockScrolling: true }}
        />

Controls:

          <button onClick={this.runCode}>see code</button>

      </>
    );
  }
}

export default Code;

Body:
constructor(props) {
 super(props);
 this.state = { code: `console.log("Hello World")` };
 this.runCode = this.runCode.bind(this);
}

You need to bind the runCode function to your class. You can do this in your constructor as shown above.


问:
How can I debug tests in Visual Studio Code with a serverless-framework project using the serverless-bundle package?
I have a serverless-framework project that is using the serverless-bundle package so that I can use ES6 imports and exports.

I currently have a failing test. When I click on the "Debug" link in Visual Studio Code, the debug session fails for the following reason on line 1 of my test code: SyntaxError: Cannot use import statement outside a module

The test code I'm working on is located here: https://github.com/groffcole/art-center-service/blob/master/ports/GalleriesHttpPort.test.js

What can I do to fix this issue?

Thanks.

答:
try using const "" = require() and see if that works. if it does, what version of nodejs do you have installed? and did you set it up to use es6 imports? ES^ imports are still experimental as of node 13
https://nodejs.org/api/esm.html#esm_introduction
https://nodejs.org/dist/latest-v13.x/docs/api/modules.html#modules_module_exports</p>

```<code>let func1 = ()=>{
return "Hello"
}
let func2 = ()=>{
return "World"
}
module.exports ={func1:func1,func2:func2}
</code>```

Body:
try using const "" = require() and see if that works. if it does, what version of nodejs do you have installed? and did you set it up to use es6 imports? ES^ imports are still experimental as of node 13
https://nodejs.org/api/esm.html#esm_introduction
https://nodejs.org/dist/latest-v13.x/docs/api/modules.html#modules_module_exports

let func1 = ()=>{
return "Hello"
}
let func2 = ()=>{
return "World"
}
module.exports ={func1:func1,func2:func2}


问:
How can I create a time series line graph in chart.js?
I created a python script that fetches data from an API to get weather temperature at a certain time

The result is a CSV file that looks like this:

```<code>Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2
</code>```

How can transform the CSV into a JavaScript array and make a Chart.js line chart out of it?

Right now, I have a Chart.js base script that looks like this (isn't filled with any data)

```<code>new Chart(document.getElementById("line-chart"), {
type: 'line',
 data: {
   labels: [],
   datasets: [{
       data: [],
       label: "Temperature",
       borderColor: "#3e95cd",
       fill: false
     }
   ]
 },
 options: {
   scales: {
     xAxes: [{
       type: 'time',
       distribution: 'linear',
     }],
   title: {
     display: false,
   }
   }
 }
});

</code>```

答:
Basically, convert every single file-line string:

```<code>2020-02-15 18:37:39,-8.25
</code>```

into an Object:

```<code>{x: "2020-02-15 18:37:39", y: -8.25}
</code>```

to be stored inside the Chart.js data : [] Array.

Here's an example on how to create a function csvToChartData() that returns such an Array (to be used like: ... data: csvToChartData(csv) )

Trim and split a file string by newline \n into a lines array .

Remove titles (the first array key) by using lines.shift();

Convert every line to an object {x: date, y: temperature} by splitting each line by comma .split(',')

Pass that newly mapped Array (by using .map()) as your chart data:

const csv = `Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2`;

const csvToChartData = csv => {
  const lines = csv.trim().split('\n');
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(',');
    return {
      x: date,
      y: temperature
    }
  });
};

const ctx = document.querySelector("#line-chart").getContext('2d');
const config = {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      data: csvToChartData(csv),
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear',
      }],
      title: {
        display: false,
      }
    }
  }
};
new Chart(ctx, config);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#line-chart {
  display: block;
  width: 100%;
}</code>```

<canvas id="line-chart"></canvas>

```
</div>
</div>
</p>

<h1>Fetch data dynamically:</h1>

<p><img src="https://i.stack.imgur.com/UvSzO.gif" alt="enter image description here"></p>

<p>To fetch the data dynamically, say <strong>every 5 seconds</strong>, you could use AJAX and the Fetch API.<br>
Here's the modified JS example given you have a CSV file called <code>temperature.csv</code></p>

<pre class="lang-js prettyprint-override"><code>const config = {
  type: "line",
  data: {
    labels: [],
    datasets: [{
      data: [], // Set initially to empty data
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: "time",
        distribution: "linear"
      }],
      title: {
        display: false
      }
    }
  }
};

const ctx = document.querySelector("#line-chart").getContext("2d");
const temperatureChart = new Chart(ctx, config);

const csvToChartData = csv => {
  const lines = csv.trim().split("\n");
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(",");
    return {
      x: date,
      y: temperature
    };
  });
};

const fetchCSV = () => fetch("temperature.csv")
  .then(data => data.text())
  .then(csv => {
    temperatureChart.data.datasets[0].data = csvToChartData(csv);
    temperatureChart.update();
    setTimeout(fetchCSV, 5000); // Repeat every 5 sec
  });

fetchCSV(); // First fetch!
</code>```

Body:
I created a python script that fetches data from an API to get weather temperature at a certain time

The result is a CSV file that looks like this:

Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2

How can transform the CSV into a JavaScript array and make a Chart.js line chart out of it?

Right now, I have a Chart.js base script that looks like this (isn't filled with any data)

new Chart(document.getElementById("line-chart"), {
type: 'line',
 data: {
   labels: [],
   datasets: [{
       data: [],
       label: "Temperature",
       borderColor: "#3e95cd",
       fill: false
     }
   ]
 },
 options: {
   scales: {
     xAxes: [{
       type: 'time',
       distribution: 'linear',
     }],
   title: {
     display: false,
   }
   }
 }
});

Body:
Basically, convert every single file-line string:

2020-02-15 18:37:39,-8.25

into an Object:

{x: "2020-02-15 18:37:39", y: -8.25}

to be stored inside the Chart.js data : [] Array.

Here's an example on how to create a function csvToChartData() that returns such an Array (to be used like: ... data: csvToChartData(csv) )

Trim and split a file string by newline \n into a lines array .

Remove titles (the first array key) by using lines.shift();

Convert every line to an object {x: date, y: temperature} by splitting each line by comma .split(',')

Pass that newly mapped Array (by using .map()) as your chart data:

const csv = `Time,Temperature
2020-02-15 18:37:39,-8.25
2020-02-15 19:07:39,-8.08
2020-02-15 19:37:39,-8.41
2020-02-15 20:07:39,-8.2`;

const csvToChartData = csv => {
  const lines = csv.trim().split('\n');
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(',');
    return {
      x: date,
      y: temperature
    }
  });
};

const ctx = document.querySelector("#line-chart").getContext('2d');
const config = {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      data: csvToChartData(csv),
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        distribution: 'linear',
      }],
      title: {
        display: false,
      }
    }
  }
};
new Chart(ctx, config);

#line-chart {
  display: block;
  width: 100%;
}

<canvas id="line-chart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

Fetch data dynamically:

To fetch the data dynamically, say every 5 seconds, you could use AJAX and the Fetch API.

Here's the modified JS example given you have a CSV file called temperature.csv

const config = {
  type: "line",
  data: {
    labels: [],
    datasets: [{
      data: [], // Set initially to empty data
      label: "Temperature",
      borderColor: "#3e95cd",
      fill: false
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: "time",
        distribution: "linear"
      }],
      title: {
        display: false
      }
    }
  }
};

const ctx = document.querySelector("#line-chart").getContext("2d");
const temperatureChart = new Chart(ctx, config);

const csvToChartData = csv => {
  const lines = csv.trim().split("\n");
  lines.shift(); // remove titles (first line)
  return lines.map(line => {
    const [date, temperature] = line.split(",");
    return {
      x: date,
      y: temperature
    };
  });
};

const fetchCSV = () => fetch("temperature.csv")
  .then(data => data.text())
  .then(csv => {
    temperatureChart.data.datasets[0].data = csvToChartData(csv);
    temperatureChart.update();
    setTimeout(fetchCSV, 5000); // Repeat every 5 sec
  });

fetchCSV(); // First fetch!