问:
Pandas Multi-index slice only on secondary index
I have the following pandas (related to the example here: pandas: slice a MultiIndex by range of secondary index)

```<code>import numpy as np
import pandas as pd

variable = np.repeat(['a','b','c'], [5,5,5])
time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20]

arra = [variable, time]

index=pd.MultiIndex.from_arrays(arra, names=("variable", "time"))

s = pd.Series(
    np.random.randn(len(sequence)),
    index=index
)
</code>```

Output would be

```<code># In [1]: s
variable  time
a         0      -1.284692
          1      -0.313895
          5      -0.980222
          10     -1.452306
          20     -0.423921
b         0       0.248625
          1       0.183721
          5      -0.733377
          10      1.562653
          20     -1.092559
c         0       0.061172
          1       0.133960
          5       0.765271
          10     -0.648834
          20      0.147158
dtype: float64
</code>```

If I slice here on both multiindex, it would work like this:

```<code># In [2]: s.loc[("a",0),:]
variable  time
a         0       1.583589
          1      -1.081401
          5      -0.497904
          10      0.352880
          20     -0.179062
dtype: float64
</code>```

But how can I just slice on secondary index "time" at e.g. time=0 and get every row with first index? The following won't work:

```<code># In [3]: s.loc[(0),:]

KeyError: 0
</code>```

How would I do that here?

Body:
I have the following pandas (related to the example here: pandas: slice a MultiIndex by range of secondary index)

import numpy as np
import pandas as pd

variable = np.repeat(['a','b','c'], [5,5,5])
time = [0,1,5,10,20,0,1,5,10,20,0,1,5,10,20]

arra = [variable, time]

index=pd.MultiIndex.from_arrays(arra, names=("variable", "time"))

s = pd.Series(
    np.random.randn(len(sequence)),
    index=index
)

Output would be

# In [1]: s
variable  time
a         0      -1.284692
          1      -0.313895
          5      -0.980222
          10     -1.452306
          20     -0.423921
b         0       0.248625
          1       0.183721
          5      -0.733377
          10      1.562653
          20     -1.092559
c         0       0.061172
          1       0.133960
          5       0.765271
          10     -0.648834
          20      0.147158
dtype: float64

If I slice here on both multiindex, it would work like this:

# In [2]: s.loc[("a",0),:]
variable  time
a         0       1.583589
          1      -1.081401
          5      -0.497904
          10      0.352880
          20     -0.179062
dtype: float64

But how can I just slice on secondary index "time" at e.g. time=0 and get every row with first index? The following won't work:

# In [3]: s.loc[(0),:]

KeyError: 0

How would I do that here?

Body:
Use xs with specify second level or loc with : for select all values of first level and 0 for select values of second level:

print (s.xs(0, level=1))

Or:

print (s.loc[:, 0])

a    0.376784
b   -0.643836
c   -0.440340
dtype: float64

If working with indices and column(s) of DataFrame use slicers:

idx = pd.IndexSlice
df = pd.concat([s,s * 10], axis=1, keys=['a','b'])
print (df)
                      a          b
variable time
a        0     1.054582  10.545820
         1    -1.716213 -17.162130
         5    -0.187765  -1.877645
         10   -0.419005  -4.190047
         20   -0.772808  -7.728078
b        0    -0.022520  -0.225202
         1    -0.638453  -6.384531
         5     0.410156   4.101559
         10    0.512189   5.121889
         20   -1.241232 -12.412322
c        0    -0.134815  -1.348148
         1    -1.007632 -10.076318
         5    -0.859790  -8.597898
         10   -0.623177  -6.231767
         20   -0.635504  -6.355036

print (df.loc[idx[:, 0], 'a'])
variable  time
a         0       1.054582
b         0      -0.022520
c         0      -0.134815
Name: a, dtype: float64


来源: stackexchange

问:
Custom Authentication with Firebase and Generating JWT
I am integrating Firebase with my existing Authentication in Android app. As per Firebase documentation, below steps needs to be followed to achieve authentication

Generating a Secure Token on a Secure Server

Authenticating Clients

I am confused in generating a secure token, Do I need to generate it on a secure server? What does it meant? I am thinking of generating the token in the android client itself.

Let me explain my existing Authentication mechanism, After getting credentials as input it will check against MongoDB which is connected with MongoLab API through Retrofit

After this, I am thinking of integrating with Firebase in the below way

From Login User UID which I get after successful login and in the android client itself I will generate a Secure Token (JWT).

With the generated JWT, I will again authenticate a client (Second time with firebase, as Initially with my existing authentication mechanism)

Generating Secure Token (JWT)

```<code>Map<String, Object> payload = new HashMap<String, Object>();

payload.put("uid", "uniqueId1");
payload.put("some", "arbitrary");
payload.put("data", "here");

TokenGenerator tokenGenerator = new TokenGenerator("<YOUR_FIREBASE_SECRET>");
String token = tokenGenerator.createToken(payload);
</code>```

Authenticating Clients

```<code>Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");

ref.authWithCustomToken(token, new Firebase.AuthResultHandler() {
    @Override
    public void onAuthenticationError(FirebaseError error) {
       System.err.println("Login Failed! " + error.getMessage());
    }

    @Override
    public void onAuthenticated(AuthData authData) {
        System.out.println("Login Succeeded!");
    }
});
</code>```

Here it looks like a round trip, like Authenticating a User 2 times, with my existing authentication and again with Firebase Custom Authentication. Is there any better way to achieve the above process?

答: The custom token has to be generated on a backend server. Generating it on the client side will expose your project credentials compromising your entire users. Any attacker who can install your app will be able to figure out your service account credentials and have full access to your users.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am integrating Firebase with my existing Authentication in Android app. As per Firebase documentation, below steps needs to be followed to achieve authentication

Generating a Secure Token on a Secure Server

Authenticating Clients

I am confused in generating a secure token, Do I need to generate it on a secure server? What does it meant? I am thinking of generating the token in the android client itself.

Let me explain my existing Authentication mechanism, After getting credentials as input it will check against MongoDB which is connected with MongoLab API through Retrofit

After this, I am thinking of integrating with Firebase in the below way

From Login User UID which I get after successful login and in the android client itself I will generate a Secure Token (JWT).

With the generated JWT, I will again authenticate a client (Second time with firebase, as Initially with my existing authentication mechanism)

Generating Secure Token (JWT)

Map<String, Object> payload = new HashMap<String, Object>();

payload.put("uid", "uniqueId1");
payload.put("some", "arbitrary");
payload.put("data", "here");

TokenGenerator tokenGenerator = new TokenGenerator("<YOUR_FIREBASE_SECRET>");
String token = tokenGenerator.createToken(payload);

Authenticating Clients

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/");

ref.authWithCustomToken(token, new Firebase.AuthResultHandler() {
    @Override
    public void onAuthenticationError(FirebaseError error) {
       System.err.println("Login Failed! " + error.getMessage());
    }

    @Override
    public void onAuthenticated(AuthData authData) {
        System.out.println("Login Succeeded!");
    }
});

Here it looks like a round trip, like Authenticating a User 2 times, with my existing authentication and again with Firebase Custom Authentication. Is there any better way to achieve the above process?


问:
application_name is not available in audit logs in SQL Server 2017
I am looking for a way to fetch client application name in audit logs in SQL Server. As per the MSDN page, it should be available from SQL Server 2017 on-wards.

https://learn.microsoft.com/en-us/sql/relational-databases/system-functions/sys-fn-get-audit-file-transact-sql

I have created a database level audit specification for select and insert and I want to determine which application is executing those queries.

Any help around this topic is appreciated.

答:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/6e038971-8bb5-45fb-8eca-5697fa24a857/applicationname-is-not-available-in-audit-logs-in-sql-server-2017?forum=sqldatabaseengine

Apparently you can only fetch that data using T-SQL at the moment. SSMS log viewer does not show those additional columns.


问:
Disable dropdown option after selection once
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superheroes. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left to choose. Those chosen options will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

```<code><form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">
    <div class="cc-m-form-loading"></div>
        <div class="cc-m-form-view-sortable">
            <div class="cc-m-form-view-element cc-m-form-select" data-action="element" required>
            <label for="ma6b8be54cf86a6410">
                <div>Kies welke held jouw team is!</div>
                </label>
                <div class="cc-m-form-view-input-wrapper">
                    <select name="teamnaam" class="cc-m-form-element-input" required>
                        <option value="" selected disabled hidden>Selecteer</option>
                        <option value="Superman">Superman</option>
                        <option value="Batman">Batman</option>
                        <option value="X-Men">X-Men</option>
                        <option value="MegaMindy">Mega Mindy</option>
                        <option value="Spiderman">Spiderman</option>
                        <option value="TheHulk">The Hulk</option>
                        <option value="HitGirl">Hit Girl</option>
                        <option value="Meerminman">Meerminman</option></select></div></div>
                        <input type="submit" value="Naar betalen" data-action="formButton">
</code>```

So if you make a selection and submit the form, it will link to inschrijfformulie.php, this .php file contains:

```<code><?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
exit;
?>
</code>```

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

答:
For the html to disable the OPTION

```<code><select name="teamnaam">
    <option value="a">A</option>
    <option value="b" selected="selected">B</option>
    <option value="c" disabled="disabled">C</option>
    <option value="d">D</option>
</select>
</code>```

For javascript to disable the OPTION

```<code>var dropDown = document.getElementsByName("teamnaam");
var dropDownOptions = dropDown[0].getElementsByTagName("OPTION");
for( var optIdx in dropDownOptions ){
    if(dropDownOptions[optIdx].value == 'd' ){
        dropDownOptions[optIdx].setAttribute("disabled", "disabled");
    }
}
</code>```

Remarks, It is handle the UI only, the logic for limit the qty of the hero select count should be handle by PHP.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superheroes. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left to choose. Those chosen options will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

<form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">

Kies welke held jouw team is!

                    <select name="teamnaam" class="cc-m-form-element-input" required>
                        <option value="" selected disabled hidden>Selecteer</option>
                        <option value="Superman">Superman</option>
                        <option value="Batman">Batman</option>
                        <option value="X-Men">X-Men</option>
                        <option value="MegaMindy">Mega Mindy</option>
                        <option value="Spiderman">Spiderman</option>
                        <option value="TheHulk">The Hulk</option>
                        <option value="HitGirl">Hit Girl</option>
                        <option value="Meerminman">Meerminman</option></select>

                        <input type="submit" value="Naar betalen" data-action="formButton">

So if you make a selection and submit the form, it will link to inschrijfformulie.php, this .php file contains:

<?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
exit;
?>

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

Body:
For the html to disable the OPTION

<select name="teamnaam">
    <option value="a">A</option>
    <option value="b" selected="selected">B</option>
    <option value="c" disabled="disabled">C</option>
    <option value="d">D</option>
</select>

For javascript to disable the OPTION

var dropDown = document.getElementsByName("teamnaam");
var dropDownOptions = dropDown[0].getElementsByTagName("OPTION");
for( var optIdx in dropDownOptions ){
    if(dropDownOptions[optIdx].value == 'd' ){
        dropDownOptions[optIdx].setAttribute("disabled", "disabled");
    }
}

Remarks, It is handle the UI only, the logic for limit the qty of the hero select count should be handle by PHP.


问:
Elasticsearch DSL query finding irrelevant results
I am using Elasticsearch to search the Packetbeat indices to identify if two IP addresses communicate. If IP xx.xx.xx.xx talks to IP yy.yy.yy.yy OR if IP yy.yy.yy.yy talk to IP xx.xx.xx.xx, I want to know about it. Below is my DSL but all the returned results are not relevant at all. What am I doing wrong? Thanks!</p>

```<code>GET /packetbeat-*/_search?size=100&pretty
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "_type": "flow"
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "source.ip": "127.0.0.1"
          }
        },
        {
          "term": {
            "dest.ip": "127.0.0.1"
          }
        }
      ],
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_type": "flow"
                }
              },
              {
                "term": {
                  "source.ip": "xx.xx.xx.xx"
                }
              },
              {
                "term": {
                  "dest.ip": "yy.yy.yy.yy"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_type": "flow"
                }
              },
              {
                "term": {
                  "source.ip": "yy.yy.yy.yy"
                }
              },
              {
                "term": {
                  "dest.ip": "xx.xx.xx.xx"
                }
              }
            ]
          }
        }
      ],
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now-30d/d",
            "lte": "now-1d/d"
          }
        }
      }
    }
  }
}
</code>```

答:
To simplify your query:

_type: flow

not localhost

source.ip != dest.ip

source.ip OR dest.ip equal to IP_X OR IP_Y

Have a look, according to this answer:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "_type": "flow"
          }
        },
        {
          "script": {
            "script": "doc['source.ip'].value != doc['dest.ip'].value"
          }
        },
        {
          "terms": {
            "source.ip": [
              "IP_X",
              "IP_Y"
            ]
          }
        },
        {
          "terms": {
            "dest.ip": [
              "IP_X",
              "IP_Y"
            ]
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "source.ip": "127.0.0.1"
          }
        },
        {
          "term": {
            "dest.ip": "127.0.0.1"
          }
        }
      ],
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now-30d/d",
            "lte": "now-1d/d"
          }
        }
      }
    }
  }
}
</code>```

Body:
I am using Elasticsearch to search the Packetbeat indices to identify if two IP addresses communicate. If IP xx.xx.xx.xx talks to IP yy.yy.yy.yy OR if IP yy.yy.yy.yy talk to IP xx.xx.xx.xx, I want to know about it. Below is my DSL but all the returned results are not relevant at all. What am I doing wrong? Thanks!

GET /packetbeat-*/_search?size=100&pretty
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "_type": "flow"
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "source.ip": "127.0.0.1"
          }
        },
        {
          "term": {
            "dest.ip": "127.0.0.1"
          }
        }
      ],
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_type": "flow"
                }
              },
              {
                "term": {
                  "source.ip": "xx.xx.xx.xx"
                }
              },
              {
                "term": {
                  "dest.ip": "yy.yy.yy.yy"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_type": "flow"
                }
              },
              {
                "term": {
                  "source.ip": "yy.yy.yy.yy"
                }
              },
              {
                "term": {
                  "dest.ip": "xx.xx.xx.xx"
                }
              }
            ]
          }
        }
      ],
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now-30d/d",
            "lte": "now-1d/d"
          }
        }
      }
    }
  }
}

Body:
To simplify your query:

_type: flow

not localhost

source.ip != dest.ip

source.ip OR dest.ip equal to IP_X OR IP_Y

Have a look, according to this answer:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "_type": "flow"
          }
        },
        {
          "script": {
            "script": "doc['source.ip'].value != doc['dest.ip'].value"
          }
        },
        {
          "terms": {
            "source.ip": [
              "IP_X",
              "IP_Y"
            ]
          }
        },
        {
          "terms": {
            "dest.ip": [
              "IP_X",
              "IP_Y"
            ]
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "source.ip": "127.0.0.1"
          }
        },
        {
          "term": {
            "dest.ip": "127.0.0.1"
          }
        }
      ],
      "filter": {
        "range": {
          "@timestamp": {
            "gte": "now-30d/d",
            "lte": "now-1d/d"
          }
        }
      }
    }
  }
}


问:
Sql Server replication requires the actual server name to make a connection to the server
I get the following message when I want to create a new publication or Subscription.

"Sql Server replication requires the actual server name to make a connection to the server. Connections through a server alias, IP address or any other alternate name are not supported. specify the actual server name"

Does anyone know what should I do?

答: If you're working on a hosted environment where the server names are weird strings that may actually be being shared with other servers... e.g. WIN-II7VS-100. The solution I've found thanks to @ZachSmith is to edit the hosts file on the server you want to connect from and set it to the static IP of the SQL server you wish to connect to.</p>


问:
How to shift an excel UsedRange to begin at cell A1 its worksheet (i.e. delete all blank rows and columns outside UsedRange)?
I am new to VBA and have not yet been able to figure out how to select and delete the "non-UsedRange" from a sheet at once (i.e. shift the UsedRange to begin at cell A1).

In other words, I need a dynamic solution to move a UsedRange of variable size from its variable location to the very top left of its worksheet (i.e. all empty columns/rows on the left/top side of the UsededRange should disapear).

I have (probably) found a one-liner to do this (only) row-wise for (only) one specific column:

```<code>ActiveSheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
</code>```

How to shift an excel UsedRange to begin at cell A1 its worksheet (i.e. delete all blank rows and columns outside UsedRange)?

答:
Just keep deleting row 1 and column A while they are blank.</p>

```<code>with worksheets("sheet1")
    do while not cbool(application.counta(.rows(1).cells))
        .rows(1).entirerow.delete
    loop
    do while not cbool(application.counta(.columns(1).cells))
        .columns(1).entirecolumn.delete
    loop
end with
</code>```

Body:
I am new to VBA and have not yet been able to figure out how to select and delete the "non-UsedRange" from a sheet at once (i.e. shift the UsedRange to begin at cell A1).

In other words, I need a dynamic solution to move a UsedRange of variable size from its variable location to the very top left of its worksheet (i.e. all empty columns/rows on the left/top side of the UsededRange should disapear).

I have (probably) found a one-liner to do this (only) row-wise for (only) one specific column:

ActiveSheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

How to shift an excel UsedRange to begin at cell A1 its worksheet (i.e. delete all blank rows and columns outside UsedRange)?

Body:
Just keep deleting row 1 and column A while they are blank.

with worksheets("sheet1")
    do while not cbool(application.counta(.rows(1).cells))
        .rows(1).entirerow.delete
    loop
    do while not cbool(application.counta(.columns(1).cells))
        .columns(1).entirecolumn.delete
    loop
end with


问:
How to get a log4net log file's name pattern programmatically?
I am trying to write a C# code, which retrieves in runtime the name pattern of a log4net log file via the log4net API.

That is, if in log4net.config the following appender is defined:

<appender name="MyAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="%date{yyyy}\%date{MM}\%date{dd}\%property{Id}.log" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="16" />
  <maximumFileSize value="1MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%message%newline" />
  </layout>
</appender>
```

I would like to get %date{yyyy}\%date{MM}\%date{dd}\%property{Id}.log in a string variable in code (without parsing log4net.config as a plain XML).

Does anybody has an idea ho to pull this trick?

Thank you in advance.

答:
I can obtain the value of the <file value> with the following code:

```<code>((log4net.Appender.FileAppender) ((log4net.Appender.IAppender[])
            ( (log4net.Repository.Hierarchy.Logger)
                log.Logger).Appenders.SyncRoot)[0]).File
</code>```

Body:
I am trying to write a C# code, which retrieves in runtime the name pattern of a log4net log file via the log4net API.

That is, if in log4net.config the following appender is defined:

<appender name="MyAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="%date{yyyy}\%date{MM}\%date{dd}\%property{Id}.log" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="16" />
  <maximumFileSize value="1MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%message%newline" />
  </layout>
</appender>

I would like to get %date{yyyy}\%date{MM}\%date{dd}\%property{Id}.log in a string variable in code (without parsing log4net.config as a plain XML).

Does anybody has an idea ho to pull this trick?

Thank you in advance.

Body:
I can obtain the value of the <file value> with the following code:

((log4net.Appender.FileAppender) ((log4net.Appender.IAppender[])
            ( (log4net.Repository.Hierarchy.Logger)
                log.Logger).Appenders.SyncRoot)[0]).File


问:
Change background color of the selected item in Android Spinner
I am working on an android app and using Spinner at many places in my app.
What I want is to change the background color of the selected item of spinner, so that one can easily identify which item is currently selected.

I have already checked this link Setting background color for Spinner Item on selection but doing so will change the selected textview background color but do not change its color in dropdown list and I want to change the background color of the selected textview when I will see the dropdown list.

I want to change the color of selected item in list not on spinner, please see the image below.

How can I do this? Please, can someone help me here?.

Thanks a lot in advanced.

答:
Here is solution via XML:

Spinner looks like:

```<code><Spinner
        android:id="@+id/settingsSleepingTimePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/spinner_main_button"
        android:popupBackground="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:textSize="20sp"/>
</code>```

While creating spinner set setDropDownViewResource as custom layout:

```<code>adapter.setDropDownViewResource(R.layout.spinner_item);
</code>```

And spinner_item.xml looks like:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/spinner"
    android:textColor="#ffffff"
    android:textSize="20sp" />
</code>```

And finally we set @drawable/spinner like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimaryLight" android:state_hovered="true" />
    <item android:drawable="@color/colorPrimaryLight" android:state_selected="true" />
</selector>
</code>```

Hope my answer will be helpfull!

Body:
Here is solution via XML:

Spinner looks like:

<Spinner
        android:id="@+id/settingsSleepingTimePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/spinner_main_button"
        android:popupBackground="@color/colorPrimary"
        android:textColor="@android:color/white"
        android:textSize="20sp"/>

While creating spinner set setDropDownViewResource as custom layout:

adapter.setDropDownViewResource(R.layout.spinner_item);

And spinner_item.xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/spinner"
    android:textColor="#ffffff"
    android:textSize="20sp" />

And finally we set @drawable/spinner like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimaryLight" android:state_hovered="true" />
    <item android:drawable="@color/colorPrimaryLight" android:state_selected="true" />
</selector>

Hope my answer will be helpfull!


问:
How to Convert int into a type Object within method; Java only
I'm trying to do my current project at my university, and I'm given an abstract class Value, and I'm needed to change basic types: int, string, object(map) and array(list) into Value. Value is made into an abstract constructor, and I need to create four different extended classes from Value. Each extended class will be able to get one of the types and convert into Value. added is the code I made for the get method, I want to know if it's possible to return the Value as it is below...

```<code> public class Number extends Value {
     private Number k;

        public Number(Number k)
     {
            super();
            this.k = k;
    }
        public Value get(int i) {
            this.k=i;
            return this;
        }
    }
</code>```

The following is the super class given by the university...

```<code>    public abstract class Value
{
    public abstract Value get(int i);
    public abstract Value get(String s);
}
</code>```

答:
You can use some thing like this </p>

```<code>   public abstract class Value {

    public abstract Value get(int i);

    public abstract Value get(String s);
  }

  public  class Number extends Value {
    private Number k;
    private Object o;

    public Number(Number k) {
      super();
      this.k = k;
    }

    @Override
    public Value get(int i) {
      this.k.o = i;
      return this;
    }

     @Override
     public Value get(String s) {
       this.k.o = s;
       return this;
     }
   }
</code>```

Body:
I'm trying to do my current project at my university, and I'm given an abstract class Value, and I'm needed to change basic types: int, string, object(map) and array(list) into Value. Value is made into an abstract constructor, and I need to create four different extended classes from Value. Each extended class will be able to get one of the types and convert into Value. added is the code I made for the get method, I want to know if it's possible to return the Value as it is below...

 public class Number extends Value {
     private Number k;

        public Number(Number k)
     {
            super();
            this.k = k;
    }
        public Value get(int i) {
            this.k=i;
            return this;
        }
    }

The following is the super class given by the university...

    public abstract class Value
{
    public abstract Value get(int i);
    public abstract Value get(String s);
}

Body:
You can use some thing like this

   public abstract class Value {

    public abstract Value get(int i);

    public abstract Value get(String s);
  }

  public  class Number extends Value {
    private Number k;
    private Object o;

    public Number(Number k) {
      super();
      this.k = k;
    }

    @Override
    public Value get(int i) {
      this.k.o = i;
      return this;
    }

     @Override
     public Value get(String s) {
       this.k.o = s;
       return this;
     }
   }


问:
Listen to changes of dependency property
Is there any way to listen to changes of a DependencyProperty? I want to be notified and perform some actions when the value changes but I cannot use binding. It is a DependencyProperty of another class.

答: If that is the case, One hack. You could introduce a Static class with a DependencyProperty. You source class also binds to that dp and your destination class also binds to the DP.


问:
Phonegap/Cordova ios External Links inside iframe not opening in safari
I know we can use inapp browser for opening external links in the app. But I am talking about the links with in iframe, inapp browser solution doesn't work for links inside iframe. I somehow need to open external links from iframe in safari browser of iPhone. Is there a workaround for this ?

Following is my config.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0" id="com.ocevent.ocevents" version="0.0.1">
   <name>Live</name>
   <description>Live Eventmanager</description>
   <author email="chh_rahul@live.com" href="http://softweavertech.com">Rahul Chhabra</author>
   <content src="index.html" />
   <allow-navigation href="*" />
   <allow-intent href="http://*/*" />
   <allow-intent href="https://*/*" />
   <allow-intent href="tel:*" />
   <allow-intent href="sms:*" />
   <icon src="icons/iphone_57x57.png" gap:platform="ios" width="57" height="57" />
   <icon src="icons/iphone_72x72.png" gap:platform="ios" width="72" height="72" />
   <icon src="icons/iphone_76x76.png" gap:platform="ios" width="76" height="76" />
   <icon src="icons/iphone_120x120.png" gap:platform="ios" width="120" height="120" />
   <icon src="icons/iphone_152x152.png" gap:platform="ios" width="152" height="152" />
   <icon src="icons/iphone_180x180.png" gap:platform="ios" width="180" height="180" />
   <icon src="icons/LiveIcon.png" gap:platform="android" />
   <!--splash src="icons/screen.png" gap:platform="android" /-->
   <!--icon src="icons/OCEM4-Android_57.png" gap:platform="android" /-->
   <plugin name="cordova-plugin-camera" />
   <gap:plugin name="cordova-plugin-file" source="pgb" />
   <gap:plugin name="cordova-plugin-customurlscheme" source="npm">
      <param name="URL_SCHEME" value="live" />
   </gap:plugin>
   <plugin name="cordova-plugin-whitelist" />
   <!--gap:plugin name="com.hutchind.cordova.plugins.streamingmedia" spec="0.1.3" source="pgb" /-->
   <gap:plugin name="cordova-plugin-file-transfer" source="pgb" />
   <gap:plugin name="cordova-plugin-dialogs" source="pgb" />
   <gap:plugin name="cordova-plugin-media-capture" source="pgb" />
   <gap:plugin name="cordova-plugin-splashscreen" source="pgb" />
   <gap:config-file platform="ios" parent="UIStatusBarHidden">
      <true />
   </gap:config-file>
   <platform name="android">
      <!-- you can use any density that exists in the Android project -->
      <splash src="icons/screen_640x960.png" density="land-hdpi" />
      <splash src="icons/screen_640x960.png" density="land-ldpi" />
      <splash src="icons/screen_640x960.png" density="land-mdpi" />
      <splash src="icons/screen_640x960.png" density="land-xhdpi" />
      <splash src="icons/screen_640x960.png" density="port-hdpi" />
      <splash src="icons/screen_640x960.png" density="port-ldpi" />
      <splash src="icons/screen_640x960.png" density="port-mdpi" />
      <splash src="icons/screen_640x960.png" density="port-xhdpi" />
   </platform>
   <platform name="ios">
      <!-- images are determined by width and height. The following are supported -->
      <splash src="icons/screen_320x480.png" width="320" height="480" />
      <splash src="icons/screen_640x960.png" width="640" height="960" />
      <splash src="icons/screen_768x1024.png" width="768" height="1024" />
      <splash src="icons/screen_1536x2048.png" width="1536" height="2048" />
      <splash src="icons/screen_1024x768.png" width="1024" height="768" />
      <splash src="icons/screen_2048x1536.png" width="2048" height="1536" />
      <splash src="icons/screen_640x1136.png" width="640" height="1136" />
      <splash src="icons/screen_750x1334.png" width="750" height="1334" />
      <splash src="icons/screen_1242x2208.png" width="1242" height="2208" />
      <splash src="icons/screen_2208x1242.png" width="2208" height="1242" />
   </platform>
   <gap:config-file platform="ios" parent="UIViewControllerBasedStatusBarAppearance">
      <false />
   </gap:config-file>
   <preference name="AllowInlineMediaPlayback" value="true" />
   <preference name="DisallowOverscroll" value="true" />
   <preference name="SplashScreen" value="screen" />
   <preference name="SplashScreenDelay" value="5000" />
   <preference name="android-build-tool" value="gradle" />
   <preference name="phonegap-version" value="cli-5.2.0" />
   <preference name="android-minSdkVersion" value="15" />
   <preference name="android-targetSdkVersion" value="15" />
   <preference name="android-installLocation" value="auto" />
</widget>
</code>```

Any help would be appreciated.

Thanks
Rahul

答:
Here's a workaround I've made.

Since you're running the Iframe inside a Cordova container, you can modify it's contents.

The idea is to-

"listen" to the iframe page loaded events

Search for the urls you wish to open outside cordova, then backup-and-remove the href property from the html elements inside the iframe.

Instead of the href property, we assign 'onclick' listeners which will "postMessage" to the parent iFrame container (your Cordova webpage probably), where you can handle the click-event and the url link as you see fit, such as opening it via the InAppBrowserPlugin.

And here's the implementation:

```<code>// Making sure we're in Cordova environment
if(window['cordova']) {
    const linksToModify = [
      // *** Modify *** to the correct selector for your IFrame href elemenets you wish to affect, here's an example (You can put multiple elements here):
      yourIframe.contentWindow.document.querySelector('#html_element > iframe').contentWindow.document.querySelector('body > a:nth-child(1)'),
    ];

    // Once we have a reference to the elements containing the href urls we remove their href property
    // Instead the href property, we "postMessage" to your cordova/phonegap container, where you can handle the href string as you see fit.
    for(let el of linksToModify) {
      let theHref = el.getAttribute('href');
      if(theHref == null) continue;
      try {
        el.removeAttribute('href');
      } catch(_) {}
      try {
        el.removeAttribute('target');
      } catch(_) {}
      // Notify parent iframe of the click instead of opening the url in browser
      el.setAttribute('onclick', "parent.postMessage({type:'fromIframe',event:'open',link:'" + theHref + "'},'*');")
    }
}
</code>```

Modify the element selector for your specific iframe elements which contain href attributes.

Tip-You might want to run the code block after page load under a timer with retries, In my case, I used 15 max retries (1 per second).
Once the element is found and the href attributes are removed, you can cancel the timer of course.

Afterwards, add the listener in the parent container (your Cordova webpage js code):

```<code>window.addEventListener('message', function(thePostedMessage) {
    /// Handle link as you wish, it's in "thePostedMessage" argument.
}
</code>```

Body:
I know we can use inapp browser for opening external links in the app. But I am talking about the links with in iframe, inapp browser solution doesn't work for links inside iframe. I somehow need to open external links from iframe in safari browser of iPhone. Is there a workaround for this ?

Following is my config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0" id="com.ocevent.ocevents" version="0.0.1">
   <name>Live</name>
   <description>Live Eventmanager</description>
   <author email="chh_rahul@live.com" href="http://softweavertech.com">Rahul Chhabra</author>
   <content src="index.html" />
   <allow-navigation href="*" />
   <allow-intent href="http://*/*" />
   <allow-intent href="https://*/*" />
   <allow-intent href="tel:*" />
   <allow-intent href="sms:*" />
   <icon src="icons/iphone_57x57.png" gap:platform="ios" width="57" height="57" />
   <icon src="icons/iphone_72x72.png" gap:platform="ios" width="72" height="72" />
   <icon src="icons/iphone_76x76.png" gap:platform="ios" width="76" height="76" />
   <icon src="icons/iphone_120x120.png" gap:platform="ios" width="120" height="120" />
   <icon src="icons/iphone_152x152.png" gap:platform="ios" width="152" height="152" />
   <icon src="icons/iphone_180x180.png" gap:platform="ios" width="180" height="180" />
   <icon src="icons/LiveIcon.png" gap:platform="android" />

   <plugin name="cordova-plugin-camera" />
   <gap:plugin name="cordova-plugin-file" source="pgb" />
   <gap:plugin name="cordova-plugin-customurlscheme" source="npm">
      <param name="URL_SCHEME" value="live" />
   </gap:plugin>
   <plugin name="cordova-plugin-whitelist" />

   <gap:plugin name="cordova-plugin-file-transfer" source="pgb" />
   <gap:plugin name="cordova-plugin-dialogs" source="pgb" />
   <gap:plugin name="cordova-plugin-media-capture" source="pgb" />
   <gap:plugin name="cordova-plugin-splashscreen" source="pgb" />
   <gap:config-file platform="ios" parent="UIStatusBarHidden">
      <true />
   </gap:config-file>
   <platform name="android">

      <splash src="icons/screen_640x960.png" density="land-hdpi" />
      <splash src="icons/screen_640x960.png" density="land-ldpi" />
      <splash src="icons/screen_640x960.png" density="land-mdpi" />
      <splash src="icons/screen_640x960.png" density="land-xhdpi" />
      <splash src="icons/screen_640x960.png" density="port-hdpi" />
      <splash src="icons/screen_640x960.png" density="port-ldpi" />
      <splash src="icons/screen_640x960.png" density="port-mdpi" />
      <splash src="icons/screen_640x960.png" density="port-xhdpi" />
   </platform>
   <platform name="ios">

      <splash src="icons/screen_320x480.png" width="320" height="480" />
      <splash src="icons/screen_640x960.png" width="640" height="960" />
      <splash src="icons/screen_768x1024.png" width="768" height="1024" />
      <splash src="icons/screen_1536x2048.png" width="1536" height="2048" />
      <splash src="icons/screen_1024x768.png" width="1024" height="768" />
      <splash src="icons/screen_2048x1536.png" width="2048" height="1536" />
      <splash src="icons/screen_640x1136.png" width="640" height="1136" />
      <splash src="icons/screen_750x1334.png" width="750" height="1334" />
      <splash src="icons/screen_1242x2208.png" width="1242" height="2208" />
      <splash src="icons/screen_2208x1242.png" width="2208" height="1242" />
   </platform>
   <gap:config-file platform="ios" parent="UIViewControllerBasedStatusBarAppearance">
      <false />
   </gap:config-file>
   <preference name="AllowInlineMediaPlayback" value="true" />
   <preference name="DisallowOverscroll" value="true" />
   <preference name="SplashScreen" value="screen" />
   <preference name="SplashScreenDelay" value="5000" />
   <preference name="android-build-tool" value="gradle" />
   <preference name="phonegap-version" value="cli-5.2.0" />
   <preference name="android-minSdkVersion" value="15" />
   <preference name="android-targetSdkVersion" value="15" />
   <preference name="android-installLocation" value="auto" />
</widget>

Any help would be appreciated.

Thanks
Rahul

Body:
Here's a workaround I've made.

Since you're running the Iframe inside a Cordova container, you can modify it's contents.

The idea is to-

"listen" to the iframe page loaded events

Search for the urls you wish to open outside cordova, then backup-and-remove the href property from the html elements inside the iframe.

Instead of the href property, we assign 'onclick' listeners which will "postMessage" to the parent iFrame container (your Cordova webpage probably), where you can handle the click-event and the url link as you see fit, such as opening it via the InAppBrowserPlugin.

And here's the implementation:

// Making sure we're in Cordova environment
if(window['cordova']) {
    const linksToModify = [
      // *** Modify *** to the correct selector for your IFrame href elemenets you wish to affect, here's an example (You can put multiple elements here):
      yourIframe.contentWindow.document.querySelector('#html_element > iframe').contentWindow.document.querySelector('body > a:nth-child(1)'),
    ];

    // Once we have a reference to the elements containing the href urls we remove their href property
    // Instead the href property, we "postMessage" to your cordova/phonegap container, where you can handle the href string as you see fit.
    for(let el of linksToModify) {
      let theHref = el.getAttribute('href');
      if(theHref == null) continue;
      try {
        el.removeAttribute('href');
      } catch(_) {}
      try {
        el.removeAttribute('target');
      } catch(_) {}
      // Notify parent iframe of the click instead of opening the url in browser
      el.setAttribute('onclick', "parent.postMessage({type:'fromIframe',event:'open',link:'" + theHref + "'},'*');")
    }
}

Modify the element selector for your specific iframe elements which contain href attributes.

Tip-You might want to run the code block after page load under a timer with retries, In my case, I used 15 max retries (1 per second).
Once the element is found and the href attributes are removed, you can cancel the timer of course.

Afterwards, add the listener in the parent container (your Cordova webpage js code):

window.addEventListener('message', function(thePostedMessage) {
    /// Handle link as you wish, it's in "thePostedMessage" argument.
}


Title: In python. Use the format of one list to another list

Body:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

I want the list3 be like this:

list 3 = [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]

I had already get the index of the list1 like that:

index_list = [[0, 1], [2], [3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13], [14], [15], [16, 17], [18], [19], [20]]

Body:
Straightforwardly:

list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]
list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

result = []
c = 0
for item in list1:
    item_len = len(item)
    result.append(list2[c: c+item_len])
    c += item_len

print(result)

The output:

[[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]


问:
How to parallelize an IEnumerable with a slow yield (which renders PLINQ useless)?
I'm having some trouble finding a way to properly parallelize the processing of an IEnumerable, where the actual generation of each item takes a considerable amount of time, so it effectively locks for a bit every call to MoveNext on the reader side.

This is my scenario:

I have a method that takes an IEnumerable<(float[], float[])> (the specific type doesn't actually matter here), and I need to compute those items, split them into batches of a fixed side, then process every batch.

Assume I already have the partition code ready (see this answer here) as well as the code to process each individual partition.

The problem is that, as I've said, yielding every value from the initial list involves some IO/CPU operations (one would typically read an image, process it and return those two matrices with), so even with:

```<code>var items = dataset.AsParallel().Partition(size).ToArray().AsParallel().Select(partition =>
{
    // Process the partitions here..
    return partition;
}).ToArray(); // Two AsParallel calls because I'm doing two selections one after the other
</code>```

I get around 25% CPU usage (I have an 8-cores AMD FX-8350), because I guess it's the actual generation of the items in the first list that causes the enumeration to be slow, before even getting to the first AsParallel call.

I was thinking a possible solution would be to require the user of this method to instead provide an IEnumerable<Func<(float[], float[])>>, as that would allow my method to easily process those elements in parallel.

My question is: is this the only possible solution, or is there another way to enumerate a "locking" IEnumerable in parallel, without having this slowdown causing to each item being yielded not in parallel?

Thanks!

Edit: to clarify, I am not writing the actual code in the first IEnumerable, that's up to the user of the library in question, which will input its own IEnumerable for the library to split into batches and work on.
One of the reasons why I was hoping there'd be an alternative to a Func delegate was because, on the user side, just returning a tuple would be easier and more intuitive than having to explicitly return a function that lazily computes the whole thing.

答:
I'm afraid you can't. If that initial IEnumerable is slow, there is nothing you can do as a second step, no matter how many resources in terms of parallelization and processing power you employ, to make it faster. Best case scenario is you add as little as possible. But it's still slow.

The solution would be to see if maybe the original, initial sequence can be sped up by any means.

Body:
I'm having some trouble finding a way to properly parallelize the processing of an IEnumerable, where the actual generation of each item takes a considerable amount of time, so it effectively locks for a bit every call to MoveNext on the reader side.

This is my scenario:

I have a method that takes an IEnumerable<(float[], float[])> (the specific type doesn't actually matter here), and I need to compute those items, split them into batches of a fixed side, then process every batch.

Assume I already have the partition code ready (see this answer here) as well as the code to process each individual partition.

The problem is that, as I've said, yielding every value from the initial list involves some IO/CPU operations (one would typically read an image, process it and return those two matrices with), so even with:

var items = dataset.AsParallel().Partition(size).ToArray().AsParallel().Select(partition =>
{
    // Process the partitions here..
    return partition;
}).ToArray(); // Two AsParallel calls because I'm doing two selections one after the other

I get around 25% CPU usage (I have an 8-cores AMD FX-8350), because I guess it's the actual generation of the items in the first list that causes the enumeration to be slow, before even getting to the first AsParallel call.

I was thinking a possible solution would be to require the user of this method to instead provide an IEnumerable<Func<(float[], float[])>>, as that would allow my method to easily process those elements in parallel.

My question is: is this the only possible solution, or is there another way to enumerate a "locking" IEnumerable in parallel, without having this slowdown causing to each item being yielded not in parallel?

Thanks!

Edit: to clarify, I am not writing the actual code in the first IEnumerable, that's up to the user of the library in question, which will input its own IEnumerable for the library to split into batches and work on.
One of the reasons why I was hoping there'd be an alternative to a Func delegate was because, on the user side, just returning a tuple would be easier and more intuitive than having to explicitly return a function that lazily computes the whole thing.


问:
modifying getDate function's value in javascript
i did convert value from date input to text input (in html) using javascript to change the format from mm/dd/yyyy to dd/mm/yyyy.
and it works. but the value become 2/12/2017 from 12/02/2017.

i need it to become 02/12/2017 (not 2/12/2017). how to put the '0' for date under 10?

here's my code:

```<code>function mydate1()
{
    d=new Date(document.getElementById("date").value); //fetching date input's value
    dt=d.getDate(); //fetching date
    mn=d.getMonth(); //fetching month
    mn++;
    yy=d.getFullYear(); //fetching year
    document.getElementById("ndt").value=dt+"/"+mn+"/"+yy //inserting value to text input
    document.getElementById("ndt").hidden=false;
    document.getElementById("dt").hidden=true;}
</code>```

答:
I use this trick:

```<code>("0" + d.getDate()).slice(-2)
</code>```

and for the month:

```<code>("0" + (d.getMonth() + 1)).slice(-2)
</code>```

Body:
i did convert value from date input to text input (in html) using javascript to change the format from mm/dd/yyyy to dd/mm/yyyy.
and it works. but the value become 2/12/2017 from 12/02/2017.

i need it to become 02/12/2017 (not 2/12/2017). how to put the '0' for date under 10?

here's my code:

function mydate1()
{
    d=new Date(document.getElementById("date").value); //fetching date input's value
    dt=d.getDate(); //fetching date
    mn=d.getMonth(); //fetching month
    mn++;
    yy=d.getFullYear(); //fetching year
    document.getElementById("ndt").value=dt+"/"+mn+"/"+yy //inserting value to text input
    document.getElementById("ndt").hidden=false;
    document.getElementById("dt").hidden=true;}

Body:
I use this trick:

("0" + d.getDate()).slice(-2)

and for the month:

("0" + (d.getMonth() + 1)).slice(-2)


答:
What about Cut >> Paste:

```<code>ActiveSheet.UsedRange.Cut
ActiveSheet.Paste Range("A1")
</code>```

or, as @JohnyL suggested in comment, use short version:

```<code>ActiveSheet.UsedRange.Cut Range("A1")
</code>```

Title: How to shift an excel UsedRange to begin at cell A1 its worksheet (i.e. delete all blank rows and columns outside UsedRange)?

Body:
What about Cut >> Paste:

ActiveSheet.UsedRange.Cut
ActiveSheet.Paste Range("A1")

or, as @JohnyL suggested in comment, use short version:

ActiveSheet.UsedRange.Cut Range("A1")


问:
adding multiple values to python dictionary
I am using the code below to go over a bunch of strings that have date and time data. I am making a dictionary that has the keys based on the day in the month if there is a string present. After that I want to put the time-stamp for that day as the value. Since there are multiple strings for each day I want to have multiple values for one key.

The current code is able to make keys for each day were a string with data appears but when adding the time-stamp it seems to be writing over it each time and not adding to it. How can I add multiple values to the key rather than just replacing it each time.

```<code>for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta.update({day.encode("ascii"):[trigger_time]})
        #dicta[day.encode("ascii")].append[trigger_time]
</code>```

The commented line was an attempt but I get this error, AttributeError: 'int' object has no attribute 'append'

答:
That is how dictionaries work, there can only be one value for a given key.

To achieve what you are trying to do you can use a list as the value.

```<code>from collections import defaultdict
dicta = defaultdict(list) #<===== See here

for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta[day.encode("ascii")].append(trigger_time) #<===== See here
</code>```

Body:
I am using the code below to go over a bunch of strings that have date and time data. I am making a dictionary that has the keys based on the day in the month if there is a string present. After that I want to put the time-stamp for that day as the value. Since there are multiple strings for each day I want to have multiple values for one key.

The current code is able to make keys for each day were a string with data appears but when adding the time-stamp it seems to be writing over it each time and not adding to it. How can I add multiple values to the key rather than just replacing it each time.

for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta.update({day.encode("ascii"):[trigger_time]})
        #dicta[day.encode("ascii")].append[trigger_time]

The commented line was an attempt but I get this error, AttributeError: 'int' object has no attribute 'append'

Body:
That is how dictionaries work, there can only be one value for a given key.

To achieve what you are trying to do you can use a list as the value.

from collections import defaultdict
dicta = defaultdict(list) #<===== See here

for entry in data:
    month_year = entry[0:7]
    if month_year == month:
        day = entry[8:10]
        trigger_time = entry[11:19]
        print month_year
        dicta[day.encode("ascii")].append(trigger_time) #<===== See here


问:
syntax error in from clause. vb.net
I'm getting syntax error in from clause in my vb.net softwware, can any one help me????</p>

```<code>Private Sub txtSearchByDish_TextChanged(sender As Object, e As EventArgs) Handles txtSearchByDish.TextChanged
    Try
        con = New OleDbConnection(cs)
        con.Open()
        cmd = New OleDbCommand("SELECT DishName, I.Rate, SUM([Qty]) as ItemQuantity, BillDate, ( I.Rate * SUM([Qty])) As TotalAmount FROM Dish as I, RestaurantBillingInfo as P, RestaurantBillingItems as PD, WHERE DishName like '" & txtSearchByDish.Text & "%' order by DishName", con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgw.Rows.Clear()
        While (rdr.Read() = True)
            dgw.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3), rdr(4))
        End While
        con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
</code>```

答:
You can't end your FROM clause with a comma.

Change RestaurantBillingItems as PD, WHERE

To RestaurantBillingItems as PD WHERE

Note that your program is your program is vulnerable to SQL injection

Also note you're using aggregates and are not grouping by BillDate, DishName and I.Rate and they're not aggregates. You probably want to either use aggregates for them, or group by them, e.g. GROUP BY BillDate, DishName, I.Rate

Title: syntax error in from clause. vb.net

Body:
I'm getting syntax error in from clause in my vb.net softwware, can any one help me????

Private Sub txtSearchByDish_TextChanged(sender As Object, e As EventArgs) Handles txtSearchByDish.TextChanged
    Try
        con = New OleDbConnection(cs)
        con.Open()
        cmd = New OleDbCommand("SELECT DishName, I.Rate, SUM([Qty]) as ItemQuantity, BillDate, ( I.Rate * SUM([Qty])) As TotalAmount FROM Dish as I, RestaurantBillingInfo as P, RestaurantBillingItems as PD, WHERE DishName like '" & txtSearchByDish.Text & "%' order by DishName", con)
        rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgw.Rows.Clear()
        While (rdr.Read() = True)
            dgw.Rows.Add(rdr(0), rdr(1), rdr(2), rdr(3), rdr(4))
        End While
        con.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub


问:
Odoo python programming language
In V10, How can I put control on generation of Automatic sequence numbers ? For example, If we take Employee Id. When we create Employee Id, a sequence like EMP-0001 is generated. Suppose we discarded it without Saving. Next time when we create a new Employee Id the sequence we are getting is EMP-0002. How to prevent this? Please give the answer in odoo 10 </p>

答:
First you have to insert a field for the Employee ID.Like below !

```<code>name = fields.Char(string="Employee ID", Index= True, default=lambda self:('New'), readonly=True)
</code>```

Afterwards you have to create a file named as ir_sequence.xml in views folder.Write the code as like below.

```<code><odoo>
    <data>
    <record id="seq_bi_ticket" model="ir.sequence">
            <field name="name"> [NAME] </field>
            <field name="code">[class_name]</field>
            <field name="prefix"> EMP </field>
            <field name="padding"> 5 </field>
            <!-- The length of the number you need is 5 -->
            <field name="company_id" eval="False"/>
        </record>
    </data>
</odoo>
</code>```

Also have to write function inside the main class along with that field which I said above.The function code is here below:

```<code>@api.model
    def create(self, vals):
        if vals.get('name', _('New')) == _('New'):
            if 'company_id' in vals:
                vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code('[CLASS_NAME]') or _('New')
            else:
                vals['name'] = self.env['ir.sequence'].next_by_code('[CLASS_NAME]') or _('New')
        result = super([CLASS_NAME], self).create(vals)
        return result
</code>```

It's over . Thus you go !!!

Title: Odoo python programming language

Body:
First you have to insert a field for the Employee ID.Like below !

name = fields.Char(string="Employee ID", Index= True, default=lambda self:('New'), readonly=True)

Afterwards you have to create a file named as ir_sequence.xml in views folder.Write the code as like below.

<odoo>
    <data>
    <record id="seq_bi_ticket" model="ir.sequence">
            <field name="name"> [NAME] </field>
            <field name="code">[class_name]</field>
            <field name="prefix"> EMP </field>
            <field name="padding"> 5 </field>
            <!-- The length of the number you need is 5 -->
            <field name="company_id" eval="False"/>
        </record>
    </data>
</odoo>

Also have to write function inside the main class along with that field which I said above.The function code is here below:

@api.model
    def create(self, vals):
        if vals.get('name', _('New')) == _('New'):
            if 'company_id' in vals:
                vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code('[CLASS_NAME]') or _('New')
            else:
                vals['name'] = self.env['ir.sequence'].next_by_code('[CLASS_NAME]') or _('New')
        result = super([CLASS_NAME], self).create(vals)
        return result

It's over . Thus you go !!!


问:
Robolectric + PowerMock + Mockito not working
I'm struggling to get this rare combination works, but I haven't got luck. My project uses JUnit + Mockito + Robolectric for testing and Roboguice for injection, when I added PowerMock to the equation weird things happened, this are some of the things I've tried:

1.- Out of the box PowerMock + Mockito + Robolectic integration. As suggested on PowerMockIngration, I added a @PowerMockRunnerDelegate to include my custom runner which extends from RobolectricGradleTestRunner:

Build.gradle

```<code>  testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'
</code>```

Test

```<code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MyCustomRunner.class)
@Config(constants = BuildConfig.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest(RoboGuice.class)
public class Test {

  @Before
  public void setUp() throws Exception {
    PowerMockito.mockStatic(RoboGuice.class);
    ....
  }
</code>```

Result:

```<code>java.lang.IllegalArgumentException: Cannot subclass final class class roboguice.RoboGuice at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)
 at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
    at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
    at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:57)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:59)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
    at com.humana.vitalityapp.activity.BaseVitalityActivityTest.setUp(BaseVitalityActivityTest.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:146)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:139)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:130)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:139)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)...
</code>```

So is like @PrepareForTest is nor working, then I tried when a rule a class loader, as suggested in the same guide:

Build.gradle

```<code>  testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'
  testCompile "org.powermock:powermock-classloading-xstream:1.6.4"
</code>```

Test Class

```<code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MyCustomRunner.class)
@Config(constants = BuildConfig.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest(RoboGuice.class)
public class Test {
  @Rule public PowerMockRule rule = new PowerMockRule();

@Before
  public void setUp() throws Exception {
    PowerMockito.mockStatic(RoboGuice.class);
   ...
  }
</code>```

At this point the test passes and I was able to mock RoboGuice as expected, BUT when I ran all my test cases together I start getting the following exception when creating a simple mock like mock(OtherClass.class):

```<code>org.mockito.exceptions.base.MockitoException:
ClassCastException occurred while creating the mockito proxy :
  class to mock : 'com.humana.vitalityapp.analytics.Analytics', loaded by classloader : 'org.powermock.core.classloader.MockClassLoader@168fa63d'
  created class : 'com.humana.vitalityapp.analytics.Analytics$$EnhancerByMockitoWithCGLIB$$67cb81b1', loaded by classloader : 'org.mockito.internal.creation.util.SearchingClassLoader@20f5a6b6'
  proxy instance class : 'com.humana.vitalityapp.analytics.Analytics$$EnhancerByMockitoWithCGLIB$$67cb81b1', loaded by classloader : 'org.robolectric.internal.bytecode.InstrumentingClassLoader@6fdbe764'
  instance creation by : ObjenesisInstantiator

You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)

    at com.humana.vitalityapp.activity.BaseVitalityActivityTest.setUp(BaseVitalityActivityTest.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
</code>```

So I tried a lots of variants:
Remove the xtream class loader:

```<code>  java.lang.RuntimeException: java.lang.ClassNotFoundException: org.powermock.classloading.DeepCloner

    at org.powermock.api.support.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:68)
    at org.powermock.api.support.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:34)
</code>```

User JunitAgent:

```<code> testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile "org.powermock:powermock-module-junit4-rule-agent:1.6.4"
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'

Caused by: java.lang.IllegalStateException: PowerMockRule can only be used with the system classloader but was loaded by org.robolectric.internal.bytecode.InstrumentingClassLoader@2a7f1f10
</code>```

So I running out of ideas, anyone??

答:
I had the same problem.

My solution was to:

remove testCompile "org.powermock:powermock-module-junit4-rule-agent:x.x.x" from gradle

change import static *.Mockito.mock and *.Mockito.when to org.powermock.api.mockito.PowerMockito.mock and org.powermock.api.mockito.PowerMockito.when.

Body:
I'm struggling to get this rare combination works, but I haven't got luck. My project uses JUnit + Mockito + Robolectric for testing and Roboguice for injection, when I added PowerMock to the equation weird things happened, this are some of the things I've tried:

1.- Out of the box PowerMock + Mockito + Robolectic integration. As suggested on PowerMockIngration, I added a @PowerMockRunnerDelegate to include my custom runner which extends from RobolectricGradleTestRunner:

Build.gradle

  testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'

Test

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MyCustomRunner.class)
@Config(constants = BuildConfig.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest(RoboGuice.class)
public class Test {

  @Before
  public void setUp() throws Exception {
    PowerMockito.mockStatic(RoboGuice.class);
    ....
  }

Result:

java.lang.IllegalArgumentException: Cannot subclass final class class roboguice.RoboGuice at org.mockito.cglib.proxy.Enhancer.generateClass(Enhancer.java:447)
 at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217)
    at org.mockito.cglib.proxy.Enhancer.createHelper(Enhancer.java:378)
    at org.mockito.cglib.proxy.Enhancer.createClass(Enhancer.java:318)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.createProxyClass(ClassImposterizer.java:123)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:57)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.createMethodInvocationControl(MockCreator.java:111)
    at org.powermock.api.mockito.internal.mockcreation.MockCreator.mock(MockCreator.java:59)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:70)
    at com.humana.vitalityapp.activity.BaseVitalityActivityTest.setUp(BaseVitalityActivityTest.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:146)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner$2.call(DelegatingPowerMockRunner.java:139)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.withContextClassLoader(DelegatingPowerMockRunner.java:130)
    at org.powermock.modules.junit4.internal.impl.DelegatingPowerMockRunner.run(DelegatingPowerMockRunner.java:139)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)...

So is like @PrepareForTest is nor working, then I tried when a rule a class loader, as suggested in the same guide:

Build.gradle

  testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'
  testCompile "org.powermock:powermock-classloading-xstream:1.6.4"

Test Class

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(MyCustomRunner.class)
@Config(constants = BuildConfig.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest(RoboGuice.class)
public class Test {
  @Rule public PowerMockRule rule = new PowerMockRule();

@Before
  public void setUp() throws Exception {
    PowerMockito.mockStatic(RoboGuice.class);
   ...
  }

At this point the test passes and I was able to mock RoboGuice as expected, BUT when I ran all my test cases together I start getting the following exception when creating a simple mock like mock(OtherClass.class):

org.mockito.exceptions.base.MockitoException:
ClassCastException occurred while creating the mockito proxy :
  class to mock : 'com.humana.vitalityapp.analytics.Analytics', loaded by classloader : 'org.powermock.core.classloader.MockClassLoader@168fa63d'
  created class : 'com.humana.vitalityapp.analytics.Analytics$$EnhancerByMockitoWithCGLIB$$67cb81b1', loaded by classloader : 'org.mockito.internal.creation.util.SearchingClassLoader@20f5a6b6'
  proxy instance class : 'com.humana.vitalityapp.analytics.Analytics$$EnhancerByMockitoWithCGLIB$$67cb81b1', loaded by classloader : 'org.robolectric.internal.bytecode.InstrumentingClassLoader@6fdbe764'
  instance creation by : ObjenesisInstantiator

You might experience classloading issues, disabling the Objenesis cache *might* help (see MockitoConfiguration)

    at com.humana.vitalityapp.activity.BaseVitalityActivityTest.setUp(BaseVitalityActivityTest.java:77)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.powermock.modules.junit4.rule.PowerMockStatement$1.run(PowerMockRule.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)

So I tried a lots of variants:
Remove the xtream class loader:

  java.lang.RuntimeException: java.lang.ClassNotFoundException: org.powermock.classloading.DeepCloner

    at org.powermock.api.support.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:68)
    at org.powermock.api.support.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:34)

User JunitAgent:

 testCompile 'org.powermock:powermock-module-junit4:1.6.4'
  testCompile "org.powermock:powermock-module-junit4-rule-agent:1.6.4"
  testCompile 'org.powermock:powermock-api-mockito:1.6.4'

Caused by: java.lang.IllegalStateException: PowerMockRule can only be used with the system classloader but was loaded by org.robolectric.internal.bytecode.InstrumentingClassLoader@2a7f1f10

So I running out of ideas, anyone??


问:
Specific css transitioning
I want to store some images offscreen, which get activated by a button:active.

Styles:

```<code>.image {
    opacity: 0;
    position: fixed;
    top: -500px;
    left: 20%;
    transition:0.5s;
 }
 .button1:active .image01 {
    opacity: 1;
    top:5%;
    left:20%;
 }
</code>```

I want them to fade in from opacity 0 to opacity 1.
However, when I put in a transition attribute, it animates both the opacity and the position. Is there any way to only animate the opacity and make the position change instant?

答:
Simply add the property (opacity in your case) to the transition like this :

```<code>.image {
    opacity: 0;
    position: fixed;
    top: -500px;
    left: 20%;
    transition:opacity 0.5s;
 }
 .button1:active .image01 {
    opacity: 1;
    top:5%;
    left:20%;
 }
</code>```

the transtion has 4 properties than can be defined separately like this :

```<code>transition-property: opacity; /*Default value is all */
transition-duration: 2s; /* Default value is 0 (no transition effect) */
transition-timing-function: linear; /* Default value is linear */
transition-delay: 1s; /* Default value is 0 */
</code>```

or by using the shorthand property :

```<code>transition: opacity 2s linear 1s;
</code>```

So if you omit some properties they will take the default values.

Read more about transition

Title: Specific css transitioning

Body:
I want to store some images offscreen, which get activated by a button:active.

Styles:

.image {
    opacity: 0;
    position: fixed;
    top: -500px;
    left: 20%;
    transition:0.5s;
 }
 .button1:active .image01 {
    opacity: 1;
    top:5%;
    left:20%;
 }

I want them to fade in from opacity 0 to opacity 1.
However, when I put in a transition attribute, it animates both the opacity and the position. Is there any way to only animate the opacity and make the position change instant?

Body:
Simply add the property (opacity in your case) to the transition like this :

.image {
    opacity: 0;
    position: fixed;
    top: -500px;
    left: 20%;
    transition:opacity 0.5s;
 }
 .button1:active .image01 {
    opacity: 1;
    top:5%;
    left:20%;
 }

the transtion has 4 properties than can be defined separately like this :

transition-property: opacity; /*Default value is all */
transition-duration: 2s; /* Default value is 0 (no transition effect) */
transition-timing-function: linear; /* Default value is linear */
transition-delay: 1s; /* Default value is 0 */

or by using the shorthand property :

transition: opacity 2s linear 1s;

So if you omit some properties they will take the default values.

Read more about transition


问:
Which thread does Runnable run on?
I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable and Handler like this

```<code>final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run();
</code>```

It works! But I have some questions:

Which thread does this Runnable run on? MainThread or another thread? Here is the docs about postDelay

Handler is attached MainThread, so is Runnable running on MainThread?

If Runnable is running on MainThread, why needs Handler? According to my knowledge, Handler is used to send messages between two threads

答:
In your example, the Runnable runs on the UI Thread.

If you want your Handler and all its Runnable to run in a different Thread, you'll have to assign it a a new HandlerThread's Looper.

```<code>final HandlerThread handlerThread = new HandlerThread(MY_THREAD_ID);
handlerThread.start();
final Handler handler = new Handler(handlerThread.getLooper());
</code>```

You can then pass the Runnable instance via postDelayed(Runnable, long).

```<code>Runnable r = new Runnable() {
    @Override public void run() {
        handler.postDelayed(this, 2000);
    }
};

handler.postDelayed(r, 0);
</code>```

Title: Which thread does Runnable run on?

Body:
I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable and Handler like this

final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        //update UI here

        handler.postDelayed(this, 100);
    }
};
runnable.run();

It works! But I have some questions:

Which thread does this Runnable run on? MainThread or another thread? Here is the docs about postDelay

Handler is attached MainThread, so is Runnable running on MainThread?

If Runnable is running on MainThread, why needs Handler? According to my knowledge, Handler is used to send messages between two threads

Body:
In your example, the Runnable runs on the UI Thread.

If you want your Handler and all its Runnable to run in a different Thread, you'll have to assign it a a new HandlerThread's Looper.

final HandlerThread handlerThread = new HandlerThread(MY_THREAD_ID);
handlerThread.start();
final Handler handler = new Handler(handlerThread.getLooper());

You can then pass the Runnable instance via postDelayed(Runnable, long).

Runnable r = new Runnable() {
    @Override public void run() {
        handler.postDelayed(this, 2000);
    }
};

handler.postDelayed(r, 0);


问:
Playing sound files one after another in flex AIR code
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

```<code>    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }
</code>```

Thanks
Sumit

答: The problem is you are spawning multiple asynchronous calls. Implement a complete call back function on Sound and then call your playThisClip  function inside the callback function. (You can sleep for predefined time before calling)</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }

Thanks
Sumit


问:
Set the value in the SELECT map
I am trying to send map to the front end. If i put an atom in the key like in the code below it works fine.

```<code>defp build_select(queryable, opts_select) do
  if opts_select ==  nil do
    queryable
  else
    Enum.reduce opts_select, queryable, fn ({k, v}, queryable) ->
      a = from q in queryable,
        select: %{Data: field(q, ^(String.to_existing_atom k))}

    end
  end
end
</code>```

But i want to send the k value instead of Data. How would i do that? K is a string.

I tried converting the value of k into atom and using it but its not working.

答:
You can use map with an interpolated list of fields.</p>

```<code>select_list = Enum.map(opts_select, fn {k, _v} -> String.to_existing_atom(k) end)

from q in queryable,
select: map(q, ^select_list)
</code>```

Title: Set the value in the SELECT map

Body:
I am trying to send map to the front end. If i put an atom in the key like in the code below it works fine.

defp build_select(queryable, opts_select) do
  if opts_select ==  nil do
    queryable
  else
    Enum.reduce opts_select, queryable, fn ({k, v}, queryable) ->
      a = from q in queryable,
        select: %{Data: field(q, ^(String.to_existing_atom k))}

    end
  end
end

But i want to send the k value instead of Data. How would i do that? K is a string.

I tried converting the value of k into atom and using it but its not working.

Body:
You can use map with an interpolated list of fields.

select_list = Enum.map(opts_select, fn {k, _v} -> String.to_existing_atom(k) end)

from q in queryable,
select: map(q, ^select_list)


问:
Flink with Ceph as the persistent storage
Flink documents suggests that Ceph can be used as a persistent storage for states. https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/stream/checkpointing.html

Considering that Ceph is a transactional database, wouldn't it have adverse effect on Flink's performance?

答:
Ceph describes itself as a "unified, distributed storage system" and provides a network file system API. As such, it such should be seamlessly working with Flink's state backends that persist checkpoints to a remote file system.

I'm not aware of people using Ceph (HDFS and S3 are more commonly used) and have no information about the performance. However, note that Flink is able to write checkpoints asynchronously, such that the performance of the storage system does not affect the processing speed of a Flink application. It might however, constrain the interval in which checkpoints are taken.

Update:
(Feb. 2018) I noticed that multiple users reported on Flink's user mailing list that they are using Ceph with Flink.

Update 2:
Flink is working fine with S3 protocol and both (Presto & Hadoop) Flink's S3 FileSystem plugins are working fine with it.


问:
Oracle Apex ORA-00922: missing or invalid option
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

```<code>CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/
</code>```

So what could be the problem?

答:
Try this.

```<code>CREATE TABLE  "PROD_INDEX"
   (
    "PNO" NUMBER (4,0) PRIMARY KEY,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2)
   )
</code>```

Also, it is considered bad practice to name your columns after Oracle reserved words (e.g. date)

Body:
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/

So what could be the problem?

Body:
Try this.

CREATE TABLE  "PROD_INDEX"
   (
    "PNO" NUMBER (4,0) PRIMARY KEY,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2)
   )

Also, it is considered bad practice to name your columns after Oracle reserved words (e.g. date)