问:
Beginner in matlab : syntax to recup value of a line matrice
i'm beginner in MATLAB. My problem is :
When i want to take the value of the line in my matrice L(1x2) to stock it in the a and b variables, I tried to use the following code

```<code>[a,b]=L;
</code>```

It didn't work well. I don't understand why it's not possible like this. I used this syntax for the line ginput(n). I used another method to take the value but I want to understand my error in the code above.
My final code is this :

```<code>clf();
n=10;
axis([0 10 0 10]);
[px,py] = ginput(n);
Y = py';
X = ones(1,n);
X=[X ; px'];
L= Y*pinv(X);
a = L(1,1);
b = L(1,2);
x = 0:0.2:10;
plot(x,b*x+a, px,py,'r+');
grid;
</code>```

Thanks a lot

答:
You cannot assign in MATLAB using

```<code>[a,b]=L
</code>```

Instead, you can do the following:

```<code>L=[1,2];
L=num2cell(L);
[a,b]=deal(L{:});
</code>```

Then a=1 and b=2.

Body:
i'm beginner in MATLAB. My problem is :
When i want to take the value of the line in my matrice L(1x2) to stock it in the a and b variables, I tried to use the following code

[a,b]=L;

It didn't work well. I don't understand why it's not possible like this. I used this syntax for the line ginput(n). I used another method to take the value but I want to understand my error in the code above.
My final code is this :

clf();
n=10;
axis([0 10 0 10]);
[px,py] = ginput(n);
Y = py';
X = ones(1,n);
X=[X ; px'];
L= Y*pinv(X);
a = L(1,1);
b = L(1,2);
x = 0:0.2:10;
plot(x,b*x+a, px,py,'r+');
grid;

Thanks a lot

Body:
You cannot assign in MATLAB using

[a,b]=L

Instead, you can do the following:

L=[1,2];
L=num2cell(L);
[a,b]=deal(L{:});

Then a=1 and b=2.


来源: stackexchange

问:
Previous month datetime pandas
I have a datetime instance declared as follows:

```<code>dtDate = datetime.datetime(2016,1,1,0,0)
</code>```

How do I get the previous month and previous year from dtDate?

e.g. something like:

```<code>dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)
</code>```

答:
You can use DateOffset:

```<code>In [32]:
dtDate = dt.datetime(2016,1,1,0,0)
dtDate - pd.DateOffset(months=1)

Out[32]:
Timestamp('2015-12-01 00:00:00')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Previous month datetime pandas

Body:
I have a datetime instance declared as follows:

dtDate = datetime.datetime(2016,1,1,0,0)

How do I get the previous month and previous year from dtDate?

e.g. something like:

dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)

Body:
You can use DateOffset:

In [32]:
dtDate = dt.datetime(2016,1,1,0,0)
dtDate - pd.DateOffset(months=1)

Out[32]:
Timestamp('2015-12-01 00:00:00')


问:
Accessing super class variables/methods in sub class
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?</p>

```<code>public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}
</code>```

答:
If you want the Dog class to have the var attribute set by default, you can use the constructor:

```<code>public class Dog extends Animal {

    public Dog() {
        this.var=10;
    }
}
</code>```

or use:

```<code>Dog dog = new Dog();
dog.var=11;
</code>```

Body:
Since subclass can access super class's variables and methods defined as protected, why following code gives compile error?

public class Animal {
    protected int var;

    public void eat() {
        System.out.println("Animal eating");
    }
}
class Dog extends Animal {
    Animal an = new Animal();
    an.var = 10;
}

Body:
If you want the Dog class to have the var attribute set by default, you can use the constructor:

public class Dog extends Animal {

    public Dog() {
        this.var=10;
    }
}

or use:

Dog dog = new Dog();
dog.var=11;


问:
ORA-01843: not a valid month
I am creating a dynamic query using  procedure. The input parameter is of timestamp data type.

```<code>create or replace PROCEDURE TEST
(p_party_eff_dt_in mina_owner.party_to_party.effective_two_dt%TYPE)

select to_timestamp(p_party_eff_dt_in,'mm/dd/yyyy HH24:MI:SS.FF3') from <table>
</code>```

gives the following error

ORA-01843: not a valid month

Please help

Edit:

```<code>P_PARTY_EFF_DT_IN :='03-JUL-04 04.34.50.198000000 AM'; –
</code>```

答:
You are using a format mask that does not match your input string.

Assuming that in '03-JUL-04' '03' is the day and '04' stays for 2004, you need:

```<code>select to_timestamp('03-JUL-04 04.34.50.198000000 AM', 'dd-mon-yy hh.mi.ss.FF9 PM') from dual
</code>```

Title: ORA-01843: not a valid month

Body:
I am creating a dynamic query using  procedure. The input parameter is of timestamp data type.

create or replace PROCEDURE TEST
(p_party_eff_dt_in mina_owner.party_to_party.effective_two_dt%TYPE)

select to_timestamp(p_party_eff_dt_in,'mm/dd/yyyy HH24:MI:SS.FF3') from

gives the following error

ORA-01843: not a valid month

Please help

Edit:

P_PARTY_EFF_DT_IN :='03-JUL-04 04.34.50.198000000 AM'; –

Body:
You are using a format mask that does not match your input string.

Assuming that in '03-JUL-04' '03' is the day and '04' stays for 2004, you need:

select to_timestamp('03-JUL-04 04.34.50.198000000 AM', 'dd-mon-yy hh.mi.ss.FF9 PM') from dual


问:
Syntax to set color of LED in sense-hat using nodered
I am working on sense-hat using node-red. I found that, to set the four corners of the display to red, green (#00ff00), yellow and blue (0,0,255):

0,0,red,0,7,#00ff00,7,7,yellow,7,0,0,0,255

But how to set color for 2 leds in column 2 and 3 of the LED panel in rows 2-7.

Can anyone please suggest me in this?

答:
The sidebar help for the SenseHAT node describes the required syntax:

```<code>Format: <x>,<y>,<colour>

x and y must either be a value from 0 to 7,
a * to indicate the entire row or column,
or a range such as 3-6.
</code>```

But how to set color for 2 leds in column 2 and 3 of the LED panel in rows 2-7.

If you want to set just two leds within those ranges then just pick two X/Y values within that range and set them.

```<code>2,2,red,2,3,red
</code>```

Body:
The sidebar help for the SenseHAT node describes the required syntax:

Format: <x>,<y>,<colour>

x and y must either be a value from 0 to 7,
a * to indicate the entire row or column,
or a range such as 3-6.

But how to set color for 2 leds in column 2 and 3 of the LED panel in rows 2-7.

If you want to set just two leds within those ranges then just pick two X/Y values within that range and set them.

2,2,red,2,3,red


问:
Distinct() returns duplicates with a user-defined type
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

```<code>class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}
</code>```

答: You need to implement GetHashCode().</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}

Body: You need to implement GetHashCode().


问:
Multiple validations occurring with Eclipse Neon even though it is been disabled
Im having a serious problem with Eclipse Neon and in every save/click on the file/building files it shows up validation. By referring to various blogs, the below are the set up done by me on validations. But still I have same issue. Please suggest me whether this set up is correct.</p>

```<code>1) Set up done in Windows-> Preferences -> Validations
    a) Set the checkbox for 'Allow projects to override these preference settings'
    b) Set the check box for 'Suspend all validators'
    c) Rest all the check boxes are unset especially DTD validator, XML Schema Validator and XML Validator are individually deselected.
2) Build Automatically was deselected and verified, but the same situation occured. For the current set up I have enabled it again.
</code>```

答:
I followed the below steps and got this issue resolved,</p>

```<code>1) Taken help from this link: [https://github.com/nokia/RED/issues/31][1]
2) Followed this link, [http://stackoverflow.com/questions/15333825/an-error-has-occured-please-see-log-file-eclipse-juno][1]
3) Deleted *.snap files in Java Workspace->.metadata->.plugins
4) Out of Memory Issue in Eclipse:
   a) Followed this link : [https://www.youtube.com/watch?v=WYtH5yJRz5s @phcharbonneau@hotmail.com][1]
   b) Heap size provided: -Xms512m -Xmx1152m -XX:MaxPermSize=256m -XX:MaxNewSize=256m
   c) Deleted duplicate JRE files(older version)
   d) After Set Up, Restart the system.
</code>```

Body:
Im having a serious problem with Eclipse Neon and in every save/click on the file/building files it shows up validation. By referring to various blogs, the below are the set up done by me on validations. But still I have same issue. Please suggest me whether this set up is correct.

1) Set up done in Windows-> Preferences -> Validations
    a) Set the checkbox for 'Allow projects to override these preference settings'
    b) Set the check box for 'Suspend all validators'
    c) Rest all the check boxes are unset especially DTD validator, XML Schema Validator and XML Validator are individually deselected.
2) Build Automatically was deselected and verified, but the same situation occured. For the current set up I have enabled it again.

Body:
I followed the below steps and got this issue resolved,

1) Taken help from this link: [https://github.com/nokia/RED/issues/31][1]
2) Followed this link, [http://stackoverflow.com/questions/15333825/an-error-has-occured-please-see-log-file-eclipse-juno][1]
3) Deleted *.snap files in Java Workspace->.metadata->.plugins
4) Out of Memory Issue in Eclipse:
   a) Followed this link : [https://www.youtube.com/watch?v=WYtH5yJRz5s @phcharbonneau@hotmail.com][1]
   b) Heap size provided: -Xms512m -Xmx1152m -XX:MaxPermSize=256m -XX:MaxNewSize=256m
   c) Deleted duplicate JRE files(older version)
   d) After Set Up, Restart the system.


问:
Hash mismatch (integrity check failed) with Azure Blob Storage
I'm following http://willi.am/blog/2014/07/03/azure-blob-storage-and-node-downloading-blobs/.

However despite the exact same code, when I download blobs Azure gives the error:

[Error: Hash mismatch (integrity check failed), Expected value is ...]

The line being run is  blobService.getBlobToText, with blobService being the connection to Azure (createBlobService...)

What's going on? :S

My code's below:

```<code>    // Azure test
    function downloadImageAsText(blobService, containerName, blobName) {

         blobService.getBlobToText(
              containerName,
              blobName,
              function(err, blobContent, blob) {
                  if (err) {
                      console.error("Couldn't download blob %s", blobName);
                      console.error(err);
                  } else {
                      console.log("Sucessfully downloaded blob %s", blobName);
                      console.log(blobContent);
                  }
              });

    }

    function uploadImage(blobService, containerName, blobName, fileName) {

      blobService.getBlobProperties(
        containerName,
        blobName,
        function(err, properties, status) {
            if (status.isSuccessful) {
                // Blob exists
            } else {
                blobService.createBlockBlobFromLocalFile(
                    containerName,
                    blobName,
                    fileName,
                    function(error, result, response){
                        if(error){
                            console.log("Couldn't upload file %s", fileName);
                            console.error(error);
                        } else {
                            console.log('File %s uploaded successfully', fileName);
                            downloadImageAsText(blobService, containerName, blobName);
                        }
                    });
            }
        });
    }

    function testAzure() {

      accountName / hash = my details

      var storage = require('azure-storage');
      var blobService = storage.createBlobService(accountName, hash);
      var containerName = 'tst';
      var blobName = 'test.png';
      var fileName = 'test.png';

      blobService.createContainerIfNotExists(containerName, function(err, result, response) {
          if (err) {
              console.log("Couldn't create container %s", containerName);
              console.error(err);
          } else {
              if (result) {
                  console.log('Container %s created', containerName);
                  uploadImage(blobService, containerName, blobName, fileName);
              } else {
                  console.log('Container %s already exists', containerName);
                  uploadImage(blobService, containerName, blobName, fileName);
              }
          }
      });
    }

    function startServer() {
      http = require('http');
      const PORT = 8080;
      var server = http.createServer(handleRequest);
      server.on('listening',function(){
        console.log("Server listening on: http://178.62.117.207:%s", PORT);
      });
      server.listen(PORT);
    }

    startServer();
    testAzure();
</code>```

答: In case someone else runs into this; happens when you store a Buffer object but retrieve a string.

Body:
I'm following http://willi.am/blog/2014/07/03/azure-blob-storage-and-node-downloading-blobs/.

However despite the exact same code, when I download blobs Azure gives the error:

[Error: Hash mismatch (integrity check failed), Expected value is ...]

The line being run is  blobService.getBlobToText, with blobService being the connection to Azure (createBlobService...)

What's going on? :S

My code's below:

    // Azure test
    function downloadImageAsText(blobService, containerName, blobName) {

         blobService.getBlobToText(
              containerName,
              blobName,
              function(err, blobContent, blob) {
                  if (err) {
                      console.error("Couldn't download blob %s", blobName);
                      console.error(err);
                  } else {
                      console.log("Sucessfully downloaded blob %s", blobName);
                      console.log(blobContent);
                  }
              });

    }

    function uploadImage(blobService, containerName, blobName, fileName) {

      blobService.getBlobProperties(
        containerName,
        blobName,
        function(err, properties, status) {
            if (status.isSuccessful) {
                // Blob exists
            } else {
                blobService.createBlockBlobFromLocalFile(
                    containerName,
                    blobName,
                    fileName,
                    function(error, result, response){
                        if(error){
                            console.log("Couldn't upload file %s", fileName);
                            console.error(error);
                        } else {
                            console.log('File %s uploaded successfully', fileName);
                            downloadImageAsText(blobService, containerName, blobName);
                        }
                    });
            }
        });
    }

    function testAzure() {

      accountName / hash = my details

      var storage = require('azure-storage');
      var blobService = storage.createBlobService(accountName, hash);
      var containerName = 'tst';
      var blobName = 'test.png';
      var fileName = 'test.png';

      blobService.createContainerIfNotExists(containerName, function(err, result, response) {
          if (err) {
              console.log("Couldn't create container %s", containerName);
              console.error(err);
          } else {
              if (result) {
                  console.log('Container %s created', containerName);
                  uploadImage(blobService, containerName, blobName, fileName);
              } else {
                  console.log('Container %s already exists', containerName);
                  uploadImage(blobService, containerName, blobName, fileName);
              }
          }
      });
    }

    function startServer() {
      http = require('http');
      const PORT = 8080;
      var server = http.createServer(handleRequest);
      server.on('listening',function(){
        console.log("Server listening on: http://178.62.117.207:%s", PORT);
      });
      server.listen(PORT);
    }

    startServer();
    testAzure();


问:
How do I get the unix epoch from Oracle date?
Does anyone have a better AND faster solution on getting the unix epoch timestamp using Oracle SQL than this?:

```<code>SQL> select (cast(sysdate as date) - cast(to_date('1970-01-01', 'YYYY-MM-DD') as date)) * 86400 as unixepoch from dual;

 UNIXEPOCH
----------
1490789604;
</code>```

Oneliner preferred ;)

答:
You do not need to cast the values as dates, since they are already dates.</p>

```<code>SELECT ( SYSDATE - DATE '1970-01-01' ) * 86400 AS unixepoch
FROM   DUAL;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Does anyone have a better AND faster solution on getting the unix epoch timestamp using Oracle SQL than this?:

SQL> select (cast(sysdate as date) - cast(to_date('1970-01-01', 'YYYY-MM-DD') as date)) * 86400 as unixepoch from dual;

 UNIXEPOCH
----------
1490789604;

Oneliner preferred ;)

Body:
You do not need to cast the values as dates, since they are already dates.

SELECT ( SYSDATE - DATE '1970-01-01' ) * 86400 AS unixepoch
FROM   DUAL;


问:
Identifier expected but integer literal found
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

```<code>    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)
</code>```

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!

答: Scala does not use the ternary operator, http://alvinalexander.com/scala/scala-ternary-operator-syntax</p>

Body:
I got this problem when writing a recursive function that calculates the number of points where two general functions f1 and f2 are equal(Assuming only Integer values).

    object X1 {
    def numEqual(f1:Int=>Int,f2:Int=>Int)(a:Int,b:Int):Int=
    if(a>b) 0
    else f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b):0+numEqual(f1,f2)(a+1,b)

And this is what compiler says :

X1.scala:5: error: identifier expected but integer literal found.
              f1(a)==f2(a) ? 1+numEqual(f1,f2)(a+1,b) : 0+numEqual(f1,f2)(a+1,b)
                                                                  ^
  one error found.

Thank you!


问:
Android and XMPP: Currently available solutions
Which XMPP library would be the best choice nowadays for Android development?

I've been using the patched Smack
library as is
suggested in many other questions
here in SO. However, that's a patched version of
the Smack API from two years ago. And
although it generally works well I'm
exploring any other, more recent
options.

I've been looking at the official
Smack API and after a little
research, it seems it might work just
fine nowadays (although I have not
tried it yet in a real application).

There's also another solution I came
across, Beem's aSMACK library.
Beem is a fairly new XMPP client for
android and from what I understand
they are using their own patched
version of aSMACK.

Finally, there's aSMACK but that
too hasn't been updated for quite
some time (as the site suggests).

Do you have any other suggestions or can you explain why I should choose one of the above over the rest?

答:
Using Smack 4.1 Readme and Upgrade Guide

Using Android studio 2.3, Recently I have implemented a demo in a very simple way.

-> Just Add gradle dependency in app level gradle as below

```<code>compile "org.igniterealtime.smack:smack-tcp:4.1.0"

// Optional for XMPPTCPConnection

compile "org.igniterealtime.smack:smack-android-extensions:4.1.0"
</code>```

-> Configure Connection Configuration

    NOTE : Call this in AsyncTask or in other background thread

```<code> XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword("Your Username here", "Your Password here")
                    .setHost("Host name here")
                    .setServiceName("Your service name here")
                    .setPort(Your port number here)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) //Disable or enable as per development mode
                    .setDebuggerEnabled(true) // to view what's happening in detail
                    .build();
</code>```

-> Use isConnected() and  isAuthenticated()

-> Use ChatManager for add chatListener.

Body:
Using Smack 4.1 Readme and Upgrade Guide

Using Android studio 2.3, Recently I have implemented a demo in a very simple way.

-> Just Add gradle dependency in app level gradle as below

compile "org.igniterealtime.smack:smack-tcp:4.1.0"

// Optional for XMPPTCPConnection

compile "org.igniterealtime.smack:smack-android-extensions:4.1.0"

-> Configure Connection Configuration

    NOTE : Call this in AsyncTask or in other background thread

 XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword("Your Username here", "Your Password here")
                    .setHost("Host name here")
                    .setServiceName("Your service name here")
                    .setPort(Your port number here)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) //Disable or enable as per development mode
                    .setDebuggerEnabled(true) // to view what's happening in detail
                    .build();

-> Use isConnected() and  isAuthenticated()

-> Use ChatManager for add chatListener.


问:
Try-catch doesn't wait for async function inside
What I'm trying to do is, after retrying to download file for 5 times in case if download was not successful for some reason, to reset the whole process and turn back to first step: function Try(). If success, then to proceed ProcessSet(3); line

But in my situation, it starts download and without waiting, goes to ProcessSet(3); line.

What am I doing wrong? why next steps after try doesn't wait for await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path); to finish?

Here is the code:

```<code>using (WebClient webClient = new WebClient())
{
    webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

    try
    {
        await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path);
    }
    catch (Exception e)
    {
        Thread.Sleep(DelayOnRetry);
        Try();
    }
}
SetProgressBar(40, ProgressBarStyle.Continuous);
ProcessSet(3);
</code>```

And here is the Try() function

```<code>private void Try()
{
    ClearFolder(root_dir);
    Directory.CreateDirectory(root_dir);
    main_timer.Enabled = false;
    ProcessSet(1);
}
</code>```

Here is the whole code:

https://gist.github.com/turalus/8c781b5b0c56f66f7ec17e66a3e120fc

答:
if you use C# 6+,
make your Try() method signature as async and invoke with await.

Otherwise you need to change the logic with a simple boolean as @Denis Krasakov suggested.

Body:
What I'm trying to do is, after retrying to download file for 5 times in case if download was not successful for some reason, to reset the whole process and turn back to first step: function Try(). If success, then to proceed ProcessSet(3); line

But in my situation, it starts download and without waiting, goes to ProcessSet(3); line.

What am I doing wrong? why next steps after try doesn't wait for await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path); to finish?

Here is the code:

using (WebClient webClient = new WebClient())
{
    webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

    try
    {
        await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path);
    }
    catch (Exception e)
    {
        Thread.Sleep(DelayOnRetry);
        Try();
    }
}
SetProgressBar(40, ProgressBarStyle.Continuous);
ProcessSet(3);

And here is the Try() function

private void Try()
{
    ClearFolder(root_dir);
    Directory.CreateDirectory(root_dir);
    main_timer.Enabled = false;
    ProcessSet(1);
}

Here is the whole code:

https://gist.github.com/turalus/8c781b5b0c56f66f7ec17e66a3e120fc


问:
Remove first two quotes from lines more than 20 characters long
I've not written any VBA for a few years so am rusty and would apprecite some help.

I have a file with around 9k lines of text, I need a script that will go through and remove the first two quotation marks from any rows with more than 20 characters.

How can I do that?

Update:

I have this that picks out the rows with more than 20 chars but not sure how to remove the first two quotes:

```<code>Sub Sanitise()

Dim sh As Worksheet
Dim rw As Range

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

    If Len(sh.Cells(rw.Row, 1).Value) > 20 Then
    ' Need to remove the first two quotes
    End If

Next rw

End Sub
</code>```

Data:

A00,408,"UXS",201309,10X641,00110 U02,99400,"200X601","E","N","38418","       064X09","00","","","","","
  ","","","E","","" S72,"MXRE0042" S72,"MRE0047" S72,"MRE0047"
  U02,7514100,"201613","E","N","66620","

  21011X","00","","","","","  ","","","E","","" S72,"MRE00432"
  S72,"MRE00457" S72,"MRE00417" U02,7513770602,"20X12","E","N","40761","
  12775X","00","","","","","  ","","","E","","" S72,"MRE00432"
  S72,"MRE00X47" S72,"MRE004X7"

答:
Something like this will go through Column A and use a variant array to remove the first two " in strings longer than 20 characters.

The code dumps the updated strings to Column B.

```<code>Sub CrankyKohli()
Dim rng1 As Range
Dim lngCnt As Long
Dim x

Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))
x = rng1.Value

For lngCnt = 1 To UBound(x)
    If Len(x(lngCnt, 1)) > 20 Then x(lngCnt, 1) = Replace(x(lngCnt, 1), """", vbNullString, , 2)
Next

rng1.Offset(0, 1) = x

End Sub
</code>```

Body:
I've not written any VBA for a few years so am rusty and would apprecite some help.

I have a file with around 9k lines of text, I need a script that will go through and remove the first two quotation marks from any rows with more than 20 characters.

How can I do that?

Update:

I have this that picks out the rows with more than 20 chars but not sure how to remove the first two quotes:

Sub Sanitise()

Dim sh As Worksheet
Dim rw As Range

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

    If Len(sh.Cells(rw.Row, 1).Value) > 20 Then
    ' Need to remove the first two quotes
    End If

Next rw

End Sub

Data:

A00,408,"UXS",201309,10X641,00110 U02,99400,"200X601","E","N","38418","       064X09","00","","","","","
  ","","","E","","" S72,"MXRE0042" S72,"MRE0047" S72,"MRE0047"
  U02,7514100,"201613","E","N","66620","

  21011X","00","","","","","  ","","","E","","" S72,"MRE00432"
  S72,"MRE00457" S72,"MRE00417" U02,7513770602,"20X12","E","N","40761","
  12775X","00","","","","","  ","","","E","","" S72,"MRE00432"
  S72,"MRE00X47" S72,"MRE004X7"

Body:
Something like this will go through Column A and use a variant array to remove the first two " in strings longer than 20 characters.

The code dumps the updated strings to Column B.

Sub CrankyKohli()
Dim rng1 As Range
Dim lngCnt As Long
Dim x

Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))
x = rng1.Value

For lngCnt = 1 To UBound(x)
    If Len(x(lngCnt, 1)) > 20 Then x(lngCnt, 1) = Replace(x(lngCnt, 1), """", vbNullString, , 2)
Next

rng1.Offset(0, 1) = x

End Sub


问:
Connection terminated parsing multipart data in Angulrjs and JAX-RS
I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.

-Code HTML:

```<code><form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label>
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
 <input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>
</code>```

--code AngularJS;

```<code>var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        //fd.append('file', file);
       angular.forEach(file, function(file) {
            fd.append('file', file);
        });

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            console.log("done post "+response);
    }).catch(function(e) {
        console.log('failed to post: ', e);
        throw e;
    })

    }
}]);
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);
        var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
        fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"

var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };
</code>```

-After a test of the "uploadfile ()", I get the following results:

```<code>//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File
</code>```

-Test of upload file:

```<code>//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object
</code>```

答:
Try this:

```<code>this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);

    //Comment below
    //angular.forEach(file, function(file) {
    //  fd.append('file', file);
    //});

    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}
</code>```

See the answers here which accepts multiple files within one object 'file'.

Body:
I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.

-Code HTML:

<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
Image:
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
 <input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>

--code AngularJS;

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        //fd.append('file', file);
       angular.forEach(file, function(file) {
            fd.append('file', file);
        });

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            console.log("done post "+response);
    }).catch(function(e) {
        console.log('failed to post: ', e);
        throw e;
    })

    }
}]);
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);
        var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
        fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"

var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };

-After a test of the "uploadfile ()", I get the following results:

//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File

-Test of upload file:

//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object

Body:
Try this:

this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);

    //Comment below
    //angular.forEach(file, function(file) {
    //  fd.append('file', file);
    //});

    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}

See the answers here which accepts multiple files within one object 'file'.


问:
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?

答: For any significant project, I generally have a supervisor actor, a collection of worker actors each of which can do any work necessary, and a large number of pieces of work to do.  Even though I do this fairly often, I've never put it in a (personal) library because the operations end up being so different each time, and the overhead is pretty small compared to the whole coding project.</p>

Title: Using Actors to exploit cores


问:
Push Xcode Project to TFS Git repository
Trying to push Xcode project to TFS (Git repository), i created local repository for my project in Xcode, then install Git Credential Manager from GitHub, then trying to connect repository from Xcode by adding remote or connect to git repository, but the error message is "Authentication failed because the authentication credentials were rejected."
Would you please provide me with the correct steps.
Knowing that TFS 2015 & Xcode 8.2</p>

答:
TFS 2017 offers you SSH access. The earlier versions, like 2015, requires to setup SSL and Basic Authentication on the server. I guess that this is not properly configured for you.

The steps to setup SSL are described in details in the docs.
Here you can find what is required to configure Basic Authentication.

A couple of caveats:

username should be entered in domain\user format

do not enable Basic Authentication on the default non-SSL site


问:
How to apply floating label to select2 dropdown?
I'm using select2 plugin for select dropdown. I have more than one select dropdown boxes in the page and I need to apply the floating label to the selected dropdown.

I have tried and googled but I could not find any desired results as I expected.

I have provided the code that I have tried so far.

HTML

```<code><div class="container">
  <div class="row">
    <div class="col-md-6 col-lg-6 col-sm-6">
      <label class="hor-menu visible-xs visible-xs control-label col-sm-1"></label>
      <div class="form-group form-md-line-input form-md-floating-label" style="margin-top: 13px;">
        <select name="cboNGrp" id="cboNGrp" class="form-control select2me input-xlarge" data-live-search="true" data-size="8"></select>
        <label class="form_control_1 head_ctrl_label" style="padding-top: 2px;">Type</label>
      </div>
    </div>
    <div class="col-md-6 col-lg-6 col-sm-6">
      <div class="form-group form-md-line-input head_ctrl">
        <label class="hor-menu visible-xs visible-xs control-label  col-sm-1"></label>
        <select name="cboEmrGrp" id="cboEmrGrp" class="select2me form-control input-xlarge"></select>
        <label class="form_control_1 head_ctrl_label">E / M</label>
      </div>
    </div>
  </div>
</div>
</code>```

JS

```<code>$('.select2me').click(function(e){
    if($(this).find('select2-dropdown-open')) {
        $('label.head_ctrl_label').css('margin-top', '-25px');
    }
    e.preventDefault();
});
</code>```

Image showing user clicks the Dropdown to select Option

Image showing the bug floating label applies to all the dropdown not only selected one

答:
Try the following </p>

```<code>$('.select2me').click(function(e){
   if($(this).find('select2-dropdown-open')) {
      $(this).next('.head_ctrl_label').css('margin-top', '-25px'); }
      e.preventDefault();
});
</code>```

Body:
I'm using select2 plugin for select dropdown. I have more than one select dropdown boxes in the page and I need to apply the floating label to the selected dropdown.

I have tried and googled but I could not find any desired results as I expected.

I have provided the code that I have tried so far.

HTML

        <select name="cboNGrp" id="cboNGrp" class="form-control select2me input-xlarge" data-live-search="true" data-size="8"></select>
        Type

        <select name="cboEmrGrp" id="cboEmrGrp" class="select2me form-control input-xlarge"></select>
        E / M

JS

$('.select2me').click(function(e){
    if($(this).find('select2-dropdown-open')) {
        $('label.head_ctrl_label').css('margin-top', '-25px');
    }
    e.preventDefault();
});

Image showing user clicks the Dropdown to select Option

Image showing the bug floating label applies to all the dropdown not only selected one

Body:
Try the following

$('.select2me').click(function(e){
   if($(this).find('select2-dropdown-open')) {
      $(this).next('.head_ctrl_label').css('margin-top', '-25px'); }
      e.preventDefault();
});


问:
How to get visitors location using Angular 2 or TypeScript
I started use get by ServerVariables["HTTP_CF_IPCOUNTRY"] by backend server, but it is too slow, I need an Angular or TypeScript solution for this.

答:
Found solution using Vivek example.</p>

```<code>ngOnInit() {

    if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
            position => {
                this.geolocationPosition = position,
                    console.log(position)
            },
            error => {
                switch (error.code) {
                    case 1:
                        console.log('Permission Denied');
                        break;
                    case 2:
                        console.log('Position Unavailable');
                        break;
                    case 3:
                        console.log('Timeout');
                        break;
                }
            }
        );
    };
}
</code>```

Body:
Found solution using Vivek example.

ngOnInit() {

    if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(
            position => {
                this.geolocationPosition = position,
                    console.log(position)
            },
            error => {
                switch (error.code) {
                    case 1:
                        console.log('Permission Denied');
                        break;
                    case 2:
                        console.log('Position Unavailable');
                        break;
                    case 3:
                        console.log('Timeout');
                        break;
                }
            }
        );
    };
}


问:
How to stop polygon stroke style overlapping polygon fill
I have a vector polygon in ol3 that I am styling with a coloured fill and a white stroke for the outline of the polygon.

```<code>new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: '#ffffff',
          width: 3
        }),
        fill: new ol.style.Fill({
          color: 'rgba(241, 135, 0, 0.7)'
        })
      })
</code>```

At higher resolutions this style is fine and the stroke and fill are well defined:

But zooming out means the stroke encroaches the fill and eventually they overlap and hide the fill:

I think that this is due to the stroke being drawn in the middle of the line of the polygon and so half of it is outside and half is inside the polygon, therefore when zooming out the half that is inside fills the polygon hiding the fill.

I'd like the polygon to have the line only drawn on the outside of the polygon: more like shading.  I've had a play with the options but haven't quite managed it.

Does anyone know a setting that can achieve this, without resorting to dynamically reducing the width of the stroke or hiding the stroke when zooming out on the map.

答:
Use a style function and change the stroke style using the resolution passed as an argument to the style function.

Check this code snip:

```<code>var style = new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)'
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1
  }),
  text: new ol.style.Text({
    font: '12px Calibri,sans-serif',
    fill: new ol.style.Fill({
      color: '#000'
    }),
    stroke: new ol.style.Stroke({
      color: '#fff',
      width: 3
    })
  })
});

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v3.19.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
    if(resolution < 5000 ) { //adjust the resolution to fit your needs
    style.stroke_.setWidth(5); //change the stroke depending on resolution
    } else {
    style.stroke_.setWidth(1);//reset it back
    }
    return style; //and return  it
}
});
</code>```

and here is a fiddle to see it in action

Body:
I have a vector polygon in ol3 that I am styling with a coloured fill and a white stroke for the outline of the polygon.

new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: '#ffffff',
          width: 3
        }),
        fill: new ol.style.Fill({
          color: 'rgba(241, 135, 0, 0.7)'
        })
      })

At higher resolutions this style is fine and the stroke and fill are well defined:

But zooming out means the stroke encroaches the fill and eventually they overlap and hide the fill:

I think that this is due to the stroke being drawn in the middle of the line of the polygon and so half of it is outside and half is inside the polygon, therefore when zooming out the half that is inside fills the polygon hiding the fill.

I'd like the polygon to have the line only drawn on the outside of the polygon: more like shading.  I've had a play with the options but haven't quite managed it.

Does anyone know a setting that can achieve this, without resorting to dynamically reducing the width of the stroke or hiding the stroke when zooming out on the map.

Body:
Use a style function and change the stroke style using the resolution passed as an argument to the style function.

Check this code snip:

var style = new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(255, 255, 255, 0.6)'
  }),
  stroke: new ol.style.Stroke({
    color: '#319FD3',
    width: 1
  }),
  text: new ol.style.Text({
    font: '12px Calibri,sans-serif',
    fill: new ol.style.Fill({
      color: '#000'
    }),
    stroke: new ol.style.Stroke({
      color: '#fff',
      width: 3
    })
  })
});

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v3.19.0/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature, resolution) {
    if(resolution < 5000 ) { //adjust the resolution to fit your needs
    style.stroke_.setWidth(5); //change the stroke depending on resolution
    } else {
    style.stroke_.setWidth(1);//reset it back
    }
    return style; //and return  it
}
});

and here is a fiddle to see it in action


问:
How to return correct local time in Postgres
```<code>select current_time at time zone 'GMT-2'
</code>```

returns

```<code>"11:54:40.22045+02"
</code>```

but correct local time in Windows is one hour different:

```<code>12:54
</code>```

How to get correct local time ?

Using

"PostgreSQL 9.6.0, compiled by Visual C++ build 1800, 32-bit"

with  standard postgresql.conf file in Windows 10
Same issue occurs also in ealier Postgres and in earlier windows.

Server time in Windows is correct.

Daylight saving time was changed by one hour a week ago.
Maybe postgres didnt recognized it.

答:
Don't use time with time zone, it is a useless data type.

See the documentation:

The type time with time zone is defined by the SQL standard, but the
  definition exhibits properties which lead to questionable usefulness.
  In most cases, a combination of date, time, timestamp without time zone,
  and timestamp with time zone should provide a complete range of date/time
  functionality required by any application.

Use localtime to get the current time at your current session time zone (defined by the TimeZone parameter).

Body:
select current_time at time zone 'GMT-2'

returns

"11:54:40.22045+02"

but correct local time in Windows is one hour different:

12:54

How to get correct local time ?

Using

"PostgreSQL 9.6.0, compiled by Visual C++ build 1800, 32-bit"

with  standard postgresql.conf file in Windows 10
Same issue occurs also in ealier Postgres and in earlier windows.

Server time in Windows is correct.

Daylight saving time was changed by one hour a week ago.
Maybe postgres didnt recognized it.


问:
Delay ajax request for 3 seconds before processing
I have an ajax script to send data. I want to display .coin-flip for 3 seconds before the data is sent/processed. Once this 3 seconds are over the data will be sent to flip-process.php normally and then the return result will be displayed on success. But currently its so fast that I just can see the coin flipping here (the animation I want to display). Therefore, I want a delay of 3 seconds before processing the ajax request. How can I do so?

Here is my ajax script.

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#submit").click(function() {
        var dataString = {
            flip: $("#flip").val(),
            amount: $("#amount").val(),
        };
    $.ajax({
            type: "POST",
            url: "flip-process.php",
            data: dataString,
            cache: true,
      beforeSend: function(){
                $("#coins").hide();
                $(".coin-flip").show();
      },
            success: function(html){
                $(".message").html(html).fadeIn();
                    $("#coins").show();
                    $(".coin-flip").hide();
            }
        });
        return false;
    });
});
</script>
</code>```

答:
you can wrap the ajax call in timeout</p>

```<code>                    <script type="text/javascript">
        $(document).ready(function() {
            $("#submit").click(function() {
                var dataString = {
                    flip: $("#flip").val(),
                    amount: $("#amount").val(),
                };
                var processing=false;

            $.ajax({
                    type: "POST",
                    url: "flip-process.php",
                    data: dataString,
                    cache: true,
              beforeSend: function(){
                        $("#coins").hide();
                        $(".coin-flip").show();
              },
                    success: function(html){
                        $(".message").html(html).fadeIn();
                            $("#coins").show();
                            timeout = setTimeout(function(){
                            if (!processing)
                           {
                            processing=true;
                            $(".coin-flip").hide();
                            }
                    }, 2000}
                });

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

Body:
you can wrap the ajax call in timeout

                    <script type="text/javascript">
        $(document).ready(function() {
            $("#submit").click(function() {
                var dataString = {
                    flip: $("#flip").val(),
                    amount: $("#amount").val(),
                };
                var processing=false;

            $.ajax({
                    type: "POST",
                    url: "flip-process.php",
                    data: dataString,
                    cache: true,
              beforeSend: function(){
                        $("#coins").hide();
                        $(".coin-flip").show();
              },
                    success: function(html){
                        $(".message").html(html).fadeIn();
                            $("#coins").show();
                            timeout = setTimeout(function(){
                            if (!processing)
                           {
                            processing=true;
                            $(".coin-flip").hide();
                            }
                    }, 2000}
                });

);
                return false;
            });
        });
        </script>


问:
Why regex_match do not match my regex?
I have to write a C++ regex but i am not able to get correct result on regex_match as i am new to c++.
The string for testing is: D10A7;
Lets say unsigned_char[] stringToBeTested="D10A7";
What i have to do is after regex_match i will extract 10 and 7 in two different short variabled for application's use. Digit after 'D' will always be two digit and digit after 'A' is always
be one digit.
My try to do it is:

```<code>boost::regex re("D([0-9])(/([0-9]))?");
boost::cmatch mr;
if ( boost::regex_match(stringToBeTested, mr, re ) )
{
    number = atoi(mr.str(1).c_str()); //Must be 10
    axis = atoi(mr.str(2).c_str()); //Must be 7
}
</code>```

How to generate the boost::regex re for this condition, Please explain the answer in detail.

答:
The regex_match requires a full string match. You need to provide a pattern that will do that.

```<code>boost::regex re("D([0-9]{2})A([0-9])");
</code>```

Here,

D - matches D

([0-9]{2}) - captures into Group 1 two digits

A - matches A

([0-9]) - captures into Group 2 a single digit.

See the online demo of the above regex.

Title: Why regex_match do not match my regex?

Body:
I have to write a C++ regex but i am not able to get correct result on regex_match as i am new to c++.
The string for testing is: D10A7;
Lets say unsigned_char[] stringToBeTested="D10A7";
What i have to do is after regex_match i will extract 10 and 7 in two different short variabled for application's use. Digit after 'D' will always be two digit and digit after 'A' is always
be one digit.
My try to do it is:

boost::regex re("D([0-9])(/([0-9]))?");
boost::cmatch mr;
if ( boost::regex_match(stringToBeTested, mr, re ) )
{
    number = atoi(mr.str(1).c_str()); //Must be 10
    axis = atoi(mr.str(2).c_str()); //Must be 7
}

How to generate the boost::regex re for this condition, Please explain the answer in detail.

Body:
The regex_match requires a full string match. You need to provide a pattern that will do that.

boost::regex re("D([0-9]{2})A([0-9])");

Here,

D - matches D

([0-9]{2}) - captures into Group 1 two digits

A - matches A

([0-9]) - captures into Group 2 a single digit.

See the online demo of the above regex.


问:
How do I combine Result and State in Elm?
I am struggling with Elm's lack of monads. A library implementing the state monad for Elm (http://package.elm-lang.org/packages/folkertdev/elm-state/latest/State) has helped me quite a bit.

The problem is that I have now run into a situation where I have alternately nested Result and State types, when I only want to have one of each.

I tried to write a function with the following signature, but it seems impossible, because the inner Result is only known once the outer State is evaluated.

```<code>join : Result a (State s (Result a (State s x))) -> Result a (State s x)
</code>```

Maybe it would work if I put the Result inside the State in the return value, but that would generate a dummy State in case the outer Result is Err.

I think the right idea would be to make something that is both Result and State. Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Here is a rough version of one place where the problem arises:

```<code>  generateConstraints environment value
  |> Result.map (State.map (\(value, valueC) ->
    Result.map
      (State.map2 (\this (body, bodyC) ->
        ( this
        , valueC ++ bodyC ++ [(this, body)]
        ))
      freshTypevar)
      (generateConstraints (extend environment name value) body))
  )
</code>```

答:
Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Well, I can at least try. This is how your type looks directly translated to Haskell:

```<code>type EffM a s x = Either a (State s x)
</code>```

A rather obvious observation is that it's not a monad transformer.2 That's how a transformer would look like:

```<code>type TransM a s x = EitherT a (State s) x
</code>```

As you can see, the only change is the T and the fact that x is outside the parens. The latter part is essential in understanding the transformer approach.

The core idea is that the State is a part of the result production regardless of whether the Either results in "success" or "fail", whereas in your case producing "fail" means the state operation is never touched. I'd need to think harder what that means in practice, but intuitively the transformer approach is what you're gonna have in mind when working with typical, imperative code.

Now, when you use such a transformer, join is actually provided for free, as a consequence of fitting into the Monad interface.

```<code>import Control.Monad.State
import Control.Monad.Trans.Either
import Control.Monad

type Eff e s a = EitherT e (State s) a

-- type the following in REPL

λ :t join
join :: Monad m => m (m a) -> m a

λ :t join :: Eff e s (Eff e s a) -> Eff e s a
join :: Eff e s (Eff e s a) -> Eff e s a
     :: Eff e s (Eff e s a) -> Eff e s a

-- the slightly cryptic output above means that it typechecks correctly
</code>```

So this is how Haskell1 solves it. Now, it's obviously possible to write a specialized EitherState type this way (altough I'd personally flip those two in all of the examples to StateEither - feels more natural), mirroring what the implementation of join for respective transformers would do. I don't know if writing EitherT specifically is possible in Elm.

1 One possible approach. There are other, recursion schemes/Free probably being the one to watch in the upcoming years. The inherent ordering of effects stacking turns out to be more problematic than it initially seems.

2 It's also not a Monad, at least in the sense that the x can't be the direct type in the Monad instance (because Either can obviously act as one in the specialized case).

Body:
I am struggling with Elm's lack of monads. A library implementing the state monad for Elm (http://package.elm-lang.org/packages/folkertdev/elm-state/latest/State) has helped me quite a bit.

The problem is that I have now run into a situation where I have alternately nested Result and State types, when I only want to have one of each.

I tried to write a function with the following signature, but it seems impossible, because the inner Result is only known once the outer State is evaluated.

join : Result a (State s (Result a (State s x))) -> Result a (State s x)

Maybe it would work if I put the Result inside the State in the return value, but that would generate a dummy State in case the outer Result is Err.

I think the right idea would be to make something that is both Result and State. Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Here is a rough version of one place where the problem arises:

  generateConstraints environment value
  |> Result.map (State.map (\(value, valueC) ->
    Result.map
      (State.map2 (\this (body, bodyC) ->
        ( this
        , valueC ++ bodyC ++ [(this, body)]
        ))
      freshTypevar)
      (generateConstraints (extend environment name value) body))
  )

Body:
Can someone who is familiar with Haskell monad transformers explain how they solve this kind of problem or suggest an alternative solution?

Well, I can at least try. This is how your type looks directly translated to Haskell:

type EffM a s x = Either a (State s x)

A rather obvious observation is that it's not a monad transformer.2 That's how a transformer would look like:

type TransM a s x = EitherT a (State s) x

As you can see, the only change is the T and the fact that x is outside the parens. The latter part is essential in understanding the transformer approach.

The core idea is that the State is a part of the result production regardless of whether the Either results in "success" or "fail", whereas in your case producing "fail" means the state operation is never touched. I'd need to think harder what that means in practice, but intuitively the transformer approach is what you're gonna have in mind when working with typical, imperative code.

Now, when you use such a transformer, join is actually provided for free, as a consequence of fitting into the Monad interface.

import Control.Monad.State
import Control.Monad.Trans.Either
import Control.Monad

type Eff e s a = EitherT e (State s) a

-- type the following in REPL

λ :t join
join :: Monad m => m (m a) -> m a

λ :t join :: Eff e s (Eff e s a) -> Eff e s a
join :: Eff e s (Eff e s a) -> Eff e s a
     :: Eff e s (Eff e s a) -> Eff e s a

-- the slightly cryptic output above means that it typechecks correctly

So this is how Haskell1 solves it. Now, it's obviously possible to write a specialized EitherState type this way (altough I'd personally flip those two in all of the examples to StateEither - feels more natural), mirroring what the implementation of join for respective transformers would do. I don't know if writing EitherT specifically is possible in Elm.

1 One possible approach. There are other, recursion schemes/Free probably being the one to watch in the upcoming years. The inherent ordering of effects stacking turns out to be more problematic than it initially seems.

2 It's also not a Monad, at least in the sense that the x can't be the direct type in the Monad instance (because Either can obviously act as one in the specialized case).


问:
Previous month datetime pandas
I have a datetime instance declared as follows:

```<code>dtDate = datetime.datetime(2016,1,1,0,0)
</code>```

How do I get the previous month and previous year from dtDate?

e.g. something like:

```<code>dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)
</code>```

答:
Use relativedelta from dateutil:

```<code>import datetime
import dateutil.relativedelta
dtDate = datetime.datetime(2016,1,1,0,0)
# get previous month
print ((dtDate+dateutil.relativedelta.relativedelta(months=-1)).month)
# get previous year
print ((dtDate+dateutil.relativedelta.relativedelta(years=-1)).year)
</code>```

Output:

```<code>12
2015
</code>```

Title: Previous month datetime pandas

Body:
I have a datetime instance declared as follows:

dtDate = datetime.datetime(2016,1,1,0,0)

How do I get the previous month and previous year from dtDate?

e.g. something like:

dtDate.minusOneMonth()
# to return datetime.datetime(2015,12,1,0,0)

Body:
Use relativedelta from dateutil:

import datetime
import dateutil.relativedelta
dtDate = datetime.datetime(2016,1,1,0,0)
# get previous month
print ((dtDate+dateutil.relativedelta.relativedelta(months=-1)).month)
# get previous year
print ((dtDate+dateutil.relativedelta.relativedelta(years=-1)).year)

Output:

12
2015


答:
The easist option would be to use a timeout in your success function, rather than delay the actual request:</p>

```<code>success: function(html){
    setTimeout(function(){

        $(".message").html(html).fadeIn();
        $("#coins").show();
        $(".coin-flip").hide();

    },3000);
}
</code>```

Title: Delay ajax request for 3 seconds before processing

Body:
I have an ajax script to send data. I want to display .coin-flip for 3 seconds before the data is sent/processed. Once this 3 seconds are over the data will be sent to flip-process.php normally and then the return result will be displayed on success. But currently its so fast that I just can see the coin flipping here (the animation I want to display). Therefore, I want a delay of 3 seconds before processing the ajax request. How can I do so?

Here is my ajax script.

Body:
The easist option would be to use a timeout in your success function, rather than delay the actual request:

success: function(html){
    setTimeout(function(){

        $(".message").html(html).fadeIn();
        $("#coins").show();
        $(".coin-flip").hide();

    },3000);
}


问:
How to show confirm box before removing tag from select2
How to show confirm box before removing a tag from select2? I have a text box where I have two options selected on removing of any of them I want to display a warning message. Can anyone help me in this?
In HTML I have element as </p>

```<code>    <div class="form-group">
    <label for="name" class="col-lg-3 control-label required">Select Type</label>
    <div class="col-lg-9">
        <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>
    </div>
  </div>
</code>```

<p>And in the js file </p>

```<code>$("#typeselect").select2({
        placeholder: 'Select Type'
    });
</code>```

答:
function deleteItem() {
   if (confirm("Are you sure?")) {
     $("#type option:selected").remove();
   }
   return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='type'>
<option value='1'>Type1</option>
<option value='2'>Type2</option>
</select>
<button onclick='deleteItem()'>Remove</button></code>```

Add onClick event on option tag like:

```<code><select id='type'>
    <option value='1'>Type1</option>
    <option value='2'>Type2</option>
</select>
<button onclick='deleteItem()'>Remove</button>
</code>```

Then You need to add confirm() to your deleteItem(); like this:

```<code>function deleteItem() {
   if (confirm("Are you sure?")) {
     $("#type option:selected").remove();
   }
   return false;
}
</code>```

Please try this and let me know if this solved your issue!!

Body:
How to show confirm box before removing a tag from select2? I have a text box where I have two options selected on removing of any of them I want to display a warning message. Can anyone help me in this?
In HTML I have element as

    Select Type

        <select id="typeselect" class="form-control" name="crm" required>
            <option value='0'>Select Type</option>
            <option value='1'>Type1</option>
            <option value='2'>Type2</option>
        </select>

And in the js file

$("#typeselect").select2({
        placeholder: 'Select Type'
    });

Body:
function deleteItem() {
   if (confirm("Are you sure?")) {
     $("#type option:selected").remove();
   }
   return false;
}

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='type'>
<option value='1'>Type1</option>
<option value='2'>Type2</option>
</select>
<button onclick='deleteItem()'>Remove</button>

Add onClick event on option tag like:

<select id='type'>
    <option value='1'>Type1</option>
    <option value='2'>Type2</option>
</select>
<button onclick='deleteItem()'>Remove</button>

Then You need to add confirm() to your deleteItem(); like this:

function deleteItem() {
   if (confirm("Are you sure?")) {
     $("#type option:selected").remove();
   }
   return false;
}

Please try this and let me know if this solved your issue!!


Title: Check whether a value appeared within the last n minutes

Body:
If we have the following data:

timestamp = ['2016-01-09_14-49-18','2016-01-10_09-48-59','2016-01-10_09-50-29','2016-01-10_09-59-08','2016-01-10_10-33-01','2016-01-10_10-35-01','2016-01-10_10-39-05','2016-01-10_10-40-38','2016-01-10_10-50-55','2016-01-10_12-28-35','2016-01-10_15-13-34','2016-01-10_17-02-44','2016-01-10_17-05-48','2016-01-10_17-13-44','2016-01-10_17-15-52']
feature = ['A','A','B','C','B','C','C','A','A','A','B','A','C','C','A']
df = pd.DataFrame({'timestamp':timestamp, 'feature':feature})

How can one create a new column for each feature that represents whether or not that class appeared in, let's say, the last 15 minutes?

Result:

   feature    timestamp              A    B    C
0       A  2016-01-09_14-49-18       1    0    0
1       A  2016-01-10_09-48-59       1    0    0
2       B  2016-01-10_09-50-29       1    1    0
3       C  2016-01-10_09-59-08       1    1    1
4       B  2016-01-10_10-33-01       0    1    0
5       C  2016-01-10_10-35-01       0    1    1
6       C  2016-01-10_10-39-05       0    1    1
7       A  2016-01-10_10-40-38       1    1    1
8       A  2016-01-10_10-50-55       1    0    1
9       A  2016-01-10_12-28-35       1    0    0
10      B  2016-01-10_15-13-34       0    1    0
11      A  2016-01-10_17-02-44       1    0    0
12      C  2016-01-10_17-05-48       1    0    1
13      C  2016-01-10_17-13-44       1    0    1
14      A  2016-01-10_17-15-52       1    0    1

Where 1 = the class appeared in the last 15 minutes, and 0 = the class did not appear.

Body:
from datetime import timedelta, datetime
# prepare cols
df["A"] = 0
df["B"] = 0
df["C"] = 0

# convert to datetime
df["timestamp"] = pd.to_datetime(df["timestamp"],format="%Y-%m-%d_%H-%M-%S")

feature_list = ["A","B","C"]
for row in df.iterrows():
    curr_index = row[0]
    curr_time = row[1][1]
    temp_df = df.loc[(df.timestamp <= curr_time)&(df.timestamp > curr_time-timedelta(minutes=15))]
    for feature_i in feature_list:
        if feature_i in temp_df.feature.tolist():
            df.loc[curr_index, feature_i] = 1
        else:
            df.loc[curr_index, feature_i] = 0

output:

   feature           timestamp  A  B  C
0        A 2016-01-09 14:49:18  1  0  0
1        A 2016-01-10 09:48:59  1  0  0
2        B 2016-01-10 09:50:29  1  1  0
3        C 2016-01-10 09:59:08  1  1  1
4        B 2016-01-10 10:33:01  0  1  0
5        C 2016-01-10 10:35:01  0  1  1
6        C 2016-01-10 10:39:05  0  1  1
7        A 2016-01-10 10:40:38  1  1  1
8        A 2016-01-10 10:50:55  1  0  1
9        A 2016-01-10 12:28:35  1  0  0
10       B 2016-01-10 15:13:34  0  1  0
11       A 2016-01-10 17:02:44  1  0  0
12       C 2016-01-10 17:05:48  1  0  1
13       C 2016-01-10 17:13:44  1  0  1
14       A 2016-01-10 17:15:52  1  0  1


问:
When using GSON, do I have to keep the same POJO at REST-WS consumer & provider end for serialization & deserialization?
I am new to GSON, JSON & hence asking the question:

At the android end, I have to send a booking information to the REST WS on the server. So here is the question:

I have a BookingDTO & I use GSON to serialize it. I send it the REST WS on the server. Now do I also need the same BookingDTO at the server end for GSON deserialize it? (But that would mean tight coupling right?) Do I have to use GSON or can I use normal JSON?

What should be my approach?

答:
do I also need the same BookingDTO at the server end for GSON
  deserialize it?

Simply put, yes, you'll have to prepare a POJO in order to receive the request. So, for that to happen, JSON deserializer will try to parse the properties off JSON request and map that to a POJO of server.

With Spring, we do stuffs like the following. This is a creating a controller of POST request type expecting to habe a param of BookingDTO type. We use Jackson library for JSON serialize and deserialize.

```<code>    @RequestMapping(value = {"/update"}, method = RequestMethod.POST)
    @ResponseBody
    public void update(@RequestBody BookingDTO bookingDTO) throws FamsException {

        // Do what you intend to do with this bookingDTO object sent from client side(Android)
    }
</code>```

As it stands, if your JSON property name matches with the property name and type of BookingDTO then it can map those and you'll get BookingDTO bookingDTO object with all the matched properties.

Be sure not to send JSON request with property that isn't in the BookingDTO POJO. Otherwise, server will throw a 400 BAD REQUEST error.

Note that, you can also send Map as parameter. This won't require a matching POJO at server side. You can construct a different object by getting the data out of Map the way you like.

Hope you get the idea.

Body:
do I also need the same BookingDTO at the server end for GSON
  deserialize it?

Simply put, yes, you'll have to prepare a POJO in order to receive the request. So, for that to happen, JSON deserializer will try to parse the properties off JSON request and map that to a POJO of server.

With Spring, we do stuffs like the following. This is a creating a controller of POST request type expecting to habe a param of BookingDTO type. We use Jackson library for JSON serialize and deserialize.

    @RequestMapping(value = {"/update"}, method = RequestMethod.POST)
    @ResponseBody
    public void update(@RequestBody BookingDTO bookingDTO) throws FamsException {

        // Do what you intend to do with this bookingDTO object sent from client side(Android)
    }

As it stands, if your JSON property name matches with the property name and type of BookingDTO then it can map those and you'll get BookingDTO bookingDTO object with all the matched properties.

Be sure not to send JSON request with property that isn't in the BookingDTO POJO. Otherwise, server will throw a 400 BAD REQUEST error.

Note that, you can also send Map as parameter. This won't require a matching POJO at server side. You can construct a different object by getting the data out of Map the way you like.

Hope you get the idea.


问:
Changing background colour of specific select2 through javascript
In a web form, I'm using two select2 control at two panel each.

I wish to change only one of the select2's background colour when it hit certain condition through javascript else it will remain its original colour.

How can I accomplish that?

I am at the stage where the css code below I found is able to modify the select2 to the result I want.

```<code>       .select2-container .select2-selection{
        background: yellow;
        }
</code>```

Any help is much appreciated.

Edited:

Adding some part of my code:

CSS

```<code>    .select2-container {
        position: relative;
        z-index: 2;
        float: left;
        margin-bottom: 0;
        display: table;
        table-layout: fixed;
        font-size: smaller;
    }
</code>```

Markup

```<code><div class="container-fluid">
    <div class="col-md-7">
        <table>
           <tr>
                 <td>
                     <select id="ddl_Select2ONE" runat="server" class="form-control select"></select>
                 </td>
           </tr>
        </table>
    </div>
    <div class="col-md-5">
        <table>
           <tr>
                 <td>
                     <select id="ddl_Select2TWO" runat="server" class="form-control select"></select>
                 </td>
           </tr>
        </table>
    </div>
</div>
</code>```

Javascript

```<code>pageLoad(){
  configureSelect2()
}

configureSelect2(){
    if(hf_value.value == "1"){
        //Change only ddl_Select2ONE to yellow background
    }
    else{
        //Change only ddl_Select2ONE to original background
    }
}
</code>```

Then I will perform some checking on javascript's pageload when it check a hidden field value for conditional enable.

答:
Solved and solution provided here :

What I need was the "!important" in css class and finding the span I need to add the css class to.

CSS

```<code>    .yellowBackground{
        background: yellow !important;
    }
</code>```

javascript

```<code>function pageLoad(){
  configureSelect2()
}

function configureSelect2(){

        td_Name = document.getElementById("<%=td_Name.ClientID %>");
        if (hf_Value.value == "1") {
            ($(td_Name).find('span')).addClass('yellowBackground');
        }
        else {
            ($(td_Name).find('span')).removeClass('yellowBackground');
        }
}
</code>```

Hope this helps!

Body:
In a web form, I'm using two select2 control at two panel each.

I wish to change only one of the select2's background colour when it hit certain condition through javascript else it will remain its original colour.

How can I accomplish that?

I am at the stage where the css code below I found is able to modify the select2 to the result I want.

       .select2-container .select2-selection{
        background: yellow;
        }

Any help is much appreciated.

Edited:

Adding some part of my code:

CSS

    .select2-container {
        position: relative;
        z-index: 2;
        float: left;
        margin-bottom: 0;
        display: table;
        table-layout: fixed;
        font-size: smaller;
    }

Markup

                     <select id="ddl_Select2ONE" runat="server" class="form-control select"></select>

                     <select id="ddl_Select2TWO" runat="server" class="form-control select"></select>

Javascript

pageLoad(){
  configureSelect2()
}

configureSelect2(){
    if(hf_value.value == "1"){
        //Change only ddl_Select2ONE to yellow background
    }
    else{
        //Change only ddl_Select2ONE to original background
    }
}

Then I will perform some checking on javascript's pageload when it check a hidden field value for conditional enable.

Body:
Solved and solution provided here :

What I need was the "!important" in css class and finding the span I need to add the css class to.

CSS

    .yellowBackground{
        background: yellow !important;
    }

javascript

function pageLoad(){
  configureSelect2()
}

function configureSelect2(){

        td_Name = document.getElementById("<%=td_Name.ClientID %>");
        if (hf_Value.value == "1") {
            ($(td_Name).find('span')).addClass('yellowBackground');
        }
        else {
            ($(td_Name).find('span')).removeClass('yellowBackground');
        }
}

Hope this helps!


问:
How to add a image at the center of a TableLayout
I have a TableLayout with some tablerow like this:

I want to add a image over the above layout under the circular mark as mention below:

Here is my layout code:

```<code>   <TableLayout
        android:layout_width="wrap_content"
        android:id="@+id/table1"
        android:gravity="center"
        android:layout_height="wrap_content">

        <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_1"
        android:background="@drawable/button"
        android:layout_margin="3dp"
        />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_2"
        android:background="@drawable/button"
        android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_3"
        android:background="@drawable/button"
        android:layout_margin="3dp"
   />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_4"
        android:background="@drawable/button"
        android:layout_margin="3dp" />
    </TableRow>

</TableLayout>
</code>```

So how to add a image over this layout at the center position?

答:
Try this structure</p>

```<code><FrameLayout>
<TableLayout></TableLayout>
<ImageView android:layout_gravity="centre"/>
</FrameLayout>
</code>```

Body:
I have a TableLayout with some tablerow like this:

I want to add a image over the above layout under the circular mark as mention below:

Here is my layout code:

   <TableLayout
        android:layout_width="wrap_content"
        android:id="@+id/table1"
        android:gravity="center"
        android:layout_height="wrap_content">

        <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_1"
        android:background="@drawable/button"
        android:layout_margin="3dp"
        />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_2"
        android:background="@drawable/button"
        android:layout_margin="3dp" />

    </TableRow>
    <TableRow>

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_3"
        android:background="@drawable/button"
        android:layout_margin="3dp"
   />

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/img1_4"
        android:background="@drawable/button"
        android:layout_margin="3dp" />
    </TableRow>

</TableLayout>

So how to add a image over this layout at the center position?

Body:
Try this structure

<FrameLayout>
<TableLayout></TableLayout>
<ImageView android:layout_gravity="centre"/>
</FrameLayout>


问:
Port a firefox extension to a BHO (Browser Helper Objects, aka IE extensions)
I have a Firefox extension that I would like to port to IE, I don't want to code it again.

Is there something that can help me? It could come in very different ways:

An IE BHO that can render a firefox extension, with IE fonctions mapped to the ones the FF extension calls.

A generator that takes a FF extension and generates a BHO (in C,C#,etc. whatever it wants).

EDIT: There may be no such thing. I'll keep the question open...

EDIT: question is irrelevant as of today

答: There is no easy way out.  The models are very different.  Abstract your core code to the extent that you can, and write the glue once for each browser.</p>


问:
android calendar permission issue
I am trying to access the android device calendar, which fails with this exception

I added this exact build hint to the codenameone_settings.properties file:

```<code>codename1.arg.android.xpermissions=<uses-permission android:name="android.permission.READ_CALENDAR"/> <uses-permission android:name="android.permission.WRITE_CALENDAR"/>
</code>```

Is there something I am missing?

答:
please refer this link hope it will help you
https://groups.google.com/forum/#!topic/codenameone-discussions/YMP7W4_9mjM

Use Native code to set the permission.

Title: android calendar permission issue

Body:
I am trying to access the android device calendar, which fails with this exception

I added this exact build hint to the codenameone_settings.properties file:

codename1.arg.android.xpermissions=<uses-permission android:name="android.permission.READ_CALENDAR"/> <uses-permission android:name="android.permission.WRITE_CALENDAR"/>

Is there something I am missing?


问:
On Windows 10 Make Inno Setup Uninstall Not Use Programs and Features Control Panel
On Windows 10, I created an Inno Setup install that loads the program just fine. However, when I go to uninstall the program ( start menu right-click choose uninstall) it opens the Program and Features control panel and then I have to choose the program I want to uninstall a second time.

How do I code the Inno Setup Script so it automatically starts the uninstall process without opening the Program and Features control panel and making me select the program I want to uninstall a second time?

答:
You can use Exec or Exec2 I don't remember what is it called but it goes something like this :
Exec('{app}/unistall00.exe')

Sorry I can't elaborate much since i'm on a mobile and you can also see in the Documentation.


问:
Microsoft VBscript runtime error: Object required: '[string: """new 1.cmd"""]' . Not sure that exactly is causing this to happen
Here is my code:

```<code>Dim strContents, objRegx, mkey, objShell, objUser, objFile
Set objShell = CreateObject("WScript.Shell")
Set objRegx = New RegExp
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objString = CreateObject("Scripting.Dictionary")
Set objUser = CreateObject("Wscript.Network")
Set objPath = objFSO.BuildPath(CurrentDirectory, """new 1.cmd""")

objRegx.Pattern = "\[(.*?)\]"
objRegx.IgnoreCase = True
objRegx.Global = True

WScript.Echo "Acquiring data ..."
objShell.Run objPath, 1, True

Set objFile = objFSO.OpenTextFile("c:\windows\temp\plik1.txt")

strContents = objFile.ReadAll

mkey = objRegx.Replace(strContents, "")

WScript.Echo mkey

objFile.Close
</code>```

I am not sure why I am getting this error when running the script.

答:
```<code>Set objPath = objFSO.BuildPath(CurrentDirectory, """new 1.cmd""")
</code>```

You have 3 mistakes in that statement:

The nested double quotes in """new 1.cmd""" make them part of the actual filename, which is not allowed. FileSystemObject methods can handle paths with spaces by themselves, without additional double quotes. You do need to add double quotes when passing the path to the Run method, though.

CurrentDirectory is a property of WshShell objects, not a builtin variable.

The BuildPath method returns a string, not an object, so you need to remove the Set keyword.

This will do what you want:

```<code>objPath = objFSO.BuildPath(objShell.CurrentDirectory, "new 1.cmd")
...
objShell.Run """" & objPath & """", 1, True
</code>```

Body:
Here is my code:

Dim strContents, objRegx, mkey, objShell, objUser, objFile
Set objShell = CreateObject("WScript.Shell")
Set objRegx = New RegExp
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objString = CreateObject("Scripting.Dictionary")
Set objUser = CreateObject("Wscript.Network")
Set objPath = objFSO.BuildPath(CurrentDirectory, """new 1.cmd""")

objRegx.Pattern = "\[(.*?)\]"
objRegx.IgnoreCase = True
objRegx.Global = True

WScript.Echo "Acquiring data ..."
objShell.Run objPath, 1, True

Set objFile = objFSO.OpenTextFile("c:\windows\temp\plik1.txt")

strContents = objFile.ReadAll

mkey = objRegx.Replace(strContents, "")

WScript.Echo mkey

objFile.Close

I am not sure why I am getting this error when running the script.

Body:
Set objPath = objFSO.BuildPath(CurrentDirectory, """new 1.cmd""")

You have 3 mistakes in that statement:

The nested double quotes in """new 1.cmd""" make them part of the actual filename, which is not allowed. FileSystemObject methods can handle paths with spaces by themselves, without additional double quotes. You do need to add double quotes when passing the path to the Run method, though.

CurrentDirectory is a property of WshShell objects, not a builtin variable.

The BuildPath method returns a string, not an object, so you need to remove the Set keyword.

This will do what you want:

objPath = objFSO.BuildPath(objShell.CurrentDirectory, "new 1.cmd")
...
objShell.Run """" & objPath & """", 1, True


问:
Why does adding an "import" to my file cause the "require.config()" call to no longer work?
In the file where I apply my settings to require.config, I also placed other settings which included importing a view model using typescript's export functionality. I noticed it was producing the error in all browsers:

requireConfig.ts

```<code>import HomePage from "Custom/HomePage";

require.config
({
    baseUrl: "/Scripts/",
    paths: {},
    shim: {}
});

require (["Custom/Initialisation/ConfigOnDocReady"]);
</code>```

Uncaught TypeError: require.config is not a function
    at Object.<anonymous> (RequireConfig.ts:3)

When I remove line 1, it works. What is causing this? I think this is a good opportunity to learn whats behind requireJs' curtain.

答:
Summary

RequireJS provides require locally and globally. You are calling config on a locally provided require. A local require has no config method, and you get the error you get. You should call config on the global require. RequireJS exports an alias to the global require as requirejs, or you could access it as window.require.

The Long Explanation

RequireJS's local and global require calls

RequireJS provides two points of access to require: a global one, and a local one. In the browser, the global one is exported into the global space, window. The local require is provided if you specifically request it as a module in your dependency list when you call define. Calling define is the standard way to register an AMD module with an AMD loader (which is what RequireJS is). The argument to the callback here is a local require:

```<code>define(['require'], function (require) {
});
</code>```

(It is also automatically provided to the callback if you entirely omit the dependency list, but this scenario needs not detain us here.)

The local require does not provide a config method. It wouldn't make much sense if it did because calling config has global effects. For instance, there's no provision for changing baseUrl only for some modules in a context but not others. So RequireJS provides a config method only on the global require.

"But wait", you say, "I'm not calling define anywhere!"

No, but TypeScript is emitting code that calls define.

How TypeScript emits your code

Your code works when you remove the import because TypeScript outputs significantly different code depending on whether it is present:

When you have the import statement, then your code is wrapped in something similar to the define I've shown above, and consequently, your call to require is a call to the local one. (The define wrapper produced by tsc is more complex, but that's not important here.)

If there are no import/export statements, the code is considered to be a "script" and TypeScript won't output any module-related code. In particular, the code emitted won't have a define wrapper as I've shown above, and your call to require is a call to the global one.

The Upshot

If you want to change configuration from inside a module, you should take care of calling the global require. RequireJS exports it also under the requirejs alias. So you can call requirejs.config. Or you can access it explicitly through window as window.require.

Body:
In the file where I apply my settings to require.config, I also placed other settings which included importing a view model using typescript's export functionality. I noticed it was producing the error in all browsers:

requireConfig.ts

import HomePage from "Custom/HomePage";

require.config
({
    baseUrl: "/Scripts/",
    paths: {},
    shim: {}
});

require (["Custom/Initialisation/ConfigOnDocReady"]);

Uncaught TypeError: require.config is not a function
    at Object.<anonymous> (RequireConfig.ts:3)

When I remove line 1, it works. What is causing this? I think this is a good opportunity to learn whats behind requireJs' curtain.

Body:
Summary

RequireJS provides require locally and globally. You are calling config on a locally provided require. A local require has no config method, and you get the error you get. You should call config on the global require. RequireJS exports an alias to the global require as requirejs, or you could access it as window.require.

The Long Explanation

RequireJS's local and global require calls

RequireJS provides two points of access to require: a global one, and a local one. In the browser, the global one is exported into the global space, window. The local require is provided if you specifically request it as a module in your dependency list when you call define. Calling define is the standard way to register an AMD module with an AMD loader (which is what RequireJS is). The argument to the callback here is a local require:

define(['require'], function (require) {
});

(It is also automatically provided to the callback if you entirely omit the dependency list, but this scenario needs not detain us here.)

The local require does not provide a config method. It wouldn't make much sense if it did because calling config has global effects. For instance, there's no provision for changing baseUrl only for some modules in a context but not others. So RequireJS provides a config method only on the global require.

"But wait", you say, "I'm not calling define anywhere!"

No, but TypeScript is emitting code that calls define.

How TypeScript emits your code

Your code works when you remove the import because TypeScript outputs significantly different code depending on whether it is present:

When you have the import statement, then your code is wrapped in something similar to the define I've shown above, and consequently, your call to require is a call to the local one. (The define wrapper produced by tsc is more complex, but that's not important here.)

If there are no import/export statements, the code is considered to be a "script" and TypeScript won't output any module-related code. In particular, the code emitted won't have a define wrapper as I've shown above, and your call to require is a call to the global one.

The Upshot

If you want to change configuration from inside a module, you should take care of calling the global require. RequireJS exports it also under the requirejs alias. So you can call requirejs.config. Or you can access it explicitly through window as window.require.