问:
Simple JS menu toggle
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day

```

答:
I found my error.

In my JS file, on line 12 there is a typo when assigning the variable.

let getSideBarUTitle = document.querySelector(".nav-sidebar span");

should be

let getSideBarTitle = document.querySelector(".nav-sidebar span");

Title: Simple JS menu toggle

Body:
I am pretty new to JavaScript and decided to code a menu that opens/expands when you click a button and closes when you click the button again.

I got everything to work but I cannot seem to find why the menu isn't closing.

Here is my code:

Any help or guidance is much appreciated!
I have included my HTML, CSS and JS files.

let toggleNavStatus = false;

let toggleNav = function (){
    let getSideBar = document.querySelector(".nav-sidebar");
    let getSideBarUl = document.querySelector(".nav-sidebar ul");
    let getSideBarUTitle = document.querySelector(".nav-sidebar span");
    let getSideBarLinks = document.querySelectorAll(".nav-sidebar a");

    if(toggleNavStatus === false){
        getSideBarUl.style.visibility = "visible";
        getSideBar.style.width = "295px";
        getSideBarTitle.style.opacity = "0.5";

        let arrayLenght = getSideBarLinks.length;
        for(let i = 0; i < arrayLenght; i++){
            getSideBarLinks[i].style.opacity = "1";
        }
        toggleNavStatus = true;
  } else if(toggleNavStatus === true){
    getSideBarUl.style.visibility = "hidden";
    getSideBar.style.width = "50px";
    getSideBarTitle.style.opacity = "0";

    let arrayLenght = getSideBarLinks.length;
    for(let i = 0; i < arrayLenght; i++){
        getSideBarLinks[i].style.opacity = "0";
    }
    toggleNavStatus = false;
    }
}

body {
    background-color: #F1F1F1;
}

.nav-main{
    width: 100%;
    height: 60px;
    background-color: #FFF;
    display: flex;
    flex-wrap: wrap;
    z-index: 1000;
    position: fixed;
    top: 0;
}

.btn-toggle-nav{
    width: 60px;
    height: 100%;
    background-color: #f98f39;
    background-size: 50%;
    background-position: center;
    cursor: pointer;
    position: fixed;
    left: 0;
}

.btn-toggle-nav:hover{
    opacity: 0.5;
}

.nav-main ul{
    display: flex;
    flex-wrap: wrap;
    padding-left: 60px;
}

.nav-main ul li{
    list-style: none;
    line-height: 30px;
}

.nav-main ul li a{
    display: block;
    height: 100%;
    padding: 0 10px;
    text-transform: uppercase;
    text-decoration: none;
    color: #111;
    font-family: Arial;
    font-size: 16px;
}
 .nav-sidebar{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 50px;
    padding: 0 5px;
    height: calc(100vh - 60px);
    background-color: #1B1B1B;
    z-index: 1000;
 }

 .nav-sidebar ul{
    padding-top: 15px;
    overflow: hidden;
    visibility: hidden;
 }

 .nav-sidebar ul li{
    line-height: 60px;
    list-style: none;
 }

 .nav-sidebar ul li span, ul li a{
    display: block;
    height: 60px;
    padding: 0 10px;
    text-decoration: none;
    text-transform: uppercase;
    color: #FFF;
    font-family: arial;
    font-size: 16px;
    white-space: nowrap;
    opacity: 0.5;
 }

 .nav-sidebar ul li a:hover{
     background-color: #222;
 }

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ZiGi's Toggle Menu</title>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="resetstyle.css">

  Home

  Portfolio

  About Us

  Gallery

  Contact

 Projects

  Making a Website

  SEAO Optimizing Video

  Walking Through The Park

  Just Another Day


来源: stackexchange

问:
How to search AD Global Caalogue rather than Domain Controller?
I have some c# code that successfully searches a domain however our customer is saying that it needs to search the global catalogue. How easy is this? Does it make any sense?</p>

答:
Firs of all Global Catalog is a Directory. Programaticaly, it can be queried exactly in the same way as Active-Directory.

You just have to find the GCs adresses and ports. It can be easily done, querying the DNS of you client domain for service (SRV) entries  _gc._tcp.DNSDomain. The entries will give you the DNS adress and the port (generally 3268) of the global catalogs present.

Here is the Nslookup example :

```<code>> set type=srv
> _gc._tcp.societe.fr
Serveur :  srventr2.societe.fr
Address:  192.168.183.138

_gc._tcp.societe.fr     SRV service location:
          priority       = 0
          weight         = 100
          port           = 3268
          svr hostname   = srventr2.societe.fr
srventr2.societe.fr     internet address = 192.168.183.138
</code>```

After that, you can search the Global Catalog exactly in the same way as a normal directory. As you can read in comments it's only interresting if you've got multiple domains in your forest. This is because all the objects of all domains of the forest can be found in the GC, but be carefull for each object all the attributes are not present (as specified in the SCHEMA).

ContentLicense: CC BY-SA 3.0

Body:
Firs of all Global Catalog is a Directory. Programaticaly, it can be queried exactly in the same way as Active-Directory.

You just have to find the GCs adresses and ports. It can be easily done, querying the DNS of you client domain for service (SRV) entries  _gc._tcp.DNSDomain. The entries will give you the DNS adress and the port (generally 3268) of the global catalogs present.

Here is the Nslookup example :

> set type=srv
> _gc._tcp.societe.fr
Serveur :  srventr2.societe.fr
Address:  192.168.183.138

_gc._tcp.societe.fr     SRV service location:
          priority       = 0
          weight         = 100
          port           = 3268
          svr hostname   = srventr2.societe.fr
srventr2.societe.fr     internet address = 192.168.183.138

After that, you can search the Global Catalog exactly in the same way as a normal directory. As you can read in comments it's only interresting if you've got multiple domains in your forest. This is because all the objects of all domains of the forest can be found in the GC, but be carefull for each object all the attributes are not present (as specified in the SCHEMA).


问:
Get constraints in matrix format from gurobipy
I coded my model in gurobipy and I want to get the matrix of constraints and vector of cost.
Is there any way to access those?</p>

答:
Cannot comment on the answer of @david-nehme due to insufficient reputation, feel free to add this to his answer and delete mine.

Since Gurobi 9.0 you can query the coefficient matrix via .getA() as a <class 'scipy.sparse.csr.csr_matrix'>.

```<code>import matplotlib.pyplot as plt
import gurobipy as grb

m = grb.read("miplib/instances/miplib2010/aflow40b.mps.gz")
A = m.getA()
plt.spy(A) # different options, e.g. markersize=0.5
plt.show()
</code>```

Also check out matrix plots using betterspy.

Body:
Cannot comment on the answer of @david-nehme due to insufficient reputation, feel free to add this to his answer and delete mine.

Since Gurobi 9.0 you can query the coefficient matrix via .getA() as a <class 'scipy.sparse.csr.csr_matrix'>.

import matplotlib.pyplot as plt
import gurobipy as grb

m = grb.read("miplib/instances/miplib2010/aflow40b.mps.gz")
A = m.getA()
plt.spy(A) # different options, e.g. markersize=0.5
plt.show()

Also check out matrix plots using betterspy.

ContentLicense: CC BY-SA 4.0


问:
Ansible - environment variables
How to read the environment variables present inside the .env file located at target machine. Note: I don't know what are all the variables inside the .env file. I need to get the all the variables inside the env file and use them in environment keyword. How to do this in playbook. </p>

答:
Maybe you are after the 'ansible_facts'?

these are all the facts that are gathered when ansible touched a hosts.

You can read more about it here - https://www.middlewareinventory.com/blog/ansible-facts-list-how-to-use-ansible-facts/

Title: Ansible - environment variables


问:
EmbeddedKafkaRule have no brokerListProperty method
I'm trying to figure out Spring Kafka. While following reference I found error in this example. There is no brokerListProperty() method in EmbeddedKafkaRule class. How should I refactor the code to make it work?

Code from link above:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {

    @ClassRule
    public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1,
        false, "someTopic")
            .brokerListProperty("spring.kafka.bootstrap-servers");
    }

    @Autowired
    private KafkaTemplate<String, String> template;

    @Test
    public void test() {
        ...
    }

}
</code>```

答:
You can add brokerListProperty like that using KafkaTestUtils

```<code>    @Before
  public void setUp() throws Exception {
    // set up the Kafka producer properties
    Map<String, Object> senderProperties =
        KafkaTestUtils.senderProps(
            broker.getEmbeddedKafka().getBrokersAsString());
  }
</code>```

And you can follow this tutorial it seems pretty correct.

Body:
I'm trying to figure out Spring Kafka. While following reference I found error in this example. There is no brokerListProperty() method in EmbeddedKafkaRule class. How should I refactor the code to make it work?

Code from link above:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyApplicationTests {

    @ClassRule
    public static EmbeddedKafkaRule broker = new EmbeddedKafkaRule(1,
        false, "someTopic")
            .brokerListProperty("spring.kafka.bootstrap-servers");
    }

    @Autowired
    private KafkaTemplate<String, String> template;

    @Test
    public void test() {
        ...
    }

}

Body:
You can add brokerListProperty like that using KafkaTestUtils

    @Before
  public void setUp() throws Exception {
    // set up the Kafka producer properties
    Map<String, Object> senderProperties =
        KafkaTestUtils.senderProps(
            broker.getEmbeddedKafka().getBrokersAsString());
  }

And you can follow this tutorial it seems pretty correct.


问:
Ionic 5 with Angular 9 - Angular JIT compilation failed: '@angular/compiler' not loaded
Ionic 5 was announced a few hours ago (12th Feb 2020) and I upgraded my one of the small production app to Ionic 5 along with Angular 9:

# To update to Ionic 5
npm install @ionic/angular@latest @ionic/angular-toolkit@latest --save-exact --save

# To update to Angular 9
ng update @angular/core @angular/cli
```

<p>But when I did <code>ionic serve</code>, I started getting the bellow error:</p>

```Error: Angular JIT compilation failed: '@angular/compiler' not loaded!
  - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.
  - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?
  - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.
    at getCompilerFacade (core.js:610)
    at Function.get (core.js:16065)
    at getInjectableDef (core.js:362)
    at injectableDefOrInjectorDefFactory (core.js:16816)
```

I came across a few Angular GitHub issues:

https://github.com/angular/angular-cli/issues/16873

https://github.com/angular/angular/issues/32466

They are saying to include import '@angular/compiler'; in main.ts file but when I matched one of my other Angular 9 application (which I updated recently), I don't see such configurations there.

Is Angular 9 not compatible with Ionic 5?

答:
Because of ionic update not fast enough, you can try:
npm i @ionic-native/status-bar@beta @ionic-native/splash-screen@beta @ionic-native/core@beta -S work for me.

update 2020/02/18 => we can run npm i @ionic-native/status-bar @ionic-native/splash-screen @ionic-native/core -S now to get latest stable version

Body:
Ionic 5 was announced a few hours ago (12th Feb 2020) and I upgraded my one of the small production app to Ionic 5 along with Angular 9:

# To update to Ionic 5
npm install @ionic/angular@latest @ionic/angular-toolkit@latest --save-exact --save

# To update to Angular 9
ng update @angular/core @angular/cli

But when I did ionic serve, I started getting the bellow error:

Error: Angular JIT compilation failed: '@angular/compiler' not loaded!
  - JIT compilation is discouraged for production use-cases! Consider AOT mode instead.
  - Did you bootstrap using '@angular/platform-browser-dynamic' or '@angular/platform-server'?
  - Alternatively provide the compiler with 'import "@angular/compiler";' before bootstrapping.
    at getCompilerFacade (core.js:610)
    at Function.get (core.js:16065)
    at getInjectableDef (core.js:362)
    at injectableDefOrInjectorDefFactory (core.js:16816)

I came across a few Angular GitHub issues:

https://github.com/angular/angular-cli/issues/16873

https://github.com/angular/angular/issues/32466

They are saying to include import '@angular/compiler'; in main.ts file but when I matched one of my other Angular 9 application (which I updated recently), I don't see such configurations there.

Is Angular 9 not compatible with Ionic 5?


问:
How to get all the class name of an element in jquery?
I have some li's

```<code> li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"
</code>```

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

答:
you can use indeOf() something like this...suppose you have that selected class as you have written..  </p>

```<code>if(class.indexOf('views-row-2')!=-1){
    //do what ever you want to do, you can use sbstr() to get your class name too.
 }
</code>```

Body:
I have some li's

 li class="views-row views-row-2 views-row-even"
 li class="views-row views-row-3 views-row-odd"
 li class="views-row views-row-4 views-row-even"
 li class="views-row views-row-5 views-row-odd"

Now on hover i am adding a class selected to corresponding li. Suppose i hover on first li element, selected classes get added to this li. So i will have

li class="views-row views-row-2 views-row-even selected". Now how do i get the views-row-2 class of this selected li.Similarly if second li is selected i need views-row-3 class and so on. Please help

Body:
you can use indeOf() something like this...suppose you have that selected class as you have written..

if(class.indexOf('views-row-2')!=-1){
    //do what ever you want to do, you can use sbstr() to get your class name too.
 }


问:
how to get started with Elastic Search using scala client
Hi i am new in Elastic Search and i want to use it with scala so i found some codes examples on github, but there was very complex examples were given as for a beginner I spend my whole day in trying to understand this tutorial but at the end i am confused how to start this is,its very complex to understand same as with other Scala client examples

https://github.com/scalastuff/esclient

https://github.com/bsadeh/scalastic

https://github.com/gphat/wabisabi also i tried this but it contains error and i posted it here as well https://stackoverflow.com/questions/27145015/scalagetstatuscode-getresponsebody-is-not-a-member-of-dispatch-future

All these examples are very complex for a new learner like me as i go through first chapter of Elastic Search from its guide then I want to do these same things pro-grammatically with Scala.Please suggest me some starting point from where can i start learning and also there is a request do not mark this question as nonconstructive first i tried myself after then i am posting this question,Please i need help i want to learn elastic search using scala

答:
Simple elastic search client

```<code>  <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.5.0</version>
  </dependency>
   <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.5.0</version>
    </dependency>
</code>```

Scala code to ES with basic auth:

```<code>import org.apache.http.HttpHost
import org.apache.http.auth.{AuthScope, Credentials, UsernamePasswordCredentials}
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions
import org.elasticsearch.client._
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.RestClientBuilder

  val  credentials = new UsernamePasswordCredentials("<username>", "<password>");
    val credentialsProvider:CredentialsProvider  = new BasicCredentialsProvider
    credentialsProvider.setCredentials(AuthScope.ANY, credentials)

        val client = RestClient.builder(new HttpHost("<host>", 9200,"https")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
          override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
        }).build

val request = new Request(
      "GET",
      /_cat/aliases?format=JSON )
    val response = client.performRequest(request);

 println("Response:"+response.getEntity.getContent)

client.close
</code>```

Body:
Simple elastic search client

  <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.5.0</version>
  </dependency>
   <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.5.0</version>
    </dependency>

Scala code to ES with basic auth:

import org.apache.http.HttpHost
import org.apache.http.auth.{AuthScope, Credentials, UsernamePasswordCredentials}
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions
import org.elasticsearch.client._
import org.apache.http.client.CredentialsProvider
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.RestClientBuilder

  val  credentials = new UsernamePasswordCredentials("<username>", "<password>");
    val credentialsProvider:CredentialsProvider  = new BasicCredentialsProvider
    credentialsProvider.setCredentials(AuthScope.ANY, credentials)

        val client = RestClient.builder(new HttpHost("<host>", 9200,"https")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
          override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
        }).build

val request = new Request(
      "GET",
      /_cat/aliases?format=JSON )
    val response = client.performRequest(request);

 println("Response:"+response.getEntity.getContent)

client.close


问:
Python extract unknown string from dataframe column
New to python - using v3. I have a dataframe column that looks like

```<code>object
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Time Training New"}},"objectType":"Activity"}
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Time Influx"}},"objectType":"Activity"}
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Social"}},"objectType":"Activity"}
{"id":"http://Demo/2.18","definition":{"name":{"en-US":"Personal"}},"objectType":"Activity"}
</code>```

I need to extract the activity, which starts in a variable place and is of variable length. I do not know what the activities are. All the questions I've found are to extract a specific string or pattern, not an unknown one. If I use the code below

```<code>dataExtract['activity'] = dataExtract['object'].str.find('en-US":"')
</code>```

Will give me the start index and this

```<code>dataExtract['activity'] = dataExtract['object'].str.rfind('"}}')
</code>```

Will give me the end index. So I have tried combining these

```<code>dataExtract['activity'] = dataExtract['object'].str[dataExtract['object'].str.find('en-US":"'):dataExtract['object'].str.rfind('"}}')]
</code>```

But that just generates "NaN", which is clearly wrong. What syntax should I use, or is there a better way to do it?  Thanks

答:
I suggest convert values to nested dictionaries and then extract by nested keys:

```<code>#if necessary
#import ast
#dataExtract['object'] = dataExtract['object'].apply(ast.literal_eval)

dataExtract['activity'] = dataExtract['object'].apply(lambda x: x['definition']['name']['en-US'])

print (dataExtract)
                                              object           activity
0  {'id': 'http://Demo/1.7', 'definition': {'name...  Time Training New
1  {'id': 'http://Demo/1.7', 'definition': {'name...        Time Influx
2  {'id': 'http://Demo/1.7', 'definition': {'name...             Social
3  {'id': 'http://Demo/2.18', 'definition': {'nam...           Personal
</code>```

Details:

```<code>print (dataExtract['object'].apply(lambda x: x['definition']))
0    {'name': {'en-US': 'Time Training New'}}
1          {'name': {'en-US': 'Time Influx'}}
2               {'name': {'en-US': 'Social'}}
3             {'name': {'en-US': 'Personal'}}
Name: object, dtype: object

print (dataExtract['object'].apply(lambda x: x['definition']['name']))
0    {'en-US': 'Time Training New'}
1          {'en-US': 'Time Influx'}
2               {'en-US': 'Social'}
3             {'en-US': 'Personal'}
Name: object, dtype: object
</code>```

Body:
New to python - using v3. I have a dataframe column that looks like

object
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Time Training New"}},"objectType":"Activity"}
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Time Influx"}},"objectType":"Activity"}
{"id":"http://Demo/1.7","definition":{"name":{"en-US":"Social"}},"objectType":"Activity"}
{"id":"http://Demo/2.18","definition":{"name":{"en-US":"Personal"}},"objectType":"Activity"}

I need to extract the activity, which starts in a variable place and is of variable length. I do not know what the activities are. All the questions I've found are to extract a specific string or pattern, not an unknown one. If I use the code below

dataExtract['activity'] = dataExtract['object'].str.find('en-US":"')

Will give me the start index and this

dataExtract['activity'] = dataExtract['object'].str.rfind('"}}')

Will give me the end index. So I have tried combining these

dataExtract['activity'] = dataExtract['object'].str[dataExtract['object'].str.find('en-US":"'):dataExtract['object'].str.rfind('"}}')]

But that just generates "NaN", which is clearly wrong. What syntax should I use, or is there a better way to do it?  Thanks

Body:
I suggest convert values to nested dictionaries and then extract by nested keys:

#if necessary
#import ast
#dataExtract['object'] = dataExtract['object'].apply(ast.literal_eval)

dataExtract['activity'] = dataExtract['object'].apply(lambda x: x['definition']['name']['en-US'])

print (dataExtract)
                                              object           activity
0  {'id': 'http://Demo/1.7', 'definition': {'name...  Time Training New
1  {'id': 'http://Demo/1.7', 'definition': {'name...        Time Influx
2  {'id': 'http://Demo/1.7', 'definition': {'name...             Social
3  {'id': 'http://Demo/2.18', 'definition': {'nam...           Personal

Details:

print (dataExtract['object'].apply(lambda x: x['definition']))
0    {'name': {'en-US': 'Time Training New'}}
1          {'name': {'en-US': 'Time Influx'}}
2               {'name': {'en-US': 'Social'}}
3             {'name': {'en-US': 'Personal'}}
Name: object, dtype: object

print (dataExtract['object'].apply(lambda x: x['definition']['name']))
0    {'en-US': 'Time Training New'}
1          {'en-US': 'Time Influx'}
2               {'en-US': 'Social'}
3             {'en-US': 'Personal'}
Name: object, dtype: object


问:
SQL Server performance on concat method
I need to write a query to fetch some data from table and need to use concat method. I end up preparing two different queries and I'm not sure which one will have better performance when we have huge amounts of data.

Please help me understand which query will perform better, and why.

I need to concat twice, one for displaying and one for where condition:

```<code>select
    id, concat(boolean_value, long_value, string_value, double_value) as Value
from
    table
where
    concat(boolean_value, long_value, string_value, double_value) = 'XX'
</code>```

Write the above query as a subquery and add the where condition

```<code>Select *
from
    (select
         id, concat(boolean_value, long_value, string_value, double_value) as Value
     from
         table) as output
where
    Value = 'XX'
</code>```

Note: this is sample query and the actual query will have multiple joins and the need to concat from multiple columns of different tables

答:
SQL databases represent the result set being produced.  You seem to be asking if there is common expression elimination -- that is, will the concat() be performed exactly once.

You have a better chance of this with the subquery than with the version that repeat the expression.  But SQL Server could be smart enough to only evaluate it once.

If you want to guarantee single evaluation, then I think cross apply does that:

```<code>select t.id, v.value
from table t cross apply
     (values (concat( boolean_value, long_value, string_value, double_value))
     ) as Value
where v.value = 'XX';
</code>```

I would, however, question why you are comparing the result of the concat() rather than the base columns.  Comparing the base columns would allow the optimizer to take advantage of indexes, partitions, and statistics.

Title: SQL Server performance on concat method

Body:
I need to write a query to fetch some data from table and need to use concat method. I end up preparing two different queries and I'm not sure which one will have better performance when we have huge amounts of data.

Please help me understand which query will perform better, and why.

I need to concat twice, one for displaying and one for where condition:

select
    id, concat(boolean_value, long_value, string_value, double_value) as Value
from
    table
where
    concat(boolean_value, long_value, string_value, double_value) = 'XX'

Write the above query as a subquery and add the where condition

Select *
from
    (select
         id, concat(boolean_value, long_value, string_value, double_value) as Value
     from
         table) as output
where
    Value = 'XX'

Note: this is sample query and the actual query will have multiple joins and the need to concat from multiple columns of different tables

Body:
SQL databases represent the result set being produced.  You seem to be asking if there is common expression elimination -- that is, will the concat() be performed exactly once.

You have a better chance of this with the subquery than with the version that repeat the expression.  But SQL Server could be smart enough to only evaluate it once.

If you want to guarantee single evaluation, then I think cross apply does that:

select t.id, v.value
from table t cross apply
     (values (concat( boolean_value, long_value, string_value, double_value))
     ) as Value
where v.value = 'XX';

I would, however, question why you are comparing the result of the concat() rather than the base columns.  Comparing the base columns would allow the optimizer to take advantage of indexes, partitions, and statistics.


问:
Uncaught ReferenceError: writeIn is not defined at change (<anonymous>:5:4) at <anonymous>:7:1
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

```<code>function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);
</code>```

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

```<code>var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);
</code>```

答:
After a little bit of hardworking, eventually, I can solve my question and improve the code a lot. The code below works, but an error in console occurs which is not a fatal one. </p>

```<code>function change(class_selector) {
 var cls = document.querySelector(class_selector);
 var colour = prompt("What's your favourite colour?");

if(colour){
 var a = document.querySelector(class_selector).innerHTML= colour;
}else{
 var a = 'blue';
}
cls.style.color = a ;
alert(a);
}
var changing = change('.s-btn__primary');
alert(colour);
console.log(a);
</code>```

<p>You should enter the name of the class in the function when you want to use it.
Respect to anyone who made an effort to solve this challenge. </p>

Body:
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);

Body:
After a little bit of hardworking, eventually, I can solve my question and improve the code a lot. The code below works, but an error in console occurs which is not a fatal one.

function change(class_selector) {
 var cls = document.querySelector(class_selector);
 var colour = prompt("What's your favourite colour?");

if(colour){
 var a = document.querySelector(class_selector).innerHTML= colour;
}else{
 var a = 'blue';
}
cls.style.color = a ;
alert(a);
}
var changing = change('.s-btn__primary');
alert(colour);
console.log(a);

You should enter the name of the class in the function when you want to use it.
Respect to anyone who made an effort to solve this challenge.


问:
Functional, Declarative, and Imperative Programming
What do the terms functional, declarative, and imperative programming mean?</p>

答: I think that your taxonomy is incorrect. There are two opposite types imperative and declarative. Functional is just a subtype of declarative. BTW, wikipedia states the same fact.</p>

OwnerDisplayName: curiouskitty

OwnerDisplayName: Rorick


问:
setContentView(R.layout.main); error
```<code>package com.elfapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_Login;
    private EditText et_UserName;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_Login = (Button) findViewById(R.id.button_login);
        btn_Login.setOnClickListener(this);

        et_UserName = (EditText) findViewById(R.id.editText_userName);
    }

    public void onClick(View v) {
        if (v.equals(btn_Login)) {
                // skriver ut en toast när man klickar på knappen
            Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();

                // används i debuggern för att påvisa att programmet exekverat hit
            Log.v("ThisApp", "onClick Successful");

                // TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
            // send et_UserName.getText().toString() to controller

                // if(username exists)
            Intent intent = new Intent(this, RoomActivity.class);
            this.startActivity(intent);
        }
    }

}
</code>```

I'm getting an error on the line containing setContentView(R.layout.main);
Not sure about what the error/exception is because I'm not used to working in Eclipse..

答:
is this already solved?

i also had this problem. I solved it just by cleaning the project.

Project>Clean>Clean projects selected below>Check [your project's name]

Title: setContentView(R.layout.main); error

Body:
package com.elfapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_Login;
    private EditText et_UserName;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn_Login = (Button) findViewById(R.id.button_login);
        btn_Login.setOnClickListener(this);

        et_UserName = (EditText) findViewById(R.id.editText_userName);
    }

    public void onClick(View v) {
        if (v.equals(btn_Login)) {
                // skriver ut en toast när man klickar på knappen
            Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();

                // används i debuggern för att påvisa att programmet exekverat hit
            Log.v("ThisApp", "onClick Successful");

                // TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
            // send et_UserName.getText().toString() to controller

                // if(username exists)
            Intent intent = new Intent(this, RoomActivity.class);
            this.startActivity(intent);
        }
    }

}

I'm getting an error on the line containing setContentView(R.layout.main);
Not sure about what the error/exception is because I'm not used to working in Eclipse..


答: You may run EXPLAIN on both queries to see what exactly is on the mind of SQL Server.  I would expect that the first version would be preferable, because, unlike the second version, it does not force SQL Server to materialize an intermediate table.  Regarding whether or not SQL Server would have to actually evaluate CONCAT twice in the first version, it may not even matter if the cost of the subquery be very high.

Title: SQL Server performance on concat method


问:
instant delete when the button is cliked
im trying to delete from a datatable when i click the remove button the data will be removed for a quick action in the admin side but my code dose not work i tried to fix it but i don't see any problem in the code here is my code </p>

```<code> <div class="table-responsive">
<table id="datas" class="table table-striped table-bordered fixed" style="width:100%">

    <thead style="color:black;" >
        <th>id</th>
        <th>Company Name</th>
        <th>Product Name</th>
        <th>Weight</th>
        <th>Price Per Gram</th>
        <th>Quantity</th>
        <th>Type</th>
        <th>Category</th>
        <th>Product Price</th>
        <th>Image</th>
        <th>Total Price</th>

        <th class="text-center">Actions</th>

    </thead>

    <?php
    $get = mysqli_query($conn,"SELECT * FROM stock;");
    ?>
    <tbody>

    <?php
    while ($row=mysqli_fetch_array($get)) {
        $id=$row['id'];
        $company=$row['company_name'];
        $name=$row['product_name'];

        $weight=$row['weight'];
        $price_per_gram=$row['price_per_gram'];
        $quantity=$row['quantity'];

        $type=$row['type'];
        $category=$row['category'];
        $price=$row['product_price'];
        $img=$row['img'];
        $total=$row['total_price'];
        ?>
            <tr>
            <td ><?php echo $id;?></td>
            <td><?php echo $company;?></td>
            <td><?php echo $name;?></td>
            <td><?php echo $weight;?> g</td>
            <td><?php echo $price_per_gram;?> $</td>
            <td><?php echo $quantity;?></td>
            <td><?php echo $type;?></td>
            <td><?php echo $category;?></td>
            <td><?php echo $price;?></td>
            <td>
                <img  src="product_img/<?php echo $img; ?>" style="height:5rem;width:5rem;border-radius:10px;">
            </td>
            <td><?php echo $total;?></td>
             <td style="width: 20px"> <a href="editstock.php?id=<?php echo $id;?>" class="btn btn-gradient-primary">Edit</a>
                 <button class="btn btn-danger" name="delete"  type="submit" value="<?php echo "$id" ?>">Delete</button> </td>

            </tr>

    <?php } ?>
    </tbody>
</table>

<?php

 if (isset($_POST['delete'])) {

$delete = mysqli_query($conn,"DELETE FROM stock WHERE id= ".$_POST['delete']." ");
header("location:viewstcok.php");

} ?>
</code>```

<p>i give the delete button a value when clicked so it will delete with that value but it did not seems to work can any one help me </p>

答:
you have to  placed table inside <form></form> tag

```<code><div class="table-responsive">
<form>
<table id="datas" class="table table-striped table-bordered fixed" style="width:100%">

    <thead style="color:black;" >
        <th>id</th>
        <th>Company Name</th>
        <th>Product Name</th>
        <th>Weight</th>
        <th>Price Per Gram</th>
        <th>Quantity</th>
        <th>Type</th>
        <th>Category</th>
        <th>Product Price</th>
        <th>Image</th>
        <th>Total Price</th>

        <th class="text-center">Actions</th>

    </thead>

    <?php
    $get = mysqli_query($conn,"SELECT * FROM stock;");
    ?>
    <tbody>

    <?php
    while ($row=mysqli_fetch_array($get)) {
        $id=$row['id'];
        $company=$row['company_name'];
        $name=$row['product_name'];

        $weight=$row['weight'];
        $price_per_gram=$row['price_per_gram'];
        $quantity=$row['quantity'];

        $type=$row['type'];
        $category=$row['category'];
        $price=$row['product_price'];
        $img=$row['img'];
        $total=$row['total_price'];
        ?>
            <tr>
            <td ><?php echo $id;?></td>
            <td><?php echo $company;?></td>
            <td><?php echo $name;?></td>
            <td><?php echo $weight;?> g</td>
            <td><?php echo $price_per_gram;?> $</td>
            <td><?php echo $quantity;?></td>
            <td><?php echo $type;?></td>
            <td><?php echo $category;?></td>
            <td><?php echo $price;?></td>
            <td>
                <img  src="product_img/<?php echo $img; ?>" style="height:5rem;width:5rem;border-radius:10px;">
            </td>
            <td><?php echo $total;?></td>
             <td style="width: 20px"> <a href="editstock.php?id=<?php echo $id;?>" class="btn btn-gradient-primary">Edit</a>
                 <button class="btn btn-danger" name="delete"  type="submit" value="<?php echo "$id" ?>">Delete</button> </td>

            </tr>

    <?php } ?>
    </tbody>
</table>
</form>
<?php

 if (isset($_POST['delete'])) {

$delete = mysqli_query($conn,"DELETE FROM stock WHERE id= ".$_POST['delete']." ");
header("location:viewstcok.php");

} ?>
</code>```

Body:
im trying to delete from a datatable when i click the remove button the data will be removed for a quick action in the admin side but my code dose not work i tried to fix it but i don't see any problem in the code here is my code

        id
        Company Name
        Product Name
        Weight
        Price Per Gram
        Quantity
        Type
        Category
        Product Price
        Image
        Total Price

        Actions

    <?php
    $get = mysqli_query($conn,"SELECT * FROM stock;");
    ?>

    <?php
    while ($row=mysqli_fetch_array($get)) {
        $id=$row['id'];
        $company=$row['company_name'];
        $name=$row['product_name'];

        $weight=$row['weight'];
        $price_per_gram=$row['price_per_gram'];
        $quantity=$row['quantity'];

        $type=$row['type'];
        $category=$row['category'];
        $price=$row['product_price'];
        $img=$row['img'];
        $total=$row['total_price'];
        ?>

            <?php echo $id;?>
            <?php echo $company;?>
            <?php echo $name;?>
            <?php echo $weight;?> g
            <?php echo $price_per_gram;?> $
            <?php echo $quantity;?>
            <?php echo $type;?>
            <?php echo $category;?>
            <?php echo $price;?>

                <img  src="product_img/<?php echo $img; ?>" style="height:5rem;width:5rem;border-radius:10px;">

            <?php echo $total;?>
              <a href="editstock.php?id=<?php echo $id;?>" class="btn btn-gradient-primary">Edit
                 <button class="btn btn-danger" name="delete"  type="submit" value="<?php echo "$id" ?>">Delete</button>

    <?php } ?>

<?php

 if (isset($_POST['delete'])) {

$delete = mysqli_query($conn,"DELETE FROM stock WHERE id= ".$_POST['delete']." ");
header("location:viewstcok.php");

} ?>

i give the delete button a value when clicked so it will delete with that value but it did not seems to work can any one help me

Body:
you have to  placed table inside <form></form> tag

<div class="table-responsive">
<form>
<table id="datas" class="table table-striped table-bordered fixed" style="width:100%">

    <thead style="color:black;" >
        <th>id</th>
        <th>Company Name</th>
        <th>Product Name</th>
        <th>Weight</th>
        <th>Price Per Gram</th>
        <th>Quantity</th>
        <th>Type</th>
        <th>Category</th>
        <th>Product Price</th>
        <th>Image</th>
        <th>Total Price</th>

        <th class="text-center">Actions</th>

    </thead>

    <?php
    $get = mysqli_query($conn,"SELECT * FROM stock;");
    ?>
    <tbody>

    <?php
    while ($row=mysqli_fetch_array($get)) {
        $id=$row['id'];
        $company=$row['company_name'];
        $name=$row['product_name'];

        $weight=$row['weight'];
        $price_per_gram=$row['price_per_gram'];
        $quantity=$row['quantity'];

        $type=$row['type'];
        $category=$row['category'];
        $price=$row['product_price'];
        $img=$row['img'];
        $total=$row['total_price'];
        ?>
            <tr>
            <td ><?php echo $id;?></td>
            <td><?php echo $company;?></td>
            <td><?php echo $name;?></td>
            <td><?php echo $weight;?> g</td>
            <td><?php echo $price_per_gram;?> $</td>
            <td><?php echo $quantity;?></td>
            <td><?php echo $type;?></td>
            <td><?php echo $category;?></td>
            <td><?php echo $price;?></td>
            <td>
                <img  src="product_img/<?php echo $img; ?>" style="height:5rem;width:5rem;border-radius:10px;">
            </td>
            <td><?php echo $total;?></td>
             <td style="width: 20px"> <a href="editstock.php?id=<?php echo $id;?>" class="btn btn-gradient-primary">Edit</a>
                 <button class="btn btn-danger" name="delete"  type="submit" value="<?php echo "$id" ?>">Delete</button> </td>

            </tr>

    <?php } ?>
    </tbody>
</table>
</form>
<?php

 if (isset($_POST['delete'])) {

$delete = mysqli_query($conn,"DELETE FROM stock WHERE id= ".$_POST['delete']." ");
header("location:viewstcok.php");

} ?>


问:
Failed to install android SDK tools 26.1.1 and Emulator
Can't download and install android SDK tools 26.1.1 and emulator.

This is the log output :

```<code>To install:
- Android Emulator (emulator)
- Android SDK Tools (tools)
Preparing "Install Android Emulator (revision: 26.1.4)".
Downloading https://dl.google.com/android/repository/emulator-windows-4266726.zip
An error occurred while preparing SDK package Android Emulator: Cannot download 'https://dl.google.com/android/repository/emulator-windows-4266726.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation07\emulator-windows-4266726.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android Emulator (revision: 26.1.4)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\android\repository\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK
"Install Android SDK Tools (revision: 26.1.1)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android SDK Tools (revision: 26.1.1)" failed.
Failed packages:
- Android Emulator (emulator)
- Android SDK Tools (tools)
</code>```

答:
Worked for me ..

Installed java

Run Android Studio as Administrator

Body:
Can't download and install android SDK tools 26.1.1 and emulator.

This is the log output :

To install:
- Android Emulator (emulator)
- Android SDK Tools (tools)
Preparing "Install Android Emulator (revision: 26.1.4)".
Downloading https://dl.google.com/android/repository/emulator-windows-4266726.zip
An error occurred while preparing SDK package Android Emulator: Cannot download 'https://dl.google.com/android/repository/emulator-windows-4266726.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation07\emulator-windows-4266726.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android Emulator (revision: 26.1.4)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\android\repository\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK
"Install Android SDK Tools (revision: 26.1.1)" failed.
Preparing "Install Android SDK Tools (revision: 26.1.1)".
Downloading https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip
An error occurred while preparing SDK package Android SDK Tools: Cannot download 'https://dl.google.com/android/repository/sdk-tools-windows-4333796.zip': C:\Users\hp\AppData\Local\Temp\PackageOperation02\sdk-tools-windows-4333796.zip (The system cannot find the path specified)
, response: 200 OK.
"Install Android SDK Tools (revision: 26.1.1)" failed.
Failed packages:
- Android Emulator (emulator)
- Android SDK Tools (tools)


问:
How to redirect from a ManagedBean for when the request sent is an Ajax request?
I am using PrimeFaces with JSF2. I am trying to authenticate user by sending login and password as an Ajax request. And in the action method of the backing bean, I am trying to validate user and redirect to a new view if the validation succeeds.

Is this possible while using primefaces?

Because I think with primefaces' p:commandButton, I can only either have ajax behavior or the navigation.

答:
Yes, just send a redirect instead of a (default) forward as outcome. The <navigation-case>-less JSF 2.0 way would be appending ?faces-redirect=true to the outcome string in the action method.

E.g.

```<code>public String login() {
    // ...
    return "home?faces-redirect=true";
}
</code>```

Body:
Yes, just send a redirect instead of a (default) forward as outcome. The <navigation-case>-less JSF 2.0 way would be appending ?faces-redirect=true to the outcome string in the action method.

E.g.

public String login() {
    // ...
    return "home?faces-redirect=true";
}


问:
Jackson Object Mapper com.fasterxml.jackson.databind.exc.MismatchedInputException
I am trying to run a following Junit test :

```<code>  @Test
  public void testObjectMapper() throws IOException {
    String json = new ObjectMapper().writeValueAsString(Instant.now());
    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.readValue(json, Instant.class);
  }
</code>```

But gets the following exception:

```<code>com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value
 at [Source: (String)"{"nano":627594000,"epochSecond":1581946138}"; line: 1, column: 1]
</code>```

No idea why i am not able to deserialize (String)"{"nano":627594000,"epochSecond":1581946138}" into a Instant class.

Need help!

答:
You should serialize your Instant with the same ObjectMapper used for the deserialization.

```<code>    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = om.writeValueAsString(Instant.now());
    om.readValue(json, Instant.class);
</code>```

Body:
I am trying to run a following Junit test :

  @Test
  public void testObjectMapper() throws IOException {
    String json = new ObjectMapper().writeValueAsString(Instant.now());
    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.readValue(json, Instant.class);
  }

But gets the following exception:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Instant value
 at [Source: (String)"{"nano":627594000,"epochSecond":1581946138}"; line: 1, column: 1]

No idea why i am not able to deserialize (String)"{"nano":627594000,"epochSecond":1581946138}" into a Instant class.

Need help!

Body:
You should serialize your Instant with the same ObjectMapper used for the deserialization.

    ObjectMapper om = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
        .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = om.writeValueAsString(Instant.now());
    om.readValue(json, Instant.class);


问:
managing items in a List based off some conditions in C#
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

```<code>class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}
</code>```

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

答:
Your dummy application is using the same object (oldData1).

Please refer to the below code using simple LINQ.

```<code>class Program
{
    static void Main(string[] args)
    {
        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData2.Name = "Test02";
        oldData2.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        newData2.Name = "Test05";
        newData2.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        oldItems = oldItems.Where(x => newItems != null && !newItems.Any(y => x.Name == y.Name && x.OriginalPath == y.OriginalPath)).ToList();

    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}
</code>```

Body:
I have a couple of lists  List<OldData> oldItems = new List<OldData>(); and List<NewData> newItems = new List<NewData>();

What I am trying to achieve here is to avoid the possibility of some redundant data coming in hence to check with some conditions before values are added into the list.

First up in the oldItems  I will have some values stored and in the newItems list I will have a completely different set of values stored but it could always be the case that the newItems list may have some values that are already existing in the  oldItems list.

The two variables that are in use are a Name variable and a path variable which stores a certain path

So First I want to check if there are any values where the name in the old items List is equal to the name in the new Items List ,
if There is an Item I want to check if the respective Path variable of the corresponding items are same ,

if it is same I can simply keep that item the way it is in the OldItems list , if that happens to be different I will Remove that from the old Items List (and later use the item in the new Item List)

So all the above in a nut shell ,

I want to check for in the Old Items List where there is a Name Corresponding to it in the new Item List
If there is , I want to check if the corresponding values in the Path variable for the two items with the same name from the two List are the same or different

I have made a simple dummy application to demo this but really stuck on how i can implement the logic

any suggestion ?

class Program
{
    static void Main(string[] args)
    {

        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData1.Name = "Test02";
        oldData1.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        oldData1.Name = "Test05";
        oldData1.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        foreach (var item in oldItems)
        {
            //Check if there are any Names which are same from the new Item list
            //If if there is such an item check if the OriginalPath variable is the same iin both
            //If yes => Remove that particular item from the Old data List
            //If Not => Keep that Item in  the old data List
        }
    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

In this case since the value Test01 is common to both List It will check if the path variable values corresponding to both items are the same or not

Body:
Your dummy application is using the same object (oldData1).

Please refer to the below code using simple LINQ.

class Program
{
    static void Main(string[] args)
    {
        List<OldData> oldItems = new List<OldData>();

        OldData oldData1 = new OldData();
        oldData1.Name = "Test01";
        oldData1.OriginalPath = "D:/Temp01";

        oldItems.Add(oldData1);

        OldData oldData2 = new OldData();
        oldData2.Name = "Test02";
        oldData2.OriginalPath = "D:/Temp02";
        oldItems.Add(oldData2);

        List<NewData> newItems = new List<NewData>();

        NewData newData1 = new NewData();
        newData1.Name = "Test01";
        newData1.OriginalPath = "D:/Temp01";

        newItems.Add(newData1);

        NewData newData2 = new NewData();
        newData2.Name = "Test05";
        newData2.OriginalPath = "D:/Temp05";
        newItems.Add(newData2);

        oldItems = oldItems.Where(x => newItems != null && !newItems.Any(y => x.Name == y.Name && x.OriginalPath == y.OriginalPath)).ToList();

    }
}

class OldData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}

class NewData
{
    public string Name { get; set; }
    public string OriginalPath { get; set; }
}


问:
converting a method into a member functor object which calls the method leads to a crash
I have the following method in a class:

```<code>bool temp_cmp(size_t l, size_t r) const {
    return memcmp(get_next_temp_record(l), get_next_temp_record(r), page_size) < 0;
}
</code>```

But I need it as a functor object so I rewrote it like this:

```<code>struct temp_cmp_functor {
    const sorter& _s;
    temp_cmp_functor(sorter& s) : _s(s) {
        std::cout << "ADDR: " << &_s << std::endl;
    }

    bool operator()(size_t l, size_t r) const {
        std::cout << "ADDR AT CALL: " << &_s << std::endl;
        return memcmp(_s.get_next_temp_record(l), _s.get_next_temp_record(r), page_size) < 0;
    }
};
temp_cmp_functor temp_cmp{*this};
</code>```

And now later on when I call it like temp_cmp(idx1, idx2) I get a crash in a sanitized build - with ASAN (the function get_next_temp_record accesses some fields of the class which are of type std::vector but I don't think that should be relevant).

Any idea why this change might be problematic? I'm printing the addresses of the object and they match in the constructor of the functor and when the operator() is called - I see no reason for this not to work... To me the 2 ways should be identical... What am I missing?

Here is the ASAN output:

```<code>/usr/include/c++/9/bits/stl_vector.h:1061:34: runtime error: reference binding to null pointer of   type 'const struct value_type'
../../demos/ip_demo.cc:185:33: runtime error: member access within null pointer of type 'const struct   value_type'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==3862==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000020 (pc 0x00000047a8b4 bp   0x7ffe9e0042c0 sp 0x7ffe9e0042a0 T0)
==3862==The signal is caused by a READ memory access.
==3862==Hint: address points to the zero page.
    #0 0x47a8b3 in std::__uniq_ptr_impl<char, seastar::free_deleter>::_M_ptr() const /usr/include/c++/  9/bits/unique_ptr.h:154
    #1 0x465ac5 in std::unique_ptr<char [], seastar::free_deleter>::get() const /usr/include/c++/9/ bits/unique_ptr.h:612
    #2 0x46635d in std::unique_ptr<char [], seastar::free_deleter>::operator[](unsigned long) const (/  home/onqtam/seastar/build/debug/demos/ip_demo+0x46635d)
    #3 0x45b146 in sorter::get_next_temp_record(unsigned long) const (/home/onqtam/seastar/build/   debug/demos/ip_demo+0x45b146)
    #4 0x45b3fe in sorter::temp_cmp_functor::operator()(unsigned long, unsigned long) const (/home/ onqtam/seastar/build/debug/demos/ip_demo+0x45b3fe)
    #5 0x420298 in operator() ../../demos/ip_demo.cc:421
</code>```

答: Turns out that the whole class was getting copied somewhere, and then the functor's reference to the outer class was pointing to the old location ==> memory corruption.</p>

Body:
I have the following method in a class:

bool temp_cmp(size_t l, size_t r) const {
    return memcmp(get_next_temp_record(l), get_next_temp_record(r), page_size) < 0;
}

But I need it as a functor object so I rewrote it like this:

struct temp_cmp_functor {
    const sorter& _s;
    temp_cmp_functor(sorter& s) : _s(s) {
        std::cout << "ADDR: " << &_s << std::endl;
    }

    bool operator()(size_t l, size_t r) const {
        std::cout << "ADDR AT CALL: " << &_s << std::endl;
        return memcmp(_s.get_next_temp_record(l), _s.get_next_temp_record(r), page_size) < 0;
    }
};
temp_cmp_functor temp_cmp{*this};

And now later on when I call it like temp_cmp(idx1, idx2) I get a crash in a sanitized build - with ASAN (the function get_next_temp_record accesses some fields of the class which are of type std::vector but I don't think that should be relevant).

Any idea why this change might be problematic? I'm printing the addresses of the object and they match in the constructor of the functor and when the operator() is called - I see no reason for this not to work... To me the 2 ways should be identical... What am I missing?

Here is the ASAN output:

/usr/include/c++/9/bits/stl_vector.h:1061:34: runtime error: reference binding to null pointer of   type 'const struct value_type'
../../demos/ip_demo.cc:185:33: runtime error: member access within null pointer of type 'const struct   value_type'
AddressSanitizer:DEADLYSIGNAL
=================================================================
==3862==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000020 (pc 0x00000047a8b4 bp   0x7ffe9e0042c0 sp 0x7ffe9e0042a0 T0)
==3862==The signal is caused by a READ memory access.
==3862==Hint: address points to the zero page.
    #0 0x47a8b3 in std::__uniq_ptr_impl<char, seastar::free_deleter>::_M_ptr() const /usr/include/c++/  9/bits/unique_ptr.h:154
    #1 0x465ac5 in std::unique_ptr<char [], seastar::free_deleter>::get() const /usr/include/c++/9/ bits/unique_ptr.h:612
    #2 0x46635d in std::unique_ptr<char [], seastar::free_deleter>::operator[](unsigned long) const (/  home/onqtam/seastar/build/debug/demos/ip_demo+0x46635d)
    #3 0x45b146 in sorter::get_next_temp_record(unsigned long) const (/home/onqtam/seastar/build/   debug/demos/ip_demo+0x45b146)
    #4 0x45b3fe in sorter::temp_cmp_functor::operator()(unsigned long, unsigned long) const (/home/ onqtam/seastar/build/debug/demos/ip_demo+0x45b3fe)
    #5 0x420298 in operator() ../../demos/ip_demo.cc:421


问:
make telegram bot using python
I'm trying to make a telegram bot using python, but for some reason it doesn't post the info to the telegram. my code is supposed to send a data frame to telegram as a table but it returns noting(even a error) when I call it from telegram. </p>

```<code>from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re
import pandas as pd

def get_data():
    data = pd.read_excel('C:/Users/admin/Desktop/data.xlsx')# opening xlsx file as the input
    data = data.to_string(columns = ['c.1', 'c.2'], index = False, header = True, line_width = 70, justify = 'left')
    return data

def result(bot, update):
    data = get_data()
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, table=data)
    bot.send_photo(chat_id=chat_id, photo=data)

def main():
    updater = Updater('Token key')
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('result',result))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

答:
Did you try to use the new CallbackContext? There should be an message linking to this page: https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0) when starting the bot. There it says:

Now on to the bulk of the change. You wanna change all your callback functions from the following:

```<code>def start(bot, update, args, job_queue):
    # Stuff here
</code>```

to the new style using CallbackContext

```<code>def start(update: Update, context: CallbackContext):
    # Stuff here
    # args will be available as context.args
    # jobqueue will be available as context.jobqueue
</code>```

I got it to work with a minimal example like this:

```<code>from telegram.ext import Updater, InlineQueryHandler, CommandHandler

def result(update, context):
    print('result called')
    data = 'mydata'
    update.message.reply_text(data)

def main():
    updater = Updater('Token', use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('result',result))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
</code>```

P.S.: You don't seem to use the requests and re from the imports.

Title: make telegram bot using python

Body:
I'm trying to make a telegram bot using python, but for some reason it doesn't post the info to the telegram. my code is supposed to send a data frame to telegram as a table but it returns noting(even a error) when I call it from telegram.

from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import requests
import re
import pandas as pd

def get_data():
    data = pd.read_excel('C:/Users/admin/Desktop/data.xlsx')# opening xlsx file as the input
    data = data.to_string(columns = ['c.1', 'c.2'], index = False, header = True, line_width = 70, justify = 'left')
    return data

def result(bot, update):
    data = get_data()
    chat_id = update.message.chat_id
    bot.send_message(chat_id=chat_id, table=data)
    bot.send_photo(chat_id=chat_id, photo=data)

def main():
    updater = Updater('Token key')
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('result',result))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Body:
Did you try to use the new CallbackContext? There should be an message linking to this page: https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0) when starting the bot. There it says:

Now on to the bulk of the change. You wanna change all your callback functions from the following:

def start(bot, update, args, job_queue):
    # Stuff here

to the new style using CallbackContext

def start(update: Update, context: CallbackContext):
    # Stuff here
    # args will be available as context.args
    # jobqueue will be available as context.jobqueue

I got it to work with a minimal example like this:

from telegram.ext import Updater, InlineQueryHandler, CommandHandler

def result(update, context):
    print('result called')
    data = 'mydata'
    update.message.reply_text(data)

def main():
    updater = Updater('Token', use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('result',result))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

P.S.: You don't seem to use the requests and re from the imports.


问:
how to print boost multiprecision 128 bit unsigned integer
I want to print integer value that converted from hexadecimal value but i only could print hexadecimal value.

```<code>#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;

    cpp_int          dsa("0xFFFFFFFFFFFFFFFF");
    cpp_int          daa("9223372036854775807");
    daa = ((daa * 64) + daa);
    cout << std::hex<<dsa <<std::showbase<< endl;
    cout <<dsa << endl;
    cout <<daa << endl;
    cout <<(int)daa << endl;
    cout <<(int128_t)daa << endl;

</code>```

output

```<code>ffffffffffffffff
0xffffffffffffffff
0x207fffffffffffffbf
0x7fffffff
0x207fffffffffffffbf
</code>```

How can i print max value of 128 bit type of integer ?

答:
You should use std::numeric_limits to get the max value, because that's its purpose.
Your formatting issue is independent of your actual question.

```<code>#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <limits>

int main()
{
    auto max = std::numeric_limits<boost::multiprecision::int128_t>::max();
    std::cout << max << std::endl;
}
</code>```

Body:
I want to print integer value that converted from hexadecimal value but i only could print hexadecimal value.

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;

    cpp_int          dsa("0xFFFFFFFFFFFFFFFF");
    cpp_int          daa("9223372036854775807");
    daa = ((daa * 64) + daa);
    cout << std::hex<<dsa <<std::showbase<< endl;
    cout <<dsa << endl;
    cout <<daa << endl;
    cout <<(int)daa << endl;
    cout <<(int128_t)daa << endl;

output

ffffffffffffffff
0xffffffffffffffff
0x207fffffffffffffbf
0x7fffffff
0x207fffffffffffffbf

How can i print max value of 128 bit type of integer ?

Body:
You should use std::numeric_limits to get the max value, because that's its purpose.
Your formatting issue is independent of your actual question.

#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
#include <limits>

int main()
{
    auto max = std::numeric_limits<boost::multiprecision::int128_t>::max();
    std::cout << max << std::endl;
}


问:
How to create a variable of dynamic type
I am able to create a variable 'model' of type 'Sample' as follows:

```<code>type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

var model Sample // created successfully
</code>```

I am able to create it successfully as I already know the struct type (Sample).

However, when I tried to create a similar variable 'a' as follows, I get syntax error:

```<code>package main

import (
    "fmt"
    "reflect"
)

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

func test(m interface{}) {
    fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'

    var a reflect.TypeOf(m) // it throws - syntax error: unexpected ( at end of statement
}

func main() {

    var model Sample // I have created a model of type Sample
    model = Sample{Id: 1, Name: "MAK"}
    test(model)
}
</code>```

Please advise how to create a variable of dynamic type in Go.

答:
```<code>package main

import (
    "fmt"
    "reflect"
)

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

func test(m interface{}) {
    fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'

    a, ok := m.(main.Sample)
    if ok {
        fmt.Println(a.Id)
    }
}

func main() {

    var model Sample // I have created a model of type Sample
    model = Sample{Id: 1, Name: "MAK"}
    test(model)
}
</code>```

and if you want a little more dynamism, you can use a type switch. Instead of the a, ok := m.(main.Sample), you do

```<code>switch a := m.(type) {
    case main.Sample:
        fmt.Println("It's a %s", reflect.TypeOf(m))
    case default:
        fmt.Println("It's an unknown type")
}
</code>```

Body:
I am able to create a variable 'model' of type 'Sample' as follows:

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

var model Sample // created successfully

I am able to create it successfully as I already know the struct type (Sample).

However, when I tried to create a similar variable 'a' as follows, I get syntax error:

package main

import (
    "fmt"
    "reflect"
)

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

func test(m interface{}) {
    fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'

    var a reflect.TypeOf(m) // it throws - syntax error: unexpected ( at end of statement
}

func main() {

    var model Sample // I have created a model of type Sample
    model = Sample{Id: 1, Name: "MAK"}
    test(model)
}

Please advise how to create a variable of dynamic type in Go.

Body:
package main

import (
    "fmt"
    "reflect"
)

type Sample struct {
    Id   int    `jsonapi:"attr,id,omitempty"`
    Name string `jsonapi:"attr,name,omitempty"`
}

func test(m interface{}) {
    fmt.Println(reflect.TypeOf(m)) // prints 'main.Sample'

    a, ok := m.(main.Sample)
    if ok {
        fmt.Println(a.Id)
    }
}

func main() {

    var model Sample // I have created a model of type Sample
    model = Sample{Id: 1, Name: "MAK"}
    test(model)
}

and if you want a little more dynamism, you can use a type switch. Instead of the a, ok := m.(main.Sample), you do

switch a := m.(type) {
    case main.Sample:
        fmt.Println("It's a %s", reflect.TypeOf(m))
    case default:
        fmt.Println("It's an unknown type")
}


问:
Updating only part of an HTML page using Django
I have an HTML (annotator.html) page where the top half contains a table. I have JavaScript code that pulls data out of the data model when the user selects a row in the table and displays that data in a div below the table.

My Javascript looks like this:

```<code>$('#radiological tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) {
        $(this).removeClass('selected');
    }
    else {
        //first unselect any other selected row
        dt_table.$('tr.selected').removeClass('selected');

        //then select row of interest
        $(this).addClass('selected');

        var rowIndex = dt_table.row('.selected')[0];
        var row = dt_table.rows(rowIndex);
        var id = row.data()[0]['id'];
        var url = '/report/' + id + '/';
        //window.location = url;

        $.ajax({
            url: url,
            type: 'get', // This is the default though, you don't actually need to always mention it
            success: function(data) {
            },
            failure: function(data) {
                alert('Got an error dude');
            }
        });
</code>```

And correctly populates the bottom half of my page but also updates the top half.  I Just want the bottom half refreshed.

My report view looks like this:

```<code>def report_page(request, id):
    template_name = "annotator.html"
    data = Radiology2.objects.get(id=id)
    context = {"data": data}
    context["title"] = title
    context["version"] = version
    context["id"] = id

    if (request.is_ajax()):
        # return render(request, template_name, context)
        return JsonResponse(context)
    else:
        return render(request, template_name, context)
</code>```

I added support for AJAX.  I'm  just not sure how to return from view properly when AJAX is used.  Obviously, I'm not understanding something.

答: Instead of Ajax, I replaced window.location=url; with $('#divIdToRefresh').load(url +  ' #divIdToRefresh');

Body:
I have an HTML (annotator.html) page where the top half contains a table. I have JavaScript code that pulls data out of the data model when the user selects a row in the table and displays that data in a div below the table.

My Javascript looks like this:

$('#radiological tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected') ) {
        $(this).removeClass('selected');
    }
    else {
        //first unselect any other selected row
        dt_table.$('tr.selected').removeClass('selected');

        //then select row of interest
        $(this).addClass('selected');

        var rowIndex = dt_table.row('.selected')[0];
        var row = dt_table.rows(rowIndex);
        var id = row.data()[0]['id'];
        var url = '/report/' + id + '/';
        //window.location = url;

        $.ajax({
            url: url,
            type: 'get', // This is the default though, you don't actually need to always mention it
            success: function(data) {
            },
            failure: function(data) {
                alert('Got an error dude');
            }
        });

And correctly populates the bottom half of my page but also updates the top half.  I Just want the bottom half refreshed.

My report view looks like this:

def report_page(request, id):
    template_name = "annotator.html"
    data = Radiology2.objects.get(id=id)
    context = {"data": data}
    context["title"] = title
    context["version"] = version
    context["id"] = id

    if (request.is_ajax()):
        # return render(request, template_name, context)
        return JsonResponse(context)
    else:
        return render(request, template_name, context)

I added support for AJAX.  I'm  just not sure how to return from view properly when AJAX is used.  Obviously, I'm not understanding something.


问:
Separating even and odd indexes from and ArrayList in Java using recursion
I'm trying to separate even and odd indexes from an ArrayList in java as part of an assignment. It must be a recursive method. Here is what I've tried;;

```<code>public ArrayList<Integer> toOddList(ArrayList<Integer> input) {
        ArrayList<Integer> copiedList = (ArrayList<Integer>) input.clone();
        ArrayList<Integer> oddList = new ArrayList<Integer>();
        ArrayList<Integer> evenList = new ArrayList<Integer>();
        int index = (copiedList.size() - 1);      // Sets index to the max size of ArrayList - 1
        if (index <= 0) {
            return oddList;
        }
        if ((index % 2) == 0) {
            evenList.add(copiedList.get(index));  // Adds indexed number to even Arraylist
            copiedList.remove(index);             // Removes index from copiedList
            copiedList = toOddList(copiedList);   // Calls function again
        } else {
            oddList.add(copiedList.get(index));   // Adds indexed number to odd Arraylist
            copiedList.remove(index);             // Removes index from copied List
            copiedList = toOddList(copiedList);   // Call method again
        } return oddList;
    }
</code>```

If there is any other way to use recursion for this, or to instead use two methods for even and odd separately, any help would be appreciated.

答:
I am borrowing Jarvis' idea of using index rather than cloning the input array. I think the intent here is to make the base case that we have reached the end of the list, and if not we add the current element to the right list, then call ourselves on the rest of the list, taking care to increment the index and switch the spots of the current list and the one that is on deck. Then the method becomes:

```<code>//assumes all lists initialized by caller
public void splitList(ArrayList<Integer> input, int index, ArrayList<Integer> current, ArrayList<Integer> onDeck) {
    if (index >= input.size()) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(index));
        splitList(input, index + 1, onDeck, current); //note toggling output list and advancing index
    }
}
</code>```

and it gets called once the input list is initialized and odds and evens contain freshly constructed empty array lists as follows:

```<code>splitList(splitThis, 0, evens, odds);//start with evens because 0 is even
</code>```

REVISION:
I noticed it would be possible not to worry about the index as much and somewhat more natural to make "the rest of the list" a sublist. I also generalized to any kind of list. Thus:

```<code>//assumes all lists initialized by caller
public void splitList(List<Integer> input, List<Integer> current, List<Integer> onDeck) {
    if (input.size() == 0) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(0));
        splitList(input.subList(1, input.size()), onDeck, current); //note toggling output list and call on rest of list, if any
    }
}
</code>```

and the call is simplified to:

```<code>splitList(splitThis, evens, odds);//start with evens because 0 is even
</code>```

Body:
I'm trying to separate even and odd indexes from an ArrayList in java as part of an assignment. It must be a recursive method. Here is what I've tried;;

public ArrayList<Integer> toOddList(ArrayList<Integer> input) {
        ArrayList<Integer> copiedList = (ArrayList<Integer>) input.clone();
        ArrayList<Integer> oddList = new ArrayList<Integer>();
        ArrayList<Integer> evenList = new ArrayList<Integer>();
        int index = (copiedList.size() - 1);      // Sets index to the max size of ArrayList - 1
        if (index <= 0) {
            return oddList;
        }
        if ((index % 2) == 0) {
            evenList.add(copiedList.get(index));  // Adds indexed number to even Arraylist
            copiedList.remove(index);             // Removes index from copiedList
            copiedList = toOddList(copiedList);   // Calls function again
        } else {
            oddList.add(copiedList.get(index));   // Adds indexed number to odd Arraylist
            copiedList.remove(index);             // Removes index from copied List
            copiedList = toOddList(copiedList);   // Call method again
        } return oddList;
    }

If there is any other way to use recursion for this, or to instead use two methods for even and odd separately, any help would be appreciated.

Body:
I am borrowing Jarvis' idea of using index rather than cloning the input array. I think the intent here is to make the base case that we have reached the end of the list, and if not we add the current element to the right list, then call ourselves on the rest of the list, taking care to increment the index and switch the spots of the current list and the one that is on deck. Then the method becomes:

//assumes all lists initialized by caller
public void splitList(ArrayList<Integer> input, int index, ArrayList<Integer> current, ArrayList<Integer> onDeck) {
    if (index >= input.size()) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(index));
        splitList(input, index + 1, onDeck, current); //note toggling output list and advancing index
    }
}

and it gets called once the input list is initialized and odds and evens contain freshly constructed empty array lists as follows:

splitList(splitThis, 0, evens, odds);//start with evens because 0 is even

REVISION:
I noticed it would be possible not to worry about the index as much and somewhat more natural to make "the rest of the list" a sublist. I also generalized to any kind of list. Thus:

//assumes all lists initialized by caller
public void splitList(List<Integer> input, List<Integer> current, List<Integer> onDeck) {
    if (input.size() == 0) { //base case
        return;
    } else { //add the current element and call us on the rest of the list
        current.add(input.get(0));
        splitList(input.subList(1, input.size()), onDeck, current); //note toggling output list and call on rest of list, if any
    }
}

and the call is simplified to:

splitList(splitThis, evens, odds);//start with evens because 0 is even


问:
Relative imports - ModuleNotFoundError: No module named x
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

```<code>debug = True
</code>```

test.py

```<code>import config
print (config.debug)
</code>```

I also have an __init__.py

However, I'm getting the following error:

```<code>ModuleNotFoundError: No module named 'config'
</code>```

I'm aware that the py3 convention is to use absolute imports:

```<code>from . import config
</code>```

However, this leads to the following error:

```<code>ImportError: cannot import name 'config'
</code>```

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)

答:
Set PYTHONPATH environment variable in root project directory.

Considering UNIX-like:

```<code>export PYTHONPATH=.
</code>```

Body:
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

debug = True

test.py

import config
print (config.debug)

I also have an __init__.py

However, I'm getting the following error:

ModuleNotFoundError: No module named 'config'

I'm aware that the py3 convention is to use absolute imports:

from . import config

However, this leads to the following error:

ImportError: cannot import name 'config'

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)

Body:
Set PYTHONPATH environment variable in root project directory.

Considering UNIX-like:

export PYTHONPATH=.


问:
XML Structure in SQL Server
I have the following code which works fine and returns the expected results:

```<code>DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)
</code>```

However, it also accept when I provide it with the following structure and returns the ssame results:

```<code>SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'
</code>```

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky

答:
If you want to enforce a specific structure of your XML, you can add a XML schema to your SQL Server database to check XML contents against a schema.

Go grab The Art of XSD - SQL Server XML Schema Collections as a free PDF download to learn more about this

Title: XML Structure in SQL Server

Body:
I have the following code which works fine and returns the expected results:

DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)

However, it also accept when I provide it with the following structure and returns the ssame results:

SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky


问:
Selecting options from Mat-select using cypress
I have Mat-select dropdown as follows

```<code><mat-form-field>
   <mat-label>Gender</mat-label>
      <mat-select id="gender" required formControlName="gender">
         <mat-option id="Male" value="male"> Male </mat-option>
         <mat-option value="female"> Female </mat-option>
      </mat-select>
 </mat-form-field>
</code>```

I'm trying to use Cypress to select male or female from the field.

```<code>cy.get('mat-select').click().select('Male')
</code>```

With the above code I get the following error:

```<code>CypressError: cy.select() can only be called on a <select>. Your subject is a: <mat-select>
</code>```

I need some help in fixing this, thank you.

The code that worked for me.

```<code>cy.get('#gender').click().then(() => {
            cy.get('#male').click()
        })
</code>```

答:
Opens up the mat-option dialog for the mat-select & selects the field that contains "Apple Inc."</p>

```<code>cy.get('mat-select[formControlName=companyName]').click().get('mat-option').contains('Apple Inc.').click();
</code>```

Body:
I have Mat-select dropdown as follows

<mat-form-field>
   <mat-label>Gender</mat-label>
      <mat-select id="gender" required formControlName="gender">
         <mat-option id="Male" value="male"> Male </mat-option>
         <mat-option value="female"> Female </mat-option>
      </mat-select>
 </mat-form-field>

I'm trying to use Cypress to select male or female from the field.

cy.get('mat-select').click().select('Male')

With the above code I get the following error:

CypressError: cy.select() can only be called on a <select>. Your subject is a: <mat-select>

I need some help in fixing this, thank you.

The code that worked for me.

cy.get('#gender').click().then(() => {
            cy.get('#male').click()
        })

Body:
Opens up the mat-option dialog for the mat-select & selects the field that contains "Apple Inc."

cy.get('mat-select[formControlName=companyName]').click().get('mat-option').contains('Apple Inc.').click();