问:
How can I trap CAN bus exceptions such as 'Network down' from within python-can interfaces?
I have a small python project to simulate CAN-enabled electronics that I have built. The project has a shell interpreter to interact with the simulated electronics devices. I'm at a point I'd like to trap exceptions thrown from within python-can running instances and print friendly error messages in the main shell UI instead of getting a full stack trace garbling the display.

For instance, if I run my script while the can0 interface is not configured (i.e. before executing ip link set can0 up type can bitrate 250000) I get a stack trace such as this:

```<code>Failed to send: Timestamp:        0.000000        ID: 0541    000    DLC: 8    01 1a c4 13 00 00 e2 04
> Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/lib/python3.6/site-packages/can/notifier.py", line 39, in rx_thread
    msg = self.bus.recv(self.timeout)
  File "/usr/lib/python3.6/site-packages/can/interfaces/socketcan_native.py", line 341, in recv
    packet = capturePacket(self.socket)
  File "/usr/lib/python3.6/site-packages/can/interfaces/socketcan_native.py", line 274, in capturePacket
    cf, addr = sock.recvfrom(can_frame_size)
OSError: [Errno 100] Network is down
</code>```

Note that the '>' sign above is my mini-shell prompt. That looks ugly, right.

I first tried to derive SocketcanNative_Bus and override the recv() method but then my new class is rejected as there's a check in /usr/lib/python3.6/site-packages/can/interfaces/interface.py that validates an interface class name against a list of well-known modules. So this might be not-quite-the-way-to-go.

Before I try anything else stupid, does python-can provide some means to intercept OS errors that occur in Notifier threads during transmission of data packets or when the CAN interface goes down, for instance?

Note that since I'm using a USB CAN adapter, it's pointless to check the network state only when the script starts because the CAN adapter could as well be unplugged while the script runs. So the only relevant way is to catch exceptions thrown by python-can modules and show a friendly message in the main thread.

答:
I still don't know if that's what python-can developers intended but here's my latest working attempt. I'm overriding the recv() method of a class SocketcanNative_Bus instance, aka bus:

```<code>can.rc['interface'] = 'socketcan_native'
can.rc['channel'] = args[1]

from can.interfaces.socketcan_native import SocketcanNative_Bus
def recv(self, timeout=None):
    try:
        return SocketcanNative_Bus.recv(self, timeout)
    except OSError as e:
        print(str(e))
        return None

try:
    import types
    bus = can.interface.Bus()
    bus.recv = types.MethodType(recv, bus)

except OSError as e:
    print('Error {0}: {1}'.format(e.errno, e.strerror), file=sys.stderr)
</code>```

I dynamically overrode the bus instance's method recv() using Python's types.MethodType(). It's called patching as explained elsewhere on Stackoverflow.

Body:
I have a small python project to simulate CAN-enabled electronics that I have built. The project has a shell interpreter to interact with the simulated electronics devices. I'm at a point I'd like to trap exceptions thrown from within python-can running instances and print friendly error messages in the main shell UI instead of getting a full stack trace garbling the display.

For instance, if I run my script while the can0 interface is not configured (i.e. before executing ip link set can0 up type can bitrate 250000) I get a stack trace such as this:

Failed to send: Timestamp:        0.000000        ID: 0541    000    DLC: 8    01 1a c4 13 00 00 e2 04
> Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/lib/python3.6/site-packages/can/notifier.py", line 39, in rx_thread
    msg = self.bus.recv(self.timeout)
  File "/usr/lib/python3.6/site-packages/can/interfaces/socketcan_native.py", line 341, in recv
    packet = capturePacket(self.socket)
  File "/usr/lib/python3.6/site-packages/can/interfaces/socketcan_native.py", line 274, in capturePacket
    cf, addr = sock.recvfrom(can_frame_size)
OSError: [Errno 100] Network is down

Note that the '>' sign above is my mini-shell prompt. That looks ugly, right.

I first tried to derive SocketcanNative_Bus and override the recv() method but then my new class is rejected as there's a check in /usr/lib/python3.6/site-packages/can/interfaces/interface.py that validates an interface class name against a list of well-known modules. So this might be not-quite-the-way-to-go.

Before I try anything else stupid, does python-can provide some means to intercept OS errors that occur in Notifier threads during transmission of data packets or when the CAN interface goes down, for instance?

Note that since I'm using a USB CAN adapter, it's pointless to check the network state only when the script starts because the CAN adapter could as well be unplugged while the script runs. So the only relevant way is to catch exceptions thrown by python-can modules and show a friendly message in the main thread.

Body:
I still don't know if that's what python-can developers intended but here's my latest working attempt. I'm overriding the recv() method of a class SocketcanNative_Bus instance, aka bus:

can.rc['interface'] = 'socketcan_native'
can.rc['channel'] = args[1]

from can.interfaces.socketcan_native import SocketcanNative_Bus
def recv(self, timeout=None):
    try:
        return SocketcanNative_Bus.recv(self, timeout)
    except OSError as e:
        print(str(e))
        return None

try:
    import types
    bus = can.interface.Bus()
    bus.recv = types.MethodType(recv, bus)

except OSError as e:
    print('Error {0}: {1}'.format(e.errno, e.strerror), file=sys.stderr)

I dynamically overrode the bus instance's method recv() using Python's types.MethodType(). It's called patching as explained elsewhere on Stackoverflow.


来源: stackexchange

问:
Android build error : duplicate entry: okio/AsyncTimeout$1.class
I added a intel webrtc library into my ./libs folder. And added this line in build.gradle

```<code>compile files('./libs/woogeenconference.jar')
</code>```

After that, i start getting

```<code>Execution failed for task ':app:transformClassesWithJarMergingForUserStaging'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okio/AsyncTimeout$1.class
</code>```

How do I deal with this build error? I am using some other android packages as well. I think this is containing the same class.

```<code>compile 'com.squareup.okhttp:okhttp:2.3.0'
</code>```

答:
Try this</p>

```<code>compile files('./libs/woogeenconference.jar') {
    exclude group: 'okhttp', module: 'okhttp'
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I added a intel webrtc library into my ./libs folder. And added this line in build.gradle

compile files('./libs/woogeenconference.jar')

After that, i start getting

Execution failed for task ':app:transformClassesWithJarMergingForUserStaging'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okio/AsyncTimeout$1.class

How do I deal with this build error? I am using some other android packages as well. I think this is containing the same class.

compile 'com.squareup.okhttp:okhttp:2.3.0'

Body:
Try this

compile files('./libs/woogeenconference.jar') {
    exclude group: 'okhttp', module: 'okhttp'
}

ContentLicense: CC BY-SA 3.0


问:
preg_match_all : Assign same name to two subpatterns
I want to use a regex to match two different subpatterns and give them the same name using the PCRE_INFO_JCHANGED modifier (?J)

The two subpatterns are very different from each other so I have to catch them using |

What I usually do is give the two patterns a different name and then choose the one I want using PHP, but I'd like to know if it possible without PHP

Example here : https://3v4l.org/GEMeT (edited thanks to @JustOnUnderMillions)

The 2nd ?P<number> will always capture and replace the first ?P<number>

What I want : Capture both patterns with one regex and store them both with the same key number

```<code>Desired output :

Pattern 1
string(1) "1"

Pattern 2
string(1) "2"
</code>```

Thanks for your help !

答:
Dont use preg_match_all here

```<code>$regex = '/(?J)I wanna match pattern (?P<number>1) which is very different from pattern 2|(?P<number>2), again nothing to do with pattern 1 here/';
</code>```

Result with preg_match:

```<code>array(3) {
 [0]=>
 string(62) "I wanna match pattern 1 which is very different from pattern 2"
 ["number"]=>
 string(1) "1"
 [1]=>
 string(1) "1"
}
</code>```

Full with fixed regex 'nothing similar' was not found in the orignal regex:

```<code>$text1 = 'I wanna match pattern 1 which is very different from pattern 2';
$text2 = 'I wanna match pattern 2, again nothing similar with pattern 1 here';
$regex = '/(?J)(I wanna match pattern (?P<number>1) which is very different from pattern 2|I wanna match pattern (?P<number>2), again nothing similar with pattern 1 here)/';

echo "Pattern 1\n";
preg_match( $regex, $text1, $matches );
var_dump($matches);

echo "\n\nPattern 2\n";
preg_match( $regex, $text2, $matches );
var_dump($matches);
</code>```

Body:
I want to use a regex to match two different subpatterns and give them the same name using the PCRE_INFO_JCHANGED modifier (?J)

The two subpatterns are very different from each other so I have to catch them using |

What I usually do is give the two patterns a different name and then choose the one I want using PHP, but I'd like to know if it possible without PHP

Example here : https://3v4l.org/GEMeT (edited thanks to @JustOnUnderMillions)

The 2nd ?P<number> will always capture and replace the first ?P<number>

What I want : Capture both patterns with one regex and store them both with the same key number

Desired output :

Pattern 1
string(1) "1"

Pattern 2
string(1) "2"

Thanks for your help !

Body:
Dont use preg_match_all here

$regex = '/(?J)I wanna match pattern (?P<number>1) which is very different from pattern 2|(?P<number>2), again nothing to do with pattern 1 here/';

Result with preg_match:

array(3) {
 [0]=>
 string(62) "I wanna match pattern 1 which is very different from pattern 2"
 ["number"]=>
 string(1) "1"
 [1]=>
 string(1) "1"
}

Full with fixed regex 'nothing similar' was not found in the orignal regex:

$text1 = 'I wanna match pattern 1 which is very different from pattern 2';
$text2 = 'I wanna match pattern 2, again nothing similar with pattern 1 here';
$regex = '/(?J)(I wanna match pattern (?P<number>1) which is very different from pattern 2|I wanna match pattern (?P<number>2), again nothing similar with pattern 1 here)/';

echo "Pattern 1\n";
preg_match( $regex, $text1, $matches );
var_dump($matches);

echo "\n\nPattern 2\n";
preg_match( $regex, $text2, $matches );
var_dump($matches);


问:
Render partial with link_to in Google maps info window
I am trying to render a partial by clicking a title within an info window of the Google map on my site.

I am creating the info window with this code:

var iw = new google.maps.InfoWindow({content: content, disableAutoPan: true});

This is what I'm passing as content:

"#{escape_javascript(render 'user/map_infowindow_multiple')}"

Here's my link within the map_infowindow_multiple partial that I am passing to content:

= link_to user.name, multi_user_map_user_path(user), remote: true

Controller action:

```<code>def multi_user_map
  respond_to do |format|
    format.js { render 'multi_user_map.js.haml' }
  end
end
</code>```

Route:

```<code>resources :users do
  member do
    get :multi_user_map
  end
end
</code>```

Within the multi_user_map.js file I have just got an alert for now, I just want to see that something happens when I click the link in the info window.

This is successfully creating the info window with the content that I want, however when I click the link nothing happens.  I think it might be an issue with my route, but I'm not sure.

I'm new to Rails and Stack Overflow, sorry if I'm missing something here.

答: I would first check the route by running "rake routes" command. After clicking the button check the console in the browser( Inspect element in browser). Usually javascript related errors will be shown there. And I hope you have written a function to handle the remote request generated by the button click.</p>

Body:
I am trying to render a partial by clicking a title within an info window of the Google map on my site.

I am creating the info window with this code:

var iw = new google.maps.InfoWindow({content: content, disableAutoPan: true});

This is what I'm passing as content:

"#{escape_javascript(render 'user/map_infowindow_multiple')}"

Here's my link within the map_infowindow_multiple partial that I am passing to content:

= link_to user.name, multi_user_map_user_path(user), remote: true

Controller action:

def multi_user_map
  respond_to do |format|
    format.js { render 'multi_user_map.js.haml' }
  end
end

Route:

resources :users do
  member do
    get :multi_user_map
  end
end

Within the multi_user_map.js file I have just got an alert for now, I just want to see that something happens when I click the link in the info window.

This is successfully creating the info window with the content that I want, however when I click the link nothing happens.  I think it might be an issue with my route, but I'm not sure.

I'm new to Rails and Stack Overflow, sorry if I'm missing something here.


问:
Most parts of the address return null when using the OneLine Search in SKMaps
When I use the oneline search in SKMaps most parts of the address will return null. In android I use the below code:

```<code>SKSearchResult result = results.get(i);
SKAddress address = result.getAddress();
String houseNumber = address.getHouseNumber();
String street = address.getStreet();
String town = address.getCity();
String zipCode = address.getZipCode();
String formatted = houseNumber + " " + street + " " + town + " " + zipCode;
</code>```

When I print out the formatted address it will say

null null city null

How do I get the components of the address without them being null?

答:
Apparently the SKMaps Library is unable to get some components from Open Street Map even though they are available on the Open Street Map website. There is no solution to get these components through the SKMaps Library but you can change the search from Open Street Map to Google by doing:</p>

```<code>onelineSearchSettings.setOnlineGeocoder(SKOnelineSearchSettings.SKGeocoderType.MAP_SEARCH_GOOGLE);
</code>```

Body:
When I use the oneline search in SKMaps most parts of the address will return null. In android I use the below code:

SKSearchResult result = results.get(i);
SKAddress address = result.getAddress();
String houseNumber = address.getHouseNumber();
String street = address.getStreet();
String town = address.getCity();
String zipCode = address.getZipCode();
String formatted = houseNumber + " " + street + " " + town + " " + zipCode;

When I print out the formatted address it will say

null null city null

How do I get the components of the address without them being null?

Body:
Apparently the SKMaps Library is unable to get some components from Open Street Map even though they are available on the Open Street Map website. There is no solution to get these components through the SKMaps Library but you can change the search from Open Street Map to Google by doing:

onelineSearchSettings.setOnlineGeocoder(SKOnelineSearchSettings.SKGeocoderType.MAP_SEARCH_GOOGLE);


问:
0 Results Returned from NetSuite Search
I am attempting to stop a record from being created based on a search result. I can't seem to return any data through my SuiteScript search though, even though I know for a fact the data exists.

I created a Custom Saved Search with the exact filter being used below and return the results I am looking for.

Does anything stand out on why I may not be retrieving any results?

NOTE: The sfdcAccountId Variable does have a value, so I am searching on a valid value.

```<code>// 2.0
define(["N/error", "N/log", "N/search"], function (err, log, search) {

    /**
     * User Event 2.0 example showing usage of the Submit events
     *
     * @NApiVersion 2.x
     * @NModuleScope SameAccount
     * @NScriptType UserEventScript
     * @appliedtorecord customer
     */
    var exports = {};

    function beforeSubmit(scriptContext) {
        log.debug({
            "title": "Before Submit",
            "details": "action=" + scriptContext.type
        });

        if (doesCustomerExist(scriptContext)) {
            throw err.create({
                "name": "DUPLICATE_SFDC_ACCOUNT_ID",
                "message": "Customer Already Contains SFDC Account Id",
                "notifyOff": true
            });
        }
    }

    function doesCustomerExist(scriptContext) {
        var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
        log.debug({
            "title": "Before Submit",
            "details": "sfdcAccountId=" + sfdcAccountId
        });

        if(sfdcAccountId == null || sfdcAccountId == '') return false;

        var searchResult = search.create({
                                            type: search.Type.CUSTOMER,
                                            filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
                                        }).run();

        return (searchResult != null && searchResult.length > 0);
    }

    exports.beforeSubmit = beforeSubmit;
    return exports;
});
</code>```

答:
When you call .run() on a search, it returns a search.ResultSet object.  If you call getRange() on that object, you'll get the array of results that you're looking for.  Here's an updated version of your search that returns search.Result[] on which you can check the length or iterate through as necessary.

```<code>var searchResult = search.create({
    type: search.Type.CUSTOMER,
    filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
}).run().getRange({start: 0, end: 1000});
</code>```

Title: 0 Results Returned from NetSuite Search

Body:
I am attempting to stop a record from being created based on a search result. I can't seem to return any data through my SuiteScript search though, even though I know for a fact the data exists.

I created a Custom Saved Search with the exact filter being used below and return the results I am looking for.

Does anything stand out on why I may not be retrieving any results?

NOTE: The sfdcAccountId Variable does have a value, so I am searching on a valid value.

// 2.0
define(["N/error", "N/log", "N/search"], function (err, log, search) {

    /**
     * User Event 2.0 example showing usage of the Submit events
     *
     * @NApiVersion 2.x
     * @NModuleScope SameAccount
     * @NScriptType UserEventScript
     * @appliedtorecord customer
     */
    var exports = {};

    function beforeSubmit(scriptContext) {
        log.debug({
            "title": "Before Submit",
            "details": "action=" + scriptContext.type
        });

        if (doesCustomerExist(scriptContext)) {
            throw err.create({
                "name": "DUPLICATE_SFDC_ACCOUNT_ID",
                "message": "Customer Already Contains SFDC Account Id",
                "notifyOff": true
            });
        }
    }

    function doesCustomerExist(scriptContext) {
        var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
        log.debug({
            "title": "Before Submit",
            "details": "sfdcAccountId=" + sfdcAccountId
        });

        if(sfdcAccountId == null || sfdcAccountId == '') return false;

        var searchResult = search.create({
                                            type: search.Type.CUSTOMER,
                                            filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
                                        }).run();

        return (searchResult != null && searchResult.length > 0);
    }

    exports.beforeSubmit = beforeSubmit;
    return exports;
});

Body:
When you call .run() on a search, it returns a search.ResultSet object.  If you call getRange() on that object, you'll get the array of results that you're looking for.  Here's an updated version of your search that returns search.Result[] on which you can check the length or iterate through as necessary.

var searchResult = search.create({
    type: search.Type.CUSTOMER,
    filters: ['custentitysfdc_account_id', search.Operator.IS, sfdcAccountId]
}).run().getRange({start: 0, end: 1000});


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
"Naive" serialization that just dumps the value of pointers is never going to work because, when deserializing, those pointers will be invalid.

The general approach to this kind of problem would go like this:

Have each object that can be serialized in your game implement a serialize() virtual function (I am assuming all such objects will ultimately derive from the same base class).

Have the base class implement a get_serialized_id() public function. This function will use a static auto-incremented variable to generate a unique id for each object instance, but only the first time it is called (subsequent calls will just return the existing value).

Now, when serializing:

Start with a std::map<int, YourBaseClass*>. Add your game object to this map, using the value returned by get_serialized_id() for the key.

While the map contains objects that have not been serialized yet:

Take the first such object.

Serialize its get_serialized_id().

Serialize it by calling its implementation for serialize(). Have it persist its primitive data as usual. For data available through pointers, call get_serialized_id() on each object pointed to and just serialize the number returned from it. Also, add that object to the map.

This will result in a bunch of objects being serialized (in a "random" order) along with each one's "random" id.

When deserializing:

Start with a std::map<int, YourBaseClass*>. Read the first item in your saved file.

For each object pointed to by this first object, you know a unique id (this is what you serialized instead of a pointer). Fetch the item with this id from the saved file and deserialize it.

Recursively do this until all items have been fetched and deserialized from the saved file.

As each item has all its dependences deserialized in step 3 above, instantiate it as an object and add it to the map.

This will enable you to grab a pointer from the map given an item's id, which you can now use to set the pointer members of objects dependent on this item.

When the recursion ends, the last object in the map will be your main "game" object with all its pointers ready to go.

ContentLicense: CC BY-SA 2.5

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?


问:
Installing jenkins in linux - import read failed(-1)
I am trying to install the Jenkins in linux machine :
    steps followed :

```<code>1> wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo
2 >rpm --import https://jenkins-ci.org/redhat/jenkins-ci.org.key
</code>```

While importing the key I am getting

```<code>error: https://jenkins-ci.org/redhat/jenkins-ci.org.key: import read failed(-1).
</code>```

Please help me in resolving this issue .

```<code> vi  /etc/yum.repos.d/jenkins.repo
[jenkins]
name=Jenkins-stable
baseurl=http://pkg.jenkins.io/redhat-stable
gpgcheck=1
</code>```

答:
I managed to get it working for me but I had to change the following for the import:</p>

```<code>sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import http://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum install jenkins
</code>```

Body:
I am trying to install the Jenkins in linux machine :
    steps followed :

1> wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins-ci.org/redhat-stable/jenkins.repo
2 >rpm --import https://jenkins-ci.org/redhat/jenkins-ci.org.key

While importing the key I am getting

error: https://jenkins-ci.org/redhat/jenkins-ci.org.key: import read failed(-1).

Please help me in resolving this issue .

 vi  /etc/yum.repos.d/jenkins.repo
[jenkins]
name=Jenkins-stable
baseurl=http://pkg.jenkins.io/redhat-stable
gpgcheck=1

Body:
I managed to get it working for me but I had to change the following for the import:

sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import http://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum install jenkins


问:
MsDeploy parameters.xml: howto refer a parameter?
Currently I'm trying to create a Web Deploy Package. So I've added a parameters.xml to the root of my project and specified some custom parameters.
I found that a lot of my parameters were partially the same. So I want to do some sort of a parameter referencing. Looking for this, I came accros Reference for the Web Application Package. There it says the following:

Hidden - A Hidden parameter is not shown to the user as part of the installation UI. A Hidden parameter must have a defaultValue set. These parameters are used either to set a hard-coded default value or to set a computed default value. Hard-coded defaults are sometimes used when establishing a parameter for future use. Computed values are used to construct a parameter’s value from other parameters. When constructing computed values, you can refer to other parameters by putting the other parameter name surrounded by {}s in the place you want the value. Please refer to the "Connection String" parameter in the example for a common usage of this tag.

So, according to the documentation a parameter "vdeHostName" can be referenced from "vdeDashboardAddress", by setting the attribute defaultValue="https://{vdeHostname}/" and tags="Hidden" on "vdeDashboardAddress".

This led me to the following code for the parameters.xml:

```<code><parameters>
  <parameter name="vdeHostname" description="Please provide the hostname" defaultValue="www.test.com">
    <description culture="en">The hostname of the website.</description>
    <parameterEntry kind="XmlFile"
                    scope="obj\\Release\\Package\\PackageTmp\\Configuration\\hosts\.config$"
                    match="/hostConfigurationSection/hostConfigurations/add[@name='Default']/@host" />
  </parameter>
  <parameter name="vdeDashboardAddress" defaultValue="https://{vdeHostname}/" tags="Hidden">
    <description culture="en">The https address of the Dashboard.</description>
    <parameterEntry kind="XmlFile"
                    scope="obj\\Release\\Package\\PackageTmp\\Configuration\\identity\.config$"
                    match="/system.identityModel/identityConfiguration[@name='Default']/audienceUris/add/@value" />
  </parameter>
<parameters>
</code>```

However, this seems not to be the case. It does not reference/replace the parts of the attribute in the defaultValue.
This is currently being outputted:

```<code><audienceUris>
  <add value="https://{vdeHostname}/" />
</audienceUris>
</code>```

The only thread I found here mentioning anything about my problem is at How to get Deploy.cmd to fill in replacement fields from Parameters.xml

Does anyone know what I'm doing wrong here?

Is the specification incorrect? Then, how does one do partial replaces in the parameters.xml?

Thank you in advance!

Best regards, rdvanbuuren

答: I'm not sure, but the scope attribute looks suspicious to me. All the scope elements in the (working) parameter file I've got in front of me are of the form scope="\\Path\\To\\File\.extension$" where the path specified is assumed to start at the root folder where the application is deployed. (E.g. the most common is scope="\\Web\.config$".) None of the scope attributes in my working file include the Package\PackageTmp part of the path, even though that path is present in the zip file that WebDeploy consumes.

Body:
Currently I'm trying to create a Web Deploy Package. So I've added a parameters.xml to the root of my project and specified some custom parameters.
I found that a lot of my parameters were partially the same. So I want to do some sort of a parameter referencing. Looking for this, I came accros Reference for the Web Application Package. There it says the following:

Hidden - A Hidden parameter is not shown to the user as part of the installation UI. A Hidden parameter must have a defaultValue set. These parameters are used either to set a hard-coded default value or to set a computed default value. Hard-coded defaults are sometimes used when establishing a parameter for future use. Computed values are used to construct a parameter’s value from other parameters. When constructing computed values, you can refer to other parameters by putting the other parameter name surrounded by {}s in the place you want the value. Please refer to the "Connection String" parameter in the example for a common usage of this tag.

So, according to the documentation a parameter "vdeHostName" can be referenced from "vdeDashboardAddress", by setting the attribute defaultValue="https://{vdeHostname}/" and tags="Hidden" on "vdeDashboardAddress".

This led me to the following code for the parameters.xml:

<parameters>
  <parameter name="vdeHostname" description="Please provide the hostname" defaultValue="www.test.com">
    <description culture="en">The hostname of the website.</description>
    <parameterEntry kind="XmlFile"
                    scope="obj\\Release\\Package\\PackageTmp\\Configuration\\hosts\.config$"
                    match="/hostConfigurationSection/hostConfigurations/add[@name='Default']/@host" />
  </parameter>
  <parameter name="vdeDashboardAddress" defaultValue="https://{vdeHostname}/" tags="Hidden">
    <description culture="en">The https address of the Dashboard.</description>
    <parameterEntry kind="XmlFile"
                    scope="obj\\Release\\Package\\PackageTmp\\Configuration\\identity\.config$"
                    match="/system.identityModel/identityConfiguration[@name='Default']/audienceUris/add/@value" />
  </parameter>
<parameters>

However, this seems not to be the case. It does not reference/replace the parts of the attribute in the defaultValue.
This is currently being outputted:

<audienceUris>
  <add value="https://{vdeHostname}/" />
</audienceUris>

The only thread I found here mentioning anything about my problem is at How to get Deploy.cmd to fill in replacement fields from Parameters.xml

Does anyone know what I'm doing wrong here?

Is the specification incorrect? Then, how does one do partial replaces in the parameters.xml?

Thank you in advance!

Best regards, rdvanbuuren


问:
How can I undo commit template?
I once added global commit temlate by command:

```<code>git config --global commit.template .gitmessage.txt
</code>```

Today I created my own repository and when I tried commit, I got error:

fatal: could not read '.gitmessage.txt': No such file or directory

It's fine, because I don't create .gitmessage.txt file. I wouldn't have a template for this repo. And here comes the question: How can I undo global commit template? I can overwrite global commit template but I can delete thi configuration.

I was trying:

```<code>git config --global commit.template ""
</code>```

but i got similar error:

fatal: could not read '''': No such file or directory

And when I run command

```<code>git config --global commit.template
</code>```

i got echo current template. Anyone can help me?

答:
Remove this section from the ~/.gitconfig file on your system.</p>

```<code>[commit]
    template = .gitmessage.txt
</code>```

Title: How can I undo commit template?

Body:
I once added global commit temlate by command:

git config --global commit.template .gitmessage.txt

Today I created my own repository and when I tried commit, I got error:

fatal: could not read '.gitmessage.txt': No such file or directory

It's fine, because I don't create .gitmessage.txt file. I wouldn't have a template for this repo. And here comes the question: How can I undo global commit template? I can overwrite global commit template but I can delete thi configuration.

I was trying:

git config --global commit.template ""

but i got similar error:

fatal: could not read '''': No such file or directory

And when I run command

git config --global commit.template

i got echo current template. Anyone can help me?

Body:
Remove this section from the ~/.gitconfig file on your system.

[commit]
    template = .gitmessage.txt


问:
XSD/Schema validation workaround in .net core?
I got from https://github.com/dotnet/corefx/issues/3633, that XSD Schema Validation now is not yet supported, and planned in .Net Core 1.2.0 whose release date is Spring, 2017.

However it's one of the key features of our product, so it somehow has to be supported. Now .Net Standard doesn't even have System.Xml.Schema when we thought to temporarily use full .net core, yet doesn't help.

Before v1.2.0, is there any workaround to do the xsd schema validation?

答:
If you need some functionality that needs to be run in .Net Core library, you may try to port your product with portable library workaround.

However, it's nearly the .NET Core 2.0 Preview time, so you may basically wait for it.


问:
In React, how to convert country code to country name, using country-data?
Using country-data, I thought I could do

```<code>npm install --save country-data
</code>```

and then in the code:

```<code>import CountryData from "country-data";
</code>```

and use

```<code>CountryData.countries["TW"]
</code>```

to get the country data, and

```<code>CountryData.countries["TW"].name
</code>```

to get the name. But CountryData.countries["TW"] gets undefined already. How can it be done? Are there possible better alternatives to using country-data?

P.S. the npm page and github page of country-data has some info on how to use it with webpack, which I suspect is needed to be used with React. But I did them:

```<code>npm install json-loader --save-dev
</code>```

add to webpack.config.js:

```<code>// ...
   loaders: [
      // other loaders
      { test: /\.json$/, loader: 'json' },
  ],
// ...
</code>```

and it doessn't work yet.

答:
If you use

```<code>var CountryData = require('country-data');
console.log(CountryData.countries['TW']);
</code>```

It works an outputs as such

```<code>{ alpha2: 'TW',
  alpha3: 'TWN',
  countryCallingCodes: [ '+886' ],
  currencies: [ 'TWD' ],
  emoji: '',
  ioc: 'TPE',
  languages: [ 'zho' ],
  name: 'Taiwan',
  status: 'assigned' }
</code>```

It could be because of how the module is exported?

This also works

```<code>import CountryData from 'country-data'
console.log(JSON.stringify(CountryData.countries['TW']));
</code>```

Outputs as such

```<code>{"alpha2":"TW","alpha3":"TWN","countryCallingCodes":["+886"],"currencies":["TWD"],"emoji":"","ioc":"TPE","languages":["zho"],"name":"Taiwan","status":"assigned"}
</code>```

Body:
Using country-data, I thought I could do

npm install --save country-data

and then in the code:

import CountryData from "country-data";

and use

CountryData.countries["TW"]

to get the country data, and

CountryData.countries["TW"].name

to get the name. But CountryData.countries["TW"] gets undefined already. How can it be done? Are there possible better alternatives to using country-data?

P.S. the npm page and github page of country-data has some info on how to use it with webpack, which I suspect is needed to be used with React. But I did them:

npm install json-loader --save-dev

add to webpack.config.js:

// ...
   loaders: [
      // other loaders
      { test: /\.json$/, loader: 'json' },
  ],
// ...

and it doessn't work yet.

Body:
If you use

var CountryData = require('country-data');
console.log(CountryData.countries['TW']);

It works an outputs as such

{ alpha2: 'TW',
  alpha3: 'TWN',
  countryCallingCodes: [ '+886' ],
  currencies: [ 'TWD' ],
  emoji: '',
  ioc: 'TPE',
  languages: [ 'zho' ],
  name: 'Taiwan',
  status: 'assigned' }

It could be because of how the module is exported?

This also works

import CountryData from 'country-data'
console.log(JSON.stringify(CountryData.countries['TW']));

Outputs as such

{"alpha2":"TW","alpha3":"TWN","countryCallingCodes":["+886"],"currencies":["TWD"],"emoji":"","ioc":"TPE","languages":["zho"],"name":"Taiwan","status":"assigned"}


问:
In SQL Server select record which are completed without going to resolved state
I want to find records in SQL Server which are marked as completed but they do not go through resolved state.

Here is the example below.

```<code>tracking_id task_id task status   old_status new_status_id
1195372     140717  ABC  Complete NULL       NULL
1195373     140717  ABC  Complete NULL       New
1195374     140717  ABC  Complete New        Completed
1195380     140718  XYZ  Complete NULL       NULL
1195381     140718  XYZ  Complete NULL       New
1195382     140718  XYZ  Complete New        Completed
1195383     140719  PQR  Complete NULL       NULL
1195384     140719  PQR  Complete NULL       Resolved
1195385     140719  PQR  Complete Resolved   Completed
</code>```

Now in the table as task_id 140717 and 140718 is marked as Completed but it never went to state Resolved. Where as task_id 140719 is also marked completed but it goes through state Resolved. So I want to write SQL Query to just get record with task_id 140717 and 140718.

Any help with how to write query for this will be appreciated.

答:
You should follow some guides about select statements as this is very basic syntax.

Just use some where clauses:

```<code>SELECT *
FROM Table
WHERE old_status !+ 'Resolved'
AND new_status_id = 'Completed'
</code>```

Body:
I want to find records in SQL Server which are marked as completed but they do not go through resolved state.

Here is the example below.

tracking_id task_id task status   old_status new_status_id
1195372     140717  ABC  Complete NULL       NULL
1195373     140717  ABC  Complete NULL       New
1195374     140717  ABC  Complete New        Completed
1195380     140718  XYZ  Complete NULL       NULL
1195381     140718  XYZ  Complete NULL       New
1195382     140718  XYZ  Complete New        Completed
1195383     140719  PQR  Complete NULL       NULL
1195384     140719  PQR  Complete NULL       Resolved
1195385     140719  PQR  Complete Resolved   Completed

Now in the table as task_id 140717 and 140718 is marked as Completed but it never went to state Resolved. Where as task_id 140719 is also marked completed but it goes through state Resolved. So I want to write SQL Query to just get record with task_id 140717 and 140718.

Any help with how to write query for this will be appreciated.

Body:
You should follow some guides about select statements as this is very basic syntax.

Just use some where clauses:

SELECT *
FROM Table
WHERE old_status !+ 'Resolved'
AND new_status_id = 'Completed'


问:
iOS - Print and store array of dictionary in swift 3
In my project I have an array of dictionaries:

```<code>var list = [[String: Any]] ()
</code>```

Very briefly, what I do is download a JSON file from a URL

```<code>//        json parsing 2
        let url:String = "https://jsonplaceholder.typicode.com/users"
        let urlRequest = URL(string: url)
        URLSession.shared.dataTask(with: urlRequest!, completionHandler: {(data, response, error) in
            if(error != nil)
            {
                print(error.debugDescription)
            }else{
                do {
                    self.list = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                        as! [[String: Any]]
                    OperationQueue.main.addOperation {
                        self.tableView.reloadData()
                    }
                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()
</code>```

Now, within the list (which is an array of dictionaries) I have all the data that interest me. But if I want to pick out a single value, or print the entire contents of list how am I supposed to do?

EDIT: also, I can simplify the structure and do not use an array
  of dictionaries, but something simpler?

答:
Or you can use archiving

```<code>import Foundation

class UserDataManager {

var documentsURL: NSURL?
var fileURL:NSURL?

func setFileURL(file: String) {
    documentsURL = FileManager.default.urls(for: .documentDirectory,
                                                   in: .userDomainMask)[0] as NSURL?
    fileURL = documentsURL!.appendingPathComponent(file) as NSURL?

}

func write(file: String, mDict: NSDictionary) {
    setFileURL(file: file)
    let data : NSData = NSKeyedArchiver.archivedData(withRootObject: mDict) as NSData
    if let fileAssigend = fileURL {
        data.write(to: fileAssigend as URL, atomically: true)
    }
}

func read(file: String) -> NSDictionary {
    setFileURL(file: file)

    var data:NSData?
    if let url = fileURL {
        data =  NSData(contentsOf: url as URL)
        if let result = data {
            return NSKeyedUnarchiver.unarchiveObject(with: result as Data) as! NSDictionary
        }
    }

    let dict = NSDictionary()

    return dict
}
}
</code>```

and use it with

write:

```<code>        let userDataManager = UserDataManager()
        userDataManager.write(file: "userDataDict", mDict: responseObject)
</code>```

read:

```<code>        let userDataManager = UserDataManager()
        let userDataDict = userDataManager.read(file: "userDataDict")
</code>```

Body:
In my project I have an array of dictionaries:

var list = [[String: Any]] ()

Very briefly, what I do is download a JSON file from a URL

//        json parsing 2
        let url:String = "https://jsonplaceholder.typicode.com/users"
        let urlRequest = URL(string: url)
        URLSession.shared.dataTask(with: urlRequest!, completionHandler: {(data, response, error) in
            if(error != nil)
            {
                print(error.debugDescription)
            }else{
                do {
                    self.list = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                        as! [[String: Any]]
                    OperationQueue.main.addOperation {
                        self.tableView.reloadData()
                    }
                }catch let error as NSError{
                    print(error)
                }
            }
        }).resume()

Now, within the list (which is an array of dictionaries) I have all the data that interest me. But if I want to pick out a single value, or print the entire contents of list how am I supposed to do?

EDIT: also, I can simplify the structure and do not use an array
  of dictionaries, but something simpler?

Body:
Or you can use archiving

import Foundation

class UserDataManager {

var documentsURL: NSURL?
var fileURL:NSURL?

func setFileURL(file: String) {
    documentsURL = FileManager.default.urls(for: .documentDirectory,
                                                   in: .userDomainMask)[0] as NSURL?
    fileURL = documentsURL!.appendingPathComponent(file) as NSURL?

}

func write(file: String, mDict: NSDictionary) {
    setFileURL(file: file)
    let data : NSData = NSKeyedArchiver.archivedData(withRootObject: mDict) as NSData
    if let fileAssigend = fileURL {
        data.write(to: fileAssigend as URL, atomically: true)
    }
}

func read(file: String) -> NSDictionary {
    setFileURL(file: file)

    var data:NSData?
    if let url = fileURL {
        data =  NSData(contentsOf: url as URL)
        if let result = data {
            return NSKeyedUnarchiver.unarchiveObject(with: result as Data) as! NSDictionary
        }
    }

    let dict = NSDictionary()

    return dict
}
}

and use it with

write:

        let userDataManager = UserDataManager()
        userDataManager.write(file: "userDataDict", mDict: responseObject)

read:

        let userDataManager = UserDataManager()
        let userDataDict = userDataManager.read(file: "userDataDict")


答:
The idea is to make sure that a task ID has a "Completed" record, but not a "Resolved" record.

```<code>select ...
from the_table t_outer
where
  status = 'Completed' and
  not exists (
    select 1 from the_table t_inner
    where
      t_inner.task_id = t_outer.task_id and  -- same task
      'Resolved' in (t_inner.old_status, t_inner.new_status)
  )
</code>```

(The whole status / new_status / old_status thing feels untidy.)

Title: In SQL Server select record which are completed without going to resolved state

Body:
The idea is to make sure that a task ID has a "Completed" record, but not a "Resolved" record.

select ...
from the_table t_outer
where
  status = 'Completed' and
  not exists (
    select 1 from the_table t_inner
    where
      t_inner.task_id = t_outer.task_id and  -- same task
      'Resolved' in (t_inner.old_status, t_inner.new_status)
  )

(The whole status / new_status / old_status thing feels untidy.)


问:
How can I stop gdb from reading ".cshrc"?
I am trying to debug an application using the gdb debugger.  This application has some specific environment requirements.  Before starting gdb I set up the environment the way I want, then I open gdb.

At first glance it looks like all is well. The command show environment shows all of the variables that I want, but when I use the run command they magically get reset!

I did some digging and found out that gdb is automatically calling the .cshrc file and reloading all of the environment variables, but there doesn't seem to be any way to stop it! How can I stop this from happening?

Is there a way to check inside of the .cshrc file if it is being called from gdb and skip it?  I've been struggling with this for days and it's incredibly irritating.

答:
So far I have found one solution, but I'm not sure if this is going to break other things on the server yet.

I added the following code the the .cshrc file and now it aborts when it is called by gdb:

```<code>if ( ! $?prompt ) then
    exit
endif
</code>```

This code basically tells it to abort if it is being called by something other than an interactive shell.  It works for now, but I have a feeling that I may find out this breaks something else in the future.

Body:
So far I have found one solution, but I'm not sure if this is going to break other things on the server yet.

I added the following code the the .cshrc file and now it aborts when it is called by gdb:

if ( ! $?prompt ) then
    exit
endif

This code basically tells it to abort if it is being called by something other than an interactive shell.  It works for now, but I have a feeling that I may find out this breaks something else in the future.


问:
data structure to store and manipulate efficienty pixels :
l have a set of images (1000 images). each one has a dimension of 3072.
each image has this representation :
image 1 for instance :

```<code>array([255, 78, 48, ..., 190, 230, 178], dtype=uint8)
</code>```

l want to store that in matrix such that each line represents a vector (3072) of an image. which means l get at the end a matrix of (1000,3072)
here is what l tried

```<code>matrix_of_images= []
for img in images:
    data.append(img)
    data.append(img2)
</code>```

however append list gives me a structure which is difficult to manipulate since l want to store it in csv file then call a part of an image.

```<code>[array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8)]
</code>```

l'm looking for something like
X=

```<code>[

[23,56, 78,....,45,156],
[60,56, 104,....,145,157],
[78,45, 7,....,0,15],
[45,56, 178,....,5,200]

]
</code>```

where l can read form example

```<code>X[1] #  second image
 [60,56, 104,....,145,157]
X[1][2] # third pixel of second image
104
</code>```

a structure which is easy to store in csv file  where each pixel in a column.

EDIT :
the vectors to add at each iteration are img1 and img2

```<code>for i in range(1,500):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i-1]
    if (charac== "'/'"):
        charac= "'slash'"

    charac = charac.strip('"\'')
    #actual cropping of the image (easy with numpy)
    #img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac = img[int(coords[4]):int(coords[5]), int(coords[2]):int(coords[3])]
    #cv2.imwrite(path_save_cropped_images + str(charac) + "_" + str(i) + "_" + str(img_charac.shape) + ".png",  img_charac)

    #resize
    img_charac_resized=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    #cv2.imwrite(path_save_resized_images + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",img_charac_resized)
    #img_charac = cv2.resize(img_charac, (32, 32))

    #switch images
    img_charac_switched = 255 - img_charac_resized
    #cv2.imwrite(path_save_switched_pixels+ str(charac) +"_switched"+ "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)

    img1 = img_charac_resized.reshape((-1, 1))
    img1 = img1.T
    img1= img1.flatten()
    img1_label=charac

    img2=img_charac_switched.reshape((-1,1))
    img2=img2.T
    img2=img2.flatten()
    img2_label = charac
    #x=switch(charac)
    #saving the image

    #dataset

    #cv2.imwrite(path_dataset+ str(charac) + "_switched" + "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)
    #cv2.imwrite(path_dataset + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",  img_charac_resized)

    #images = [img1,img2]
    img_arr = np.stack(img1, axis=0)
    img_arr = np.stack(img2, axis=0)
    #data.append(img1)
    #data.append(img2)

    #print (img_arr.shape)
    #print(i)

print(img_arr)
print(img_arr.shape)
</code>```

答:
You want to be using numpy.stack. Specify axis=0 to stack vertically:

```<code>import numpy as np
n = 1000
images = [np.random.random(3072) for _ in range(n)]
img_arr = np.stack(images,axis=0)

>>> img_arr.shape
(1000, 3072)
</code>```

In the case of your code:

```<code>images = []
for i in range(500):
    # create img1 and img2
    images.extend([img1,img2])
img_arr = np.stack(images,axis=0)
</code>```

Body:
l have a set of images (1000 images). each one has a dimension of 3072.
each image has this representation :
image 1 for instance :

array([255, 78, 48, ..., 190, 230, 178], dtype=uint8)

l want to store that in matrix such that each line represents a vector (3072) of an image. which means l get at the end a matrix of (1000,3072)
here is what l tried

matrix_of_images= []
for img in images:
    data.append(img)
    data.append(img2)

however append list gives me a structure which is difficult to manipulate since l want to store it in csv file then call a part of an image.

[array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8)]

l'm looking for something like
X=

[

[23,56, 78,....,45,156],
[60,56, 104,....,145,157],
[78,45, 7,....,0,15],
[45,56, 178,....,5,200]

]

where l can read form example

X[1] #  second image
 [60,56, 104,....,145,157]
X[1][2] # third pixel of second image
104

a structure which is easy to store in csv file  where each pixel in a column.

EDIT :
the vectors to add at each iteration are img1 and img2

for i in range(1,500):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i-1]
    if (charac== "'/'"):
        charac= "'slash'"

    charac = charac.strip('"\'')
    #actual cropping of the image (easy with numpy)
    #img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac = img[int(coords[4]):int(coords[5]), int(coords[2]):int(coords[3])]
    #cv2.imwrite(path_save_cropped_images + str(charac) + "_" + str(i) + "_" + str(img_charac.shape) + ".png",  img_charac)

    #resize
    img_charac_resized=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    #cv2.imwrite(path_save_resized_images + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",img_charac_resized)
    #img_charac = cv2.resize(img_charac, (32, 32))

    #switch images
    img_charac_switched = 255 - img_charac_resized
    #cv2.imwrite(path_save_switched_pixels+ str(charac) +"_switched"+ "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)

    img1 = img_charac_resized.reshape((-1, 1))
    img1 = img1.T
    img1= img1.flatten()
    img1_label=charac

    img2=img_charac_switched.reshape((-1,1))
    img2=img2.T
    img2=img2.flatten()
    img2_label = charac
    #x=switch(charac)
    #saving the image

    #dataset

    #cv2.imwrite(path_dataset+ str(charac) + "_switched" + "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)
    #cv2.imwrite(path_dataset + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",  img_charac_resized)

    #images = [img1,img2]
    img_arr = np.stack(img1, axis=0)
    img_arr = np.stack(img2, axis=0)
    #data.append(img1)
    #data.append(img2)

    #print (img_arr.shape)
    #print(i)

print(img_arr)
print(img_arr.shape)

Body:
You want to be using numpy.stack. Specify axis=0 to stack vertically:

import numpy as np
n = 1000
images = [np.random.random(3072) for _ in range(n)]
img_arr = np.stack(images,axis=0)

>>> img_arr.shape
(1000, 3072)

In the case of your code:

images = []
for i in range(500):
    # create img1 and img2
    images.extend([img1,img2])
img_arr = np.stack(images,axis=0)


问:
How can I apply href and data-toggle to an element except one of its child elements?
I want to make a link and data-toggle for all elements inside tr except for .jill. How can I remove the link and data-toggle only for this specific child?

 $(".jill").removeAttr('data-toggle');
 $(".jill").removeAttr("href");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="width:100%">
  <tr href="#" data-toggle="control-sidebar">
    <td class="jill">Jill</td>
    <td>Smith</td>
    <td>50</td>
     <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table></code>```

The way I do it it is not working

答:
I'll expand on my comment.

The href is not applied to the child elements, only the parent element. So the href can't be removed from the children, because the children do not have that attribute.

So you have a few options, you can either apply the href and data-toggle in each , except the ones you want. Or you could set this all with jquery. I'm not sure why you would want to do it in jquery, but if you're dynamically generating these rows you could do this, and use a

```<code> .not('.jill')
</code>```

in your selector, then do something like

```<code> .attr('href', '#')
</code>```

To set the href.

Body:
I want to make a link and data-toggle for all elements inside tr except for .jill. How can I remove the link and data-toggle only for this specific child?

 $(".jill").removeAttr('data-toggle');
 $(".jill").removeAttr("href");

    Jill
    Smith
    50
     Eve
    Jackson
    94

The way I do it it is not working

Body:
I'll expand on my comment.

The href is not applied to the child elements, only the parent element. So the href can't be removed from the children, because the children do not have that attribute.

So you have a few options, you can either apply the href and data-toggle in each <td>, except the ones you want. Or you could set this all with jquery. I'm not sure why you would want to do it in jquery, but if you're dynamically generating these rows you could do this, and use a

 .not('.jill')

in your selector, then do something like

 .attr('href', '#')

To set the href.


问:
Google Maps polyline not drawing correctly
I'm making an app that when clicking on a marker it will open a dialog with a "Go" button, when the user press that button it show a path. I'm creating the path with the overview-polyline from google directions api, the problem is that the line is not correctly drawn, the line creates straight lines which makes the path pass over buildings like in the image:

How can I fix this?

答:
I think you need to enable the Google Maps Direction API form the Google Developer Console.That should give you the path along the streets.

Go to Google Developer Console.

Click on Library.

Click Google Maps Directions API under Google Maps API.

Click on ENABLE button.


问:
Disable MobaXterm file browser sidebar from opening automatically
This seems like a simple question but I can't find an answer. I use MobaXterm free edition to SSH into my machines. Every time I SSH into a machine the side bar automatically expands with the paths on the remote machine. I don't need this side bar and every time I have to collapse it. Is there a way to permanently disable the side bar or at least not automatically expend it when SSH-ing?

Here is a picture (linked) of the expaned sidebar:

答: Under settings there are these 2 settings that control this that I typically turn off.


问:
Using Actors to exploit cores
I'm new to Scala in general and Actors in particular and my problem is so basic, the online resources I have found don't cover it.

I have a CPU-intensive, easily parallelized algorithm that will be run on an n-core machine (I don't know n).  How do I implement this in Actors so that all available cores address the problem?

The first way I thought of was to simple break the problem into m pieces (where m is some medium number like 10,000) and create m Actors, one for each piece, give each Actor its little piece and let 'em go.

Somehow, this struck me as inefficient.  Zillions of Actors just hanging around, waiting for some CPU love, pointlessly switching contexts...

Then I thought, make some smaller number of Actors, and feed each one several pieces.  The problem was, there's no reason to expect the pieces are the same size, so one core might get bogged down, with many of its tasks still queued, while other cores are idle.

I noodled around with a Supervisor that knew which Actors were busy, and eventually realized that this has to be a solved problem.  There must be a standard pattern (maybe even a standard library) for dealing with this very generic issue.  Any suggestions?

答: Be aware of actor starvation if you end up utilizing the general actor threadpool. I ended up simply using my own algorithm-task-owned threadpool to handle the parallelization of a long-running, concurrent task. </p>

Title: Using Actors to exploit cores


问:
Is there any way reduce the I/O wait times in linux jobs?
I am running a multiple parallel file handling process (minimum 200 processes) where each process is reading a logs of varying size(0-50mb) to capture a real time data of the logs .I am running my jobs on 16 cores and 8 gb ram Linux machine.

But there is a huge lag between the cpu and elapsed time process of the files.

Can you please explain why there is such lag b/w cpu and elapsed time with some examples?Also is there any method to reduce the wait times of these processes.

答:
What distro are you running? I ask because one way to approach this would be to use a different I/O scheduler but your distro may not support changing your scheduler. Certain I/O schedulers are best for different filesystems and architectures so I would recommend looking here to get an idea of different schedulers. As for the discrepancy you're experiencing, I honestly have no idea what that's happening.

Also, I'm assuming the log files are located on an SSD?


问:
How to make a button expand the length of an html table header?
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

```<code><th><button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button></th>
</code>```

And this is how it looks without using width:

```<code><th><button onclick="tableColumnSort(this)">@descriptor.Name</button></th>
</code>```

答:
Change css of the clicked th with your js, with a low gray background (#ccc it's good) and change font-size a bit, 1 or 2px. TL;DR Change the frontend to show a more elegant th with the users interactions

```<code><table>
  <thead>
    <tr>
      <th onclick="tableColumnSort(this); changeTH(this);">
        shortHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        veryLongLongHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        header
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table><table>
  <thead>
    <tr>
      <th onclick="tableColumnSort(this); changeTH(this);">
        shortHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        veryLongLongHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        header
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> </td>
      <td> </td>
      <td> </td>
    </tr>
  </tbody>
</table>
</code>```

On JS:

```<code>function changeTH(container){
   var ths = document.getElementsByTagName('th');
   var totalThs = ths.length;
   //reset all ths before set your new th style
   for (i = 0; i < totalThs; i++){
     ths[i].style.background = '#fff';
     ths[i].style.fontSize = 'inherit';
   }
   container.style.background = '#ccc';
   container.style.fontSize = '12px'; //or other size you prefer
}
</code>```

The better way to do this is add all listeners inside a js file, it's more elegant, but my example works fine.

Body:
I am trying to get a button that I put in a table  to expand the full width and height of the header column, even when a table cell in the same column is larger than the text. If I do, width 100% in css, then the button will just match the cell size, and then the title will extend beyond the button and header.

I am using the button so when the user click on it the column will sort.

This is my code just trying to do with width:

<button onclick="tableColumnSort(this)" style="width:100%">@descriptor.Name</button>

And this is how it looks without using width:

<button onclick="tableColumnSort(this)">@descriptor.Name</button>

Body:
Change css of the clicked th with your js, with a low gray background (#ccc it's good) and change font-size a bit, 1 or 2px. TL;DR Change the frontend to show a more elegant th with the users interactions

<table>
  <thead>
    <tr>
      <th onclick="tableColumnSort(this); changeTH(this);">
        shortHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        veryLongLongHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        header
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table><table>
  <thead>
    <tr>
      <th onclick="tableColumnSort(this); changeTH(this);">
        shortHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        veryLongLongHeader
      </th>
      <th onclick="tableColumnSort(this); changeTH(this);">
        header
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>

On JS:

function changeTH(container){
   var ths = document.getElementsByTagName('th');
   var totalThs = ths.length;
   //reset all ths before set your new th style
   for (i = 0; i < totalThs; i++){
     ths[i].style.background = '#fff';
     ths[i].style.fontSize = 'inherit';
   }
   container.style.background = '#ccc';
   container.style.fontSize = '12px'; //or other size you prefer
}

The better way to do this is add all listeners inside a js file, it's more elegant, but my example works fine.


问:
Need Help Compiling Java (Accessors, Mutators, Constructors)
So I have been working on this project for some time now and I'm having a lot of trouble grasping Java for some reason.

The objective is to create 3 objects that contain 3 fruits each and each fruit has its own price/value.

I'm having trouble adding up the values currently, I'm sure there is much more wrong as I said I'm having a lot of trouble with Java so far.

My biggest problem is currently the costofBox() method.

Any suggestions that are helpful would be greatly appreciated, I've been working on this for over a week now.

Here is the entire program:

```<code>public class Project8
{

private String fruit1;
private String fruit2;
private String fruit3;
private String Bundle1;
private String Bundle2;
private String Bundle3;
private int costofBox;
double total;
int broccoli;
int tomato;
int kiwi;
int kale;
int orange;

public String toString()
{
    String output = "The box contains: " + Bundle1 + ", " + Bundle2 + ", " + Bundle3 +
    "and the cost is $" + costofBox();
    return output;
}

public String getBundle1()
{
    return Bundle1;
}
public String getBundle2()
{
    return Bundle2;
}
public String getBundle3()
{
    return Bundle3;
}

public void setBundle1(String Bundle1)
{
    Bundle1=fruit1;
}
public void setBundle2(String Bundle2)
{
    Bundle2=fruit2;
}
public void setBundle3(String Bundle3)
{
    Bundle3=fruit3;
}

public double costofBox()
{
    double total=0;
    if(Bundle1.equals("broccoli"))
        total+=6;
    else if(Bundle1.equals("tomato"))
        total+=5;
    else if(Bundle1.equals("kiwi"))
        total+=8;
    else if(Bundle1.equals("kale"))
        total+=4;
    else if(Bundle1.equals("orange"))
        total+=7;
    if(Bundle2.equals("broccoli"))
        total+=6;
    else if(Bundle2.equals("tomato"))
        total+=5;
    else if(Bundle2.equals("kiwi"))
        total+=8;
    else if(Bundle2.equals("kale"))
        total+=4;
    else if(Bundle2.equals("orange"))
        total+=7;
    if(Bundle3.equals("broccoli"))
        total+=6;
    else if(Bundle3.equals("tomato"))
        total+=5;
    else if(Bundle3.equals("kiwi"))
        total+=8;
    else if(Bundle3.equals("kale"))
        total+=4;
    else if(Bundle3.equals("orange"))
        total+=7;

    return total;
}

public Project8()
{
    fruit1 = "broccoli" + "kale" + "orange";
    fruit2 = "kale" + "kiwi" + "orange";
    fruit3 = "broccoli" + "tomato" + "kiwi";
}

public Project8(String fruit1, String fruit2, String fruit3)
{
    String Bundle1=fruit1;
    String Bundle2=fruit2;
    String Bundle3=fruit3;
}

public static void main (String [] args)
{
    Project8 Bundle1=new Project8 ("broccoli", "kale", "orange");
    Project8 Bundle2=new Project8 ("kale", "kiwi", "orange");
    Project8 Bundle3=new Project8 ("broccoli", "tomato", "kiwi");

    System.out.println("Week 1: " + Bundle1.toString());
    System.out.println("Week 2: " + Bundle2.toString());
    System.out.println("Week 3: " + Bundle3.toString());
    System.out.println("Week4: The box contains:,, and the cost is $0.0");
    }
}
</code>```

Thank you ahead of time for those of you who can help me out!

答:
Your problem is in this constructor:

```<code>public Project8(String fruit1, String fruit2, String fruit3)
{
    String Bundle1=fruit1;
    String Bundle2=fruit2;
    String Bundle3=fruit3;
}
</code>```

Because of the type String in front of these assignments, you are declaring new local variables! This means that the fields of your class:

```<code>private String Bundle1;
private String Bundle2;
private String Bundle3;
</code>```

... are not ever given values. When you try to access them you get the exception you were seeing because they are NULL.

If you change the constructor to:

```<code>public Project8(String fruit1, String fruit2, String fruit3)
{
    Bundle1 = fruit1;
    Bundle2 = fruit2;
    Bundle3 = fruit3;
}
</code>```

then your project will execute properly.

As an aside, there's a lot of ways you could reduce the length of your program, make things more concise, and repeat yourself less. I suggest once you've got it working you head over to Code Review which is a sister site to StackOverflow: they'll give you suggestions to improve. If you do decide to do that, drop me a comment on this answer!

Body:
So I have been working on this project for some time now and I'm having a lot of trouble grasping Java for some reason.

The objective is to create 3 objects that contain 3 fruits each and each fruit has its own price/value.

I'm having trouble adding up the values currently, I'm sure there is much more wrong as I said I'm having a lot of trouble with Java so far.

My biggest problem is currently the costofBox() method.

Any suggestions that are helpful would be greatly appreciated, I've been working on this for over a week now.

Here is the entire program:

public class Project8
{

private String fruit1;
private String fruit2;
private String fruit3;
private String Bundle1;
private String Bundle2;
private String Bundle3;
private int costofBox;
double total;
int broccoli;
int tomato;
int kiwi;
int kale;
int orange;

public String toString()
{
    String output = "The box contains: " + Bundle1 + ", " + Bundle2 + ", " + Bundle3 +
    "and the cost is $" + costofBox();
    return output;
}

public String getBundle1()
{
    return Bundle1;
}
public String getBundle2()
{
    return Bundle2;
}
public String getBundle3()
{
    return Bundle3;
}

public void setBundle1(String Bundle1)
{
    Bundle1=fruit1;
}
public void setBundle2(String Bundle2)
{
    Bundle2=fruit2;
}
public void setBundle3(String Bundle3)
{
    Bundle3=fruit3;
}

public double costofBox()
{
    double total=0;
    if(Bundle1.equals("broccoli"))
        total+=6;
    else if(Bundle1.equals("tomato"))
        total+=5;
    else if(Bundle1.equals("kiwi"))
        total+=8;
    else if(Bundle1.equals("kale"))
        total+=4;
    else if(Bundle1.equals("orange"))
        total+=7;
    if(Bundle2.equals("broccoli"))
        total+=6;
    else if(Bundle2.equals("tomato"))
        total+=5;
    else if(Bundle2.equals("kiwi"))
        total+=8;
    else if(Bundle2.equals("kale"))
        total+=4;
    else if(Bundle2.equals("orange"))
        total+=7;
    if(Bundle3.equals("broccoli"))
        total+=6;
    else if(Bundle3.equals("tomato"))
        total+=5;
    else if(Bundle3.equals("kiwi"))
        total+=8;
    else if(Bundle3.equals("kale"))
        total+=4;
    else if(Bundle3.equals("orange"))
        total+=7;

    return total;
}

public Project8()
{
    fruit1 = "broccoli" + "kale" + "orange";
    fruit2 = "kale" + "kiwi" + "orange";
    fruit3 = "broccoli" + "tomato" + "kiwi";
}

public Project8(String fruit1, String fruit2, String fruit3)
{
    String Bundle1=fruit1;
    String Bundle2=fruit2;
    String Bundle3=fruit3;
}

public static void main (String [] args)
{
    Project8 Bundle1=new Project8 ("broccoli", "kale", "orange");
    Project8 Bundle2=new Project8 ("kale", "kiwi", "orange");
    Project8 Bundle3=new Project8 ("broccoli", "tomato", "kiwi");

    System.out.println("Week 1: " + Bundle1.toString());
    System.out.println("Week 2: " + Bundle2.toString());
    System.out.println("Week 3: " + Bundle3.toString());
    System.out.println("Week4: The box contains:,, and the cost is $0.0");
    }
}

Thank you ahead of time for those of you who can help me out!

Body:
Your problem is in this constructor:

public Project8(String fruit1, String fruit2, String fruit3)
{
    String Bundle1=fruit1;
    String Bundle2=fruit2;
    String Bundle3=fruit3;
}

Because of the type String in front of these assignments, you are declaring new local variables! This means that the fields of your class:

private String Bundle1;
private String Bundle2;
private String Bundle3;

... are not ever given values. When you try to access them you get the exception you were seeing because they are NULL.

If you change the constructor to:

public Project8(String fruit1, String fruit2, String fruit3)
{
    Bundle1 = fruit1;
    Bundle2 = fruit2;
    Bundle3 = fruit3;
}

then your project will execute properly.

As an aside, there's a lot of ways you could reduce the length of your program, make things more concise, and repeat yourself less. I suggest once you've got it working you head over to Code Review which is a sister site to StackOverflow: they'll give you suggestions to improve. If you do decide to do that, drop me a comment on this answer!


问:
POST REST call on sharepoint 2013 send a 403 forbidden
I have one problem.

On a sharepoint 2013 there is one way to modify list for example with REST call.

So the get call are OK (read-only)
the post call to site/_api/contextinfo is ok i retrieve the token

but when i call another post (PUT) for example with X-RequestDigest and NTLM authentication i have this error :

{"error":{"code":"-2130575251, System.Runtime.InteropServices.COMException","message":{"lang":"en-US","value":"The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again."}}}

an Idea ?

答:
I'm not clear you are trying to access SharePoint Online or not, I assume your trying to access SharePoint online cause, you said you generate BinarySecurityToken.

Basically, you need to pass three values as a header in your RESTfull call.

rtFa as Cookies

FedAuth as Cookie

FormDigestValue as X-RequestDigest

In order to get rtFa & FedAuth you need to pass BinarySecurityToken to your SPO site, SPO single sign on process will genarate these authentication Cookies after validate your token.

This link will guide you to generate above mentioned values,
https://denuwanhimangahettiarachchi.blogspot.com/2017/03/generate-sharepoint-online-rest-api.html


问:
Open the same window.location.origin in a new tab without cache
Framework: Angular 1.4.8

I want to create a new tab which takes the same window.location.origin that the old tab has. But I want to ensure that data is loaded from the server and not from cache.

There is a method to open the new tab: window.open(window.location.origin).

But I can't find any option which disables cache in the API reference. I am looking for an option similar to forcedReload in the window.location.reload method.

答:
I came with the following solution:

```<code> ...
 browser.openNewCleanTab = function (forcedReload = true) {
   const openNewTab = function (url) {
     return new Promise ((resolve, reject) => {
       resolve(window.open(url));
     });
   };

   openNewTab(window.location.origin).then((newTab) => {
     newTab.location.reload(forcedReload);
   });
 };
</code>```

Basically, it opens a new tab and then reloads is with forcedRelod.

Body:
I came with the following solution:

 ...
 browser.openNewCleanTab = function (forcedReload = true) {
   const openNewTab = function (url) {
     return new Promise ((resolve, reject) => {
       resolve(window.open(url));
     });
   };

   openNewTab(window.location.origin).then((newTab) => {
     newTab.location.reload(forcedReload);
   });
 };

Basically, it opens a new tab and then reloads is with forcedRelod.


问:
AVPlayerLayer with alpha mask
Has anyone got a video playing on an AVPlayerLayer with an alpha channel?

If so, how is it possible? I've tried many different solutions including using pure alpha channel video, applying blend modes to the target layer and animating every frame myself. The only workable solution is the latter and it bogs the phone down too much.

答:
i use mask,

```<code>NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: file];

AVURLAsset* url = [AVURLAsset URLAssetWithURL:fileURL options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey]];

AVPlayerItem* pitem = [AVPlayerItem playerItemWithAsset:url1];
AVPlayer*player  = [AVPlayer playerWithPlayerItem:pitem1];

pv = [[PlayerView alloc] initWithFrame:CGRectMake(0,0, 100, 100)];
[pv setPlayer:player];

UIImageView*iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mask"]];
pv.layer.mask = iv.layer;
</code>```

mask is png-file with transparency.

Title: AVPlayerLayer with alpha mask

Body:
i use mask,

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: file];

AVURLAsset* url = [AVURLAsset URLAssetWithURL:fileURL options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey]];

AVPlayerItem* pitem = [AVPlayerItem playerItemWithAsset:url1];
AVPlayer*player  = [AVPlayer playerWithPlayerItem:pitem1];

pv = [[PlayerView alloc] initWithFrame:CGRectMake(0,0, 100, 100)];
[pv setPlayer:player];

UIImageView*iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mask"]];
pv.layer.mask = iv.layer;

mask is png-file with transparency.


问:
Spring Integration Migration from 3 to 4
I have multiple services (serviceA, ServiceB ..)using spring integration .  Each service is dependent upon other submodules(which again is using spring integration).

In most of our config xml files we have hard coded the version like below  :
              http://www.springframework.org/schema/integration/ws http://www.springframework.org/schema/integration/ws/spring-integration-ws-3.0.xsd

I have a task to migrate one service (ServiceA) from spring integration 3 to 4.
I changed the config files to use versionless aliases (e.g. spring-integration.xsd), but as this service is dependent on other services, it looks like I have to change all the dependent services also to spring integration 4.

Is there any other option ?

答:
I'm afraid it isn't possible if the dependency is on the code level. Spring Integration 3.0 is compatible with Spring Framework 4.x, but only if you don't use Messaging. In that case an old org.springframework.integration.Message isn't compatible with new org.springframework.messaging.Message.

See more info about migration in the Migration Guide.


问:
How to Change order of columns in gridview?
I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9  columns) with data from text file. Code is here:

```<code>public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
     {
        DataTable tbl = new DataTable();
        for (int col = 0; col < numberOfColumns; col++)
        tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

        string[] lines = File.ReadAllLines(filePath);
        List<string> ekran = new List<string>();
        foreach (string line in lines)
        {
            var cols = line.Split(',');
            DataRow dr = tbl.NewRow();
            for (int cIndex = 0; cIndex < 9; cIndex++)
            {
                if (cols[cIndex].Contains('_'))
                {
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
                else
                {
                    cols[cIndex] += '_';
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
            }
            for (int cIndex = 0; cIndex < 9;cIndex++ )
                if (dr[cIndex].ToString() == promenljiva)
                    tbl.Rows.Add(dr);
        }

        this.GridView1.DataSource = tbl;
        this.GridView1.DataBind();

        return tbl;
    }
</code>```

After that i have this:

```<code>ConvertToDataTable(filePath, 9);
</code>```

This is gridview:

```<code><asp:GridView ID="GridView1" runat="server"></asp:GridView>
</code>```

How can i do that?

答:
For further reading, it's discussed in detail here!

https://www.codeproject.com/Questions/711397/How-to-Change-order-of-columns-in-gridview

How to reorder columns in gridview dynamically

Then some add/remove column pieces with "geekwithblogs" site
http://geekswithblogs.net/dotNETvinz/archive/2009/06/03/move--autogenerate-columns-at-leftmost-part-of-the-gridview.aspx

Body:
I want to change order of gridview columns (8th to be first, first to be second, second to be third...). I am filling my gridview (which has 9  columns) with data from text file. Code is here:

public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
     {
        DataTable tbl = new DataTable();
        for (int col = 0; col < numberOfColumns; col++)
        tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

        string[] lines = File.ReadAllLines(filePath);
        List<string> ekran = new List<string>();
        foreach (string line in lines)
        {
            var cols = line.Split(',');
            DataRow dr = tbl.NewRow();
            for (int cIndex = 0; cIndex < 9; cIndex++)
            {
                if (cols[cIndex].Contains('_'))
                {
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
                else
                {
                    cols[cIndex] += '_';
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
            }
            for (int cIndex = 0; cIndex < 9;cIndex++ )
                if (dr[cIndex].ToString() == promenljiva)
                    tbl.Rows.Add(dr);
        }

        this.GridView1.DataSource = tbl;
        this.GridView1.DataBind();

        return tbl;
    }

After that i have this:

ConvertToDataTable(filePath, 9);

This is gridview:

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

How can i do that?


答:
I guess you only need the task_id not the row?

```<code>SELECT task_id
FROM yourTable
GROUP BY task_id
HAVING COUNT(CASE WHEN old_status = 'Resolved' THEN 1 END) = 0
   AND COUNT(CASE WHEN new_status_id = 'Completed' THEN 1 END) = 1
</code>```

Now if you want all the record involve on those "incomplete" tasks

```<code>WITH cte as (
    SELECT task_id
    FROM yourTable
    GROUP BY task_id
    HAVING COUNT(CASE WHEN old_status = 'Resolved' THEN 1 END) = 0
       AND COUNT(CASE WHEN new_status_id = 'Completed' THEN 1 END) = 1
)
SELECT *
FROM yourTable Y
JOIN cte C
  ON Y.task_id = C.task_id
</code>```

Body:
I want to find records in SQL Server which are marked as completed but they do not go through resolved state.

Here is the example below.

tracking_id task_id task status   old_status new_status_id
1195372     140717  ABC  Complete NULL       NULL
1195373     140717  ABC  Complete NULL       New
1195374     140717  ABC  Complete New        Completed
1195380     140718  XYZ  Complete NULL       NULL
1195381     140718  XYZ  Complete NULL       New
1195382     140718  XYZ  Complete New        Completed
1195383     140719  PQR  Complete NULL       NULL
1195384     140719  PQR  Complete NULL       Resolved
1195385     140719  PQR  Complete Resolved   Completed

Now in the table as task_id 140717 and 140718 is marked as Completed but it never went to state Resolved. Where as task_id 140719 is also marked completed but it goes through state Resolved. So I want to write SQL Query to just get record with task_id 140717 and 140718.

Any help with how to write query for this will be appreciated.

Body:
I guess you only need the task_id not the row?

SELECT task_id
FROM yourTable
GROUP BY task_id
HAVING COUNT(CASE WHEN old_status = 'Resolved' THEN 1 END) = 0
   AND COUNT(CASE WHEN new_status_id = 'Completed' THEN 1 END) = 1

Now if you want all the record involve on those "incomplete" tasks

WITH cte as (
    SELECT task_id
    FROM yourTable
    GROUP BY task_id
    HAVING COUNT(CASE WHEN old_status = 'Resolved' THEN 1 END) = 0
       AND COUNT(CASE WHEN new_status_id = 'Completed' THEN 1 END) = 1
)
SELECT *
FROM yourTable Y
JOIN cte C
  ON Y.task_id = C.task_id


问:
RewriteRule not matching?
I have this in my .htaccess:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</code>```

Why does http://mydomain.ext/url/http://www.google.com/ not match the first rule, but the second???

Edit: it seems to work when I comment out the last line, but of course i cannot do that. What's going on?

Edit2: If i change it to this it works:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
</code>```

Can anyone explain why the previous version didn't work as expected?

答:
Probably because the "start of line anchor": "^" that matches URLs starting with "url/".

Try a "^.*url/(.*)$", for example.

Title: RewriteRule not matching?

Body:
I have this in my .htaccess:

RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Why does http://mydomain.ext/url/http://www.google.com/ not match the first rule, but the second???

Edit: it seems to work when I comment out the last line, but of course i cannot do that. What's going on?

Edit2: If i change it to this it works:

RewriteEngine On
RewriteBase /
RewriteRule ^url/(.*)$ url.php?url=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

Can anyone explain why the previous version didn't work as expected?


问:
VBA excel seems unable to read non latin cell values
My VBA excell application needs to read non-latin cell values:
someString = Cells(1,1).value
when I analyse the hex content of someString, it contains only a sequence of "3F", i.e. question marks.
I need to obtain the original unicode string. When I copy the non-latin cell value into ultra-edit then the information is correctly copied</p>

答:
Found the solution here

au crypto website has vba code that does the job


问:
Parse TSQL scripts and return table and column usage
we are currently involved in a data migration project, for which we have to analyze data usage, meaning we need to figure out which tables and columns are used and need to be migrated and which data is obsolete.
We not only have many SSRS reports based on stored procedures, we also have hundreds if not thousands of TSQL scripts used for ad hoc analyzes. Analyzing them one by one by hand is virtually impossible.

I looked for a way to parse these scripts and return the data used by the scripts. I managed to write a macro in EditPad which extracts tables from a script, but I failed to do the same for columns. The main problems here are aliases, CTEs and even distinguishing column names in the script from other commands.

In contrast to a simple regex based macro, SQL Server must have a clear idea which columns are used by the script -> Execution plan.
Is there any way we could use this capability for our purposes? Or even better: is there any third party tool that could do what we need? So far, I could not find anything.

Thx very much for any advice!

答:
A partial answer:

Based on this article, it's possible to use PowerShell (or a compiled .Net language) to use the Microsoft.SqlServer.Management.SqlParser to generate the parse tree for a SQL statement as used by Microsoft tools.

```<code>[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.SqlParser") | Out-Null
$ParseOptions = New-Object Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions
$ParseOptions.BatchSeparator = 'GO'
$ParseOptions.CompatibilityLevel = [Microsoft.SqlServer.Management.SqlParser.Common.DatabaseCompatibilityLevel]::Current
$ParseOptions.IsQuotedIdentifierSet = $true
$ParseOptions.TransactSqlVersion= [Microsoft.SqlServer.Management.SqlParser.Common.TransactSqlVersion]::Current

set-psdebug -strict

#$SQL=get-content $Args[0] |foreach-object{"$_`n"}

$SQL = "SELECT  c.COLUMN_NAME,
        c.TABLE_NAME,
        t.TABLE_SCHEMA,
        t.TABLE_TYPE,
        t.TABLE_NAME AS t2
FROM INFORMATION_SCHEMA.TABLES AS t
JOIN INFORMATION_SCHEMA.COLUMNS AS c
ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_CATALOG = t.TABLE_CATALOG
"

$Script=[Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions)

$flags = [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic
$Script.GetType().GetProperty("Script", $flags).GetValue($Script).Xml
</code>```

I have a local version of SSMS 2016 and SQL Server 2014 installed, and this worked without installing anything else.

This still leaves quite a lot of work to do in terms of interpreting the tree, but you might be able to make use of it.

Body:
A partial answer:

Based on this article, it's possible to use PowerShell (or a compiled .Net language) to use the Microsoft.SqlServer.Management.SqlParser to generate the parse tree for a SQL statement as used by Microsoft tools.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.SqlParser") | Out-Null
$ParseOptions = New-Object Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions
$ParseOptions.BatchSeparator = 'GO'
$ParseOptions.CompatibilityLevel = [Microsoft.SqlServer.Management.SqlParser.Common.DatabaseCompatibilityLevel]::Current
$ParseOptions.IsQuotedIdentifierSet = $true
$ParseOptions.TransactSqlVersion= [Microsoft.SqlServer.Management.SqlParser.Common.TransactSqlVersion]::Current

set-psdebug -strict

#$SQL=get-content $Args[0] |foreach-object{"$_`n"}

$SQL = "SELECT  c.COLUMN_NAME,
        c.TABLE_NAME,
        t.TABLE_SCHEMA,
        t.TABLE_TYPE,
        t.TABLE_NAME AS t2
FROM INFORMATION_SCHEMA.TABLES AS t
JOIN INFORMATION_SCHEMA.COLUMNS AS c
ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_CATALOG = t.TABLE_CATALOG
"

$Script=[Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions)

$flags = [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic
$Script.GetType().GetProperty("Script", $flags).GetValue($Script).Xml

I have a local version of SSMS 2016 and SQL Server 2014 installed, and this worked without installing anything else.

This still leaves quite a lot of work to do in terms of interpreting the tree, but you might be able to make use of it.


问:
How can I restore the "default" button style
I have a save button, and when the user mouses over it, I change some styles - for example:

```<code>$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});
</code>```

When the mouse leaves the button, I would like to restore the original:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});
</code>```

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

答:
I would suggest not to set the properties directly, but set a class/classes instead:

```<code>$('.saveButton').mouseover(function() {
   $(this).addClass('highlight');
   $(this).parents('fieldset').addClass('highlight');
}).mouseout(function() {
   $(this).removeClass('highlight');
   $(this).parents('fieldset').removeClass('highlight');
});
</code>```

With

```<code>.saveButton.highlight { /* Double class selector is broken in IE6 */
   background-color: red;
}

fieldset.highlight {
  border: 1px solid red;
}
</code>```

If for some reason you don't want to do that, instead of setting the properities to a specfic value, but to an empty string. That should "remove" that property:

```<code>$('.saveButton').mouseout(function() {
   $(this).css("background-color", "");
   $(this).parents('fieldset').css("border", "");
});
</code>```

Body:
I have a save button, and when the user mouses over it, I change some styles - for example:

$('.saveButton').mouseover(function() {
   $(this).css("background-color", "red");
   $(this).parents('fieldset').css("border", "2px solid red");
});

When the mouse leaves the button, I would like to restore the original:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "#EEE");
   $(this).parents('fieldset').css("border", "1px solid gray");
});

However, leaving aside the matter of whether or not the default button background color is #EEE, when this code executes the button loses its rounded look, and has square corners.

Is it possible to do this?

Body:
I would suggest not to set the properties directly, but set a class/classes instead:

$('.saveButton').mouseover(function() {
   $(this).addClass('highlight');
   $(this).parents('fieldset').addClass('highlight');
}).mouseout(function() {
   $(this).removeClass('highlight');
   $(this).parents('fieldset').removeClass('highlight');
});

With

.saveButton.highlight { /* Double class selector is broken in IE6 */
   background-color: red;
}

fieldset.highlight {
  border: 1px solid red;
}

If for some reason you don't want to do that, instead of setting the properities to a specfic value, but to an empty string. That should "remove" that property:

$('.saveButton').mouseout(function() {
   $(this).css("background-color", "");
   $(this).parents('fieldset').css("border", "");
});