问:
Expand Searchbar with Search icon as well as show close icon onclick using Javascript
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }</code>```

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

```

答:
$(".icon2").click(function(){
  $(this).val('');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
 float: right;
}
.container-2{
  width: 300px;
  vertical-align: middle;
  white-space: nowrap;
  position: relative;
}

.container-2 input#search::placeholder{
  color: #0BA1F5 !important;
}

.container-2 input#search{
  width: 50px;
  height: 50px;
  border-bottom:2px #0BA1F5 solid !important;
  background: #ffffff;
  border: none;
  font-size: 11pt;
  float: right;
  color: #b4b4b4;
  padding-left: 35px;

  -webkit-transition: width .55s ease;
  -moz-transition: width .55s ease;
  -ms-transition: width .55s ease;
  -o-transition: width .55s ease;
  transition: width .55s ease;
}

.container-2 input#search::-webkit-input-placeholder {
   color: #65737e;
}

.container-2 input#search:-moz-placeholder { /* Firefox 18- */
   color: #65737e;
}

.container-2 input#search::-moz-placeholder {  /* Firefox 19+ */
   color: #65737e;
}

.container-2 input#search:-ms-input-placeholder {
   color: #65737e;
}

.container-2 .icon{
  position: absolute;
  top: 50%;
  right:20px;
  margin-left: 17px;
  margin-top: 17px;
  z-index: 1;
  color: #4f5b66;
   -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
    transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.container-2 input#search:focus, .container-2 input#search:active{
  outline:none;
  width: 300px;
}

.container-2:hover input#search{
width: 300px;
}

.container-2:hover .icon{
  color: #93a2ad;
  right:280px;
}

.container-2 .icon2{
  display:none;
  position:absolute;
  right:0px;
  top: 18px;
  cursor:pointer;
     -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
    transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.container-2:hover .icon2{
display:block;
}</code>```

     <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" data-svg="search-icon"><circle fill="none" stroke="#0BA1F5" stroke-width="2" cx="9" cy="9" r="7"></circle><path fill="none" stroke="#0BA1F5" stroke-width="2" d="M14,14 L18,18 L14,14 Z"></path></svg>
     <input type="search" id="search" placeholder="Search..." />
  <svg width="16" height="16" fill="#0BA1F5" class="icon2" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 492 492" style="enable-background:new 0 0 492 492;" xml:space="preserve">
  <g>
    <g>
      <path d="M300.188,246L484.14,62.04c5.06-5.064,7.852-11.82,7.86-19.024c0-7.208-2.792-13.972-7.86-19.028L468.02,7.872
        c-5.068-5.076-11.824-7.856-19.036-7.856c-7.2,0-13.956,2.78-19.024,7.856L246.008,191.82L62.048,7.872
        c-5.06-5.076-11.82-7.856-19.028-7.856c-7.2,0-13.96,2.78-19.02,7.856L7.872,23.988c-10.496,10.496-10.496,27.568,0,38.052
        L191.828,246L7.872,429.952c-5.064,5.072-7.852,11.828-7.852,19.032c0,7.204,2.788,13.96,7.852,19.028l16.124,16.116
        c5.06,5.072,11.824,7.856,19.02,7.856c7.208,0,13.968-2.784,19.028-7.856l183.96-183.952l183.952,183.952
        c5.068,5.072,11.824,7.856,19.024,7.856h0.008c7.204,0,13.96-2.784,19.028-7.856l16.12-16.116
        c5.06-5.064,7.852-11.824,7.852-19.028c0-7.204-2.792-13.96-7.852-19.028L300.188,246z"/>
    </g>
  </g>
  </svg>

```

Body:
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });

.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

Body:
$(".icon2").click(function(){
  $(this).val('');
})

.box{
 float: right;
}
.container-2{
  width: 300px;
  vertical-align: middle;
  white-space: nowrap;
  position: relative;
}

.container-2 input#search::placeholder{
  color: #0BA1F5 !important;
}

.container-2 input#search{
  width: 50px;
  height: 50px;
  border-bottom:2px #0BA1F5 solid !important;
  background: #ffffff;
  border: none;
  font-size: 11pt;
  float: right;
  color: #b4b4b4;
  padding-left: 35px;

  -webkit-transition: width .55s ease;
  -moz-transition: width .55s ease;
  -ms-transition: width .55s ease;
  -o-transition: width .55s ease;
  transition: width .55s ease;
}

.container-2 input#search::-webkit-input-placeholder {
   color: #65737e;
}

.container-2 input#search:-moz-placeholder { /* Firefox 18- */
   color: #65737e;
}

.container-2 input#search::-moz-placeholder {  /* Firefox 19+ */
   color: #65737e;
}

.container-2 input#search:-ms-input-placeholder {
   color: #65737e;
}

.container-2 .icon{
  position: absolute;
  top: 50%;
  right:20px;
  margin-left: 17px;
  margin-top: 17px;
  z-index: 1;
  color: #4f5b66;
   -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
    transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.container-2 input#search:focus, .container-2 input#search:active{
  outline:none;
  width: 300px;
}

.container-2:hover input#search{
width: 300px;
}

.container-2:hover .icon{
  color: #93a2ad;
  right:280px;
}

.container-2 .icon2{
  display:none;
  position:absolute;
  right:0px;
  top: 18px;
  cursor:pointer;
     -webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
    transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.container-2:hover .icon2{
display:block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
 <div class="container-2">
     <span class="icon"><svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" data-svg="search-icon"><circle fill="none" stroke="#0BA1F5" stroke-width="2" cx="9" cy="9" r="7"></circle><path fill="none" stroke="#0BA1F5" stroke-width="2" d="M14,14 L18,18 L14,14 Z"></path></svg></span>
     <input type="search" id="search" placeholder="Search..." />
  <svg width="16" height="16" fill="#0BA1F5" class="icon2" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 492 492" style="enable-background:new 0 0 492 492;" xml:space="preserve">
  <g>
    <g>
      <path d="M300.188,246L484.14,62.04c5.06-5.064,7.852-11.82,7.86-19.024c0-7.208-2.792-13.972-7.86-19.028L468.02,7.872
        c-5.068-5.076-11.824-7.856-19.036-7.856c-7.2,0-13.956,2.78-19.024,7.856L246.008,191.82L62.048,7.872
        c-5.06-5.076-11.82-7.856-19.028-7.856c-7.2,0-13.96,2.78-19.02,7.856L7.872,23.988c-10.496,10.496-10.496,27.568,0,38.052
        L191.828,246L7.872,429.952c-5.064,5.072-7.852,11.828-7.852,19.032c0,7.204,2.788,13.96,7.852,19.028l16.124,16.116
        c5.06,5.072,11.824,7.856,19.02,7.856c7.208,0,13.968-2.784,19.028-7.856l183.96-183.952l183.952,183.952
        c5.068,5.072,11.824,7.856,19.024,7.856h0.008c7.204,0,13.96-2.784,19.028-7.856l16.12-16.116
        c5.06-5.064,7.852-11.824,7.852-19.028c0-7.204-2.792-13.96-7.852-19.028L300.188,246z"/>
    </g>
  </g>
  </svg>

 </div>
</div>


来源: stackexchange

问:
Get an input's "checked" state
I have this basic HTML structure:

```<code><fieldset>
    <input/>
    <label></label>
    <div class="toggle_box">
        <div class="switch"></div>
    </div>
</fieldset>
</code>```

I would like this to happen when my input is checked:

```<code><fieldset>
    <input checked="checked" />
    <label></label>
    <div class="toggle_box">
        <div class="switch" state="on"></div>
    </div>
</fieldset>
</code>```

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

答:
You can put all these divs inside another div, and then get the father div with*document.getElementById*, find the div you want in the content and change him.</p>

```<code><div id="fatherOfTheDivs">
        <fieldset>
            <input/>
            <label></label>
            <div class="toggle_box">
                <div id="div1" class="switch"></div>
            </div>
        </fieldset>

        <fieldset>
            <input/>
            <label></label>
            <div id="div2" class="toggle_box">
                <div class="switch"></div>
            </div>
        </fieldset>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get an input's "checked" state

Body:
I have this basic HTML structure:

<fieldset>
    <input/>

</fieldset>

I would like this to happen when my input is checked:

<fieldset>
    <input checked="checked" />

</fieldset>

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

Body:
You can put all these divs inside another div, and then get the father div with*document.getElementById*, find the div you want in the content and change him.

<div id="fatherOfTheDivs">
        <fieldset>
            <input/>
            <label></label>
            <div class="toggle_box">
                <div id="div1" class="switch"></div>
            </div>
        </fieldset>

        <fieldset>
            <input/>
            <label></label>
            <div id="div2" class="toggle_box">
                <div class="switch"></div>
            </div>
        </fieldset>
</div>


问:
Intellij cannot find Maven Dependencies in pom.xml
I am new to the spring boot framework and I'm trying to import the Maven libraries, but I keep getting an error with my pom.xml. Please Help!

Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:2.0.4.RELEASE from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.0.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org

Dependency 'org.springframework.boot:spring-boot-starter-web:' not found less... (Ctrl+F1)
  Inspection info: Inspects a Maven model for resolution problems.

Plugin 'org.springframework.boot:spring-boot-maven-plugin:2.0.4.RELEASE' not found less... (Ctrl+F1)
  Inspection info: Inspects a Maven model for resolution problems.

Here is my pom.xml below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.cierra</groupId>
<artifactId>spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.0.4.RELEASE</version>
        </plugin>
    </plugins>
</build>

</project>
</code>```

答:
Change Your Maven Version Ad Check Again.

Install Maven and Then Go to File/setting/build,execution,.../build Tools/maven
And Change Maven Home Directory to Your Install Maven Directory

ContentLicense: CC BY-SA 4.0

Body:
I am new to the spring boot framework and I'm trying to import the Maven libraries, but I keep getting an error with my pom.xml. Please Help!

Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:2.0.4.RELEASE from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:2.0.4.RELEASE from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org

Dependency 'org.springframework.boot:spring-boot-starter-web:' not found less... (Ctrl+F1)
  Inspection info: Inspects a Maven model for resolution problems.

Plugin 'org.springframework.boot:spring-boot-maven-plugin:2.0.4.RELEASE' not found less... (Ctrl+F1)
  Inspection info: Inspects a Maven model for resolution problems.

Here is my pom.xml below:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

<groupId>com.cierra</groupId>
<artifactId>spring-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>2.0.4.RELEASE</version>
        </plugin>
    </plugins>
</build>

</project>


问:
Optimize code for step function using only NumPy
I'm trying to optimize the function 'pw' in the following code using only NumPy functions (or perhaps list comprehensions).

```<code>from time import time
import numpy as np

def pw(x, udata):
    """
    Creates the step function
                 | 1,  if d0 <= x < d1
                 | 2,  if d1 <= x < d2
    pw(x,data) = ...
                 | N, if d(N-1) <= x < dN
                 | 0, otherwise
    where di is the ith element in data.
    INPUT:      x   --  interval which the step function is defined over
              data  --  an ordered set of data (without repetitions)
    OUTPUT: pw_func --  an array of size x.shape[0]
    """
    vals = np.arange(1,udata.shape[0]+1).reshape(udata.shape[0],1)
    pw_func = np.sum(np.where(np.greater_equal(x,udata)*np.less(x,np.roll(udata,-1)),vals,0),axis=0)
    return pw_func

N = 50000
x = np.linspace(0,10,N)
data = [1,3,4,5,5,7]
udata = np.unique(data)

ti = time()
pw(x,udata)
tf = time()
print(tf - ti)

import cProfile
cProfile.run('pw(x,udata)')
</code>```

The cProfile.run is telling me that most of the overhead is coming from np.where (about 1 ms) but I'd like to create faster code if possible. It seems that performing the operations row-wise versus column-wise makes some difference, unless I'm mistaken, but I think I've accounted for it. I know that sometimes list comprehensions can be faster but I couldn't figure out a faster way than what I'm doing using it.

Searchsorted seems to yield better performance but that 1 ms still remains on my computer:

```<code>(modified)
def pw(xx, uu):
    """
    Creates the step function
                 | 1,  if d0 <= x < d1
                 | 2,  if d1 <= x < d2
    pw(x,data) = ...
                 | N, if d(N-1) <= x < dN
                 | 0, otherwise
    where di is the ith element in data.
    INPUT:      x   --  interval which the step function is defined over
              data  --  an ordered set of data (without repetitions)
    OUTPUT: pw_func --  an array of size x.shape[0]
    """
    inds = np.searchsorted(uu, xx, side='right')
    vals = np.arange(1,uu.shape[0]+1)
    pw_func = vals[inds[inds != uu.shape[0]]]
    num_mins = np.sum(xx < np.min(uu))
    num_maxs = np.sum(xx > np.max(uu))

    pw_func = np.concatenate((np.zeros(num_mins), pw_func, np.zeros(xx.shape[0]-pw_func.shape[0]-num_mins)))
    return pw_func
</code>```

This answer using piecewise seems pretty close, but that's on a scalar x0 and x1. How would I do it on arrays? And would it be more efficient?

Understandably, x may be pretty big but I'm trying to put it through a stress test.

I am still learning though so some hints or tricks that can help me out would be great.

EDIT

There seems to be a mistake in the second function since the resulting array from the second function doesn't match the first one (which I'm confident that it works):

```<code>N1 = pw1(x,udata.reshape(udata.shape[0],1)).shape[0]
N2 = np.sum(pw1(x,udata.reshape(udata.shape[0],1)) == pw2(x,udata))
print(N1 - N2)
</code>```

yields

```<code>15000
</code>```

data points that are not the same. So it seems that I don't know how to use 'searchsorted'.

EDIT 2

Actually I fixed it:

```<code>pw_func = vals[inds[inds != uu.shape[0]]]
</code>```

was changed to

```<code>pw_func = vals[inds[inds[(inds != uu.shape[0])*(inds != 0)]-1]]
</code>```

so at least the resulting arrays match. But the question still remains on whether there's a more efficient way of going about doing this.

EDIT 3

Thanks Tin Lai for pointing out the mistake. This one should work

```<code>pw_func = vals[inds[(inds != uu.shape[0])*(inds != 0)]-1]
</code>```

Maybe a more readable way of presenting it would be

```<code>non_endpts = (inds != uu.shape[0])*(inds != 0) # only consider the points in between the min/max data values
shift_inds = inds[non_endpts]-1       # searchsorted side='right' includes the left end point and not right end point so a shift is needed
pw_func = vals[shift_inds]
</code>```

I think I got lost in all those brackets! I guess that's the importance of readability.

答:
A very abstract yet interesting problem! Thanks for entertaining me, I had fun :)

p.s. I'm not sure about your pw2 I wasn't able to get it output the same as pw1.

For reference the original pws:

def pw1(x, udata):
    vals = np.arange(1,udata.shape[0]+1).reshape(udata.shape[0],1)
    pw_func = np.sum(np.where(np.greater_equal(x,udata)*np.less(x,np.roll(udata,-1)),vals,0),axis=0)
    return pw_func

def pw2(xx, uu):
    inds = np.searchsorted(uu, xx, side='right')
    vals = np.arange(1,uu.shape[0]+1)
    pw_func = vals[inds[inds[(inds != uu.shape[0])*(inds != 0)]-1]]
    num_mins = np.sum(xx < np.min(uu))
    num_maxs = np.sum(xx > np.max(uu))

    pw_func = np.concatenate((np.zeros(num_mins), pw_func, np.zeros(xx.shape[0]-pw_func.shape[0]-num_mins)))
    return pw_func
```

<hr>

<p>My first attempt was utilising a lot of boardcasting operation from <code>numpy</code>:</p>

<pre class="lang-py prettyprint-override"><code>def pw3(x, udata):
    # the None slice is to create new axis
    step_bool = x >= udata[None,:].T

    # we exploit the fact that bools are integer value of 1s
    # skipping the last value in "data"
    step_vals = np.sum(step_bool[:-1], axis=0)

    # for the step_bool that we skipped from previous step (last index)
    # we set it to zerp so that we can negate the step_vals once we reached
    # the last value in "data"
    step_vals[step_bool[-1]] = 0

    return step_vals
</code>```

After looking at the searchsorted from your pw2 I had a new approach that utilise it with much higher performance:

def pw4(x, udata):
    inds = np.searchsorted(udata, x, side='right')

    # fix-ups the last data if x is already out of range of data[-1]
    if x[-1] > udata[-1]:
        inds[inds == inds[-1]] = 0

    return inds
```

<hr>

<p>Plots with:</p>

<pre class="lang-py prettyprint-override"><code>plt.plot(pw1(x,udata.reshape(udata.shape[0],1)), label='pw1')
plt.plot(pw2(x,udata), label='pw2')
plt.plot(pw3(x,udata), label='pw3')
plt.plot(pw4(x,udata), label='pw4')
</code>```

with data = [1,3,4,5,5,7]:

with data = [1,3,4,5,5,7,11]

pw1,pw3,pw4 are all identical

print(np.all(pw1(x,udata.reshape(udata.shape[0],1)) == pw3(x,udata)))
>>> True
print(np.all(pw1(x,udata.reshape(udata.shape[0],1)) == pw4(x,udata)))
>>> True
```

<p><strong>Performance:</strong> (<code>timeit</code> by default runs 3 times, average of <code>number=N</code> of times)</p>

<pre class="lang-py prettyprint-override"><code>print(timeit.Timer('pw1(x,udata.reshape(udata.shape[0],1))', "from __main__ import pw1, x, udata").repeat(number=1000))
>>> [3.1938983199979702, 1.6096494779994828, 1.962694135003403]
print(timeit.Timer('pw2(x,udata)', "from __main__ import pw2, x, udata").repeat(number=1000))
>>> [0.6884554479984217, 0.6075002400029916, 0.7799002879983163]
print(timeit.Timer('pw3(x,udata)', "from __main__ import pw3, x, udata").repeat(number=1000))
>>> [0.7369808239964186, 0.7557657590004965, 0.8088172269999632]
print(timeit.Timer('pw4(x,udata)', "from __main__ import pw4, x, udata").repeat(number=1000))
>>> [0.20514375300263055, 0.20203858999957447, 0.19906871100101853]
</code>```

Body:
I'm trying to optimize the function 'pw' in the following code using only NumPy functions (or perhaps list comprehensions).

from time import time
import numpy as np

def pw(x, udata):
    """
    Creates the step function
                 | 1,  if d0 <= x < d1
                 | 2,  if d1 <= x < d2
    pw(x,data) = ...
                 | N, if d(N-1) <= x < dN
                 | 0, otherwise
    where di is the ith element in data.
    INPUT:      x   --  interval which the step function is defined over
              data  --  an ordered set of data (without repetitions)
    OUTPUT: pw_func --  an array of size x.shape[0]
    """
    vals = np.arange(1,udata.shape[0]+1).reshape(udata.shape[0],1)
    pw_func = np.sum(np.where(np.greater_equal(x,udata)*np.less(x,np.roll(udata,-1)),vals,0),axis=0)
    return pw_func

N = 50000
x = np.linspace(0,10,N)
data = [1,3,4,5,5,7]
udata = np.unique(data)

ti = time()
pw(x,udata)
tf = time()
print(tf - ti)

import cProfile
cProfile.run('pw(x,udata)')

The cProfile.run is telling me that most of the overhead is coming from np.where (about 1 ms) but I'd like to create faster code if possible. It seems that performing the operations row-wise versus column-wise makes some difference, unless I'm mistaken, but I think I've accounted for it. I know that sometimes list comprehensions can be faster but I couldn't figure out a faster way than what I'm doing using it.

Searchsorted seems to yield better performance but that 1 ms still remains on my computer:

(modified)
def pw(xx, uu):
    """
    Creates the step function
                 | 1,  if d0 <= x < d1
                 | 2,  if d1 <= x < d2
    pw(x,data) = ...
                 | N, if d(N-1) <= x < dN
                 | 0, otherwise
    where di is the ith element in data.
    INPUT:      x   --  interval which the step function is defined over
              data  --  an ordered set of data (without repetitions)
    OUTPUT: pw_func --  an array of size x.shape[0]
    """
    inds = np.searchsorted(uu, xx, side='right')
    vals = np.arange(1,uu.shape[0]+1)
    pw_func = vals[inds[inds != uu.shape[0]]]
    num_mins = np.sum(xx < np.min(uu))
    num_maxs = np.sum(xx > np.max(uu))

    pw_func = np.concatenate((np.zeros(num_mins), pw_func, np.zeros(xx.shape[0]-pw_func.shape[0]-num_mins)))
    return pw_func

This answer using piecewise seems pretty close, but that's on a scalar x0 and x1. How would I do it on arrays? And would it be more efficient?

Understandably, x may be pretty big but I'm trying to put it through a stress test.

I am still learning though so some hints or tricks that can help me out would be great.

EDIT

There seems to be a mistake in the second function since the resulting array from the second function doesn't match the first one (which I'm confident that it works):

N1 = pw1(x,udata.reshape(udata.shape[0],1)).shape[0]
N2 = np.sum(pw1(x,udata.reshape(udata.shape[0],1)) == pw2(x,udata))
print(N1 - N2)

yields

15000

data points that are not the same. So it seems that I don't know how to use 'searchsorted'.

EDIT 2

Actually I fixed it:

pw_func = vals[inds[inds != uu.shape[0]]]

was changed to

pw_func = vals[inds[inds[(inds != uu.shape[0])*(inds != 0)]-1]]

so at least the resulting arrays match. But the question still remains on whether there's a more efficient way of going about doing this.

EDIT 3

Thanks Tin Lai for pointing out the mistake. This one should work

pw_func = vals[inds[(inds != uu.shape[0])*(inds != 0)]-1]

Maybe a more readable way of presenting it would be

non_endpts = (inds != uu.shape[0])*(inds != 0) # only consider the points in between the min/max data values
shift_inds = inds[non_endpts]-1       # searchsorted side='right' includes the left end point and not right end point so a shift is needed
pw_func = vals[shift_inds]

I think I got lost in all those brackets! I guess that's the importance of readability.

Body:
A very abstract yet interesting problem! Thanks for entertaining me, I had fun :)

p.s. I'm not sure about your pw2 I wasn't able to get it output the same as pw1.

For reference the original pws:

def pw1(x, udata):
    vals = np.arange(1,udata.shape[0]+1).reshape(udata.shape[0],1)
    pw_func = np.sum(np.where(np.greater_equal(x,udata)*np.less(x,np.roll(udata,-1)),vals,0),axis=0)
    return pw_func

def pw2(xx, uu):
    inds = np.searchsorted(uu, xx, side='right')
    vals = np.arange(1,uu.shape[0]+1)
    pw_func = vals[inds[inds[(inds != uu.shape[0])*(inds != 0)]-1]]
    num_mins = np.sum(xx < np.min(uu))
    num_maxs = np.sum(xx > np.max(uu))

    pw_func = np.concatenate((np.zeros(num_mins), pw_func, np.zeros(xx.shape[0]-pw_func.shape[0]-num_mins)))
    return pw_func

My first attempt was utilising a lot of boardcasting operation from numpy:

def pw3(x, udata):
    # the None slice is to create new axis
    step_bool = x >= udata[None,:].T

    # we exploit the fact that bools are integer value of 1s
    # skipping the last value in "data"
    step_vals = np.sum(step_bool[:-1], axis=0)

    # for the step_bool that we skipped from previous step (last index)
    # we set it to zerp so that we can negate the step_vals once we reached
    # the last value in "data"
    step_vals[step_bool[-1]] = 0

    return step_vals

After looking at the searchsorted from your pw2 I had a new approach that utilise it with much higher performance:

def pw4(x, udata):
    inds = np.searchsorted(udata, x, side='right')

    # fix-ups the last data if x is already out of range of data[-1]
    if x[-1] > udata[-1]:
        inds[inds == inds[-1]] = 0

    return inds

Plots with:

plt.plot(pw1(x,udata.reshape(udata.shape[0],1)), label='pw1')
plt.plot(pw2(x,udata), label='pw2')
plt.plot(pw3(x,udata), label='pw3')
plt.plot(pw4(x,udata), label='pw4')

with data = [1,3,4,5,5,7]:

with data = [1,3,4,5,5,7,11]

pw1,pw3,pw4 are all identical

print(np.all(pw1(x,udata.reshape(udata.shape[0],1)) == pw3(x,udata)))
>>> True
print(np.all(pw1(x,udata.reshape(udata.shape[0],1)) == pw4(x,udata)))
>>> True

Performance: (timeit by default runs 3 times, average of number=N of times)

print(timeit.Timer('pw1(x,udata.reshape(udata.shape[0],1))', "from __main__ import pw1, x, udata").repeat(number=1000))
>>> [3.1938983199979702, 1.6096494779994828, 1.962694135003403]
print(timeit.Timer('pw2(x,udata)', "from __main__ import pw2, x, udata").repeat(number=1000))
>>> [0.6884554479984217, 0.6075002400029916, 0.7799002879983163]
print(timeit.Timer('pw3(x,udata)', "from __main__ import pw3, x, udata").repeat(number=1000))
>>> [0.7369808239964186, 0.7557657590004965, 0.8088172269999632]
print(timeit.Timer('pw4(x,udata)', "from __main__ import pw4, x, udata").repeat(number=1000))
>>> [0.20514375300263055, 0.20203858999957447, 0.19906871100101853]


问:
Get JWT token from Appsync Resolver Mapping Template
I am using oidc as authentication in AWS Appsync. For some purpose I need the base64encoded version of JWT TOken in the resolver mapping template. Can anyone suggest any solution? Thanks in advance

答:
I found a way here:</p>

```<code>#set($token = $context.request.headers.get("authorization"))
</code>```

Body:
I found a way here:

#set($token = $context.request.headers.get("authorization"))


问:
Download a file with password and username with C#
How would I write a script to download files from this site. Is it possible to supply the login and password with the url?

http://feeds.itunes.apple.com/feeds/epf/

Would I format the url like this?

```<code>WebClient Client = new WebClient();
Client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5?username=myusername&password=mypassword", @"C:\folder\file.md5");
</code>```

答:
Yes, just set the WebClient's Credentials property to a NetworkCredentials instance with the username/password. For example:

```<code>Client.Credentials = new System.Net.NetworkCredential("john", "password1234!");
</code>```

Body:
How would I write a script to download files from this site. Is it possible to supply the login and password with the url?

http://feeds.itunes.apple.com/feeds/epf/

Would I format the url like this?

WebClient Client = new WebClient();
Client.DownloadFile("http://feeds.itunes.apple.com/feeds/epf/v3/full/current/itunes20110511.tbz.md5?username=myusername&password=mypassword", @"C:\folder\file.md5");

Body:
Yes, just set the WebClient's Credentials property to a NetworkCredentials instance with the username/password. For example:

Client.Credentials = new System.Net.NetworkCredential("john", "password1234!");


问:
Postgres - How to drop all tables in a database except for 3
I know that to drop a table in a database is as follows, but if I have a database that has over a dozen tables and I only need to keep 3 of them, am I able to delete all but the 3 with only one command?</p>

```<code>DROP TABLE IF EXISTS c_note RESTRICT;
</code>```

答:
The following query will simmply delete all the tables but keep your schema

```<code>select 'drop table if exists ' || tablename || ' cascade;'
    from pg_tables
    where schemaname = 'public'
</code>```

Write down a query where you can skip three tables by name

```<code>select 'drop table if exists ' || tablename || ' cascade;'
from pg_tables
where schemaname = 'public'
and tablename not in (:tbaleNamesToKeep);
</code>```

Body:
I know that to drop a table in a database is as follows, but if I have a database that has over a dozen tables and I only need to keep 3 of them, am I able to delete all but the 3 with only one command?

DROP TABLE IF EXISTS c_note RESTRICT;

Body:
The following query will simmply delete all the tables but keep your schema

select 'drop table if exists ' || tablename || ' cascade;'
    from pg_tables
    where schemaname = 'public'

Write down a query where you can skip three tables by name

select 'drop table if exists ' || tablename || ' cascade;'
from pg_tables
where schemaname = 'public'
and tablename not in (:tbaleNamesToKeep);


问:
php query taking too much time to complete report
hello friend i am generating a report, first i am getting material code like this

```<code>$sql_srh="select Material_code,  Mat_type , Material_Desc , UOM from (
select Material_code, Mat_type , Material_Desc , UOM from opening_data where Mat_type in ('YACC' ,
'YFAB' , 'YLFB' , 'YLAC' , 'YSFAB' , 'YSVM' , 'YSNV' ) and datee < '".$frm."' and (location like 'J%' or location like 'L%' ) union all
select Material_code, Mat_type , Material_Desc , UOM from material_data where Mat_type in ('YACC' ,
'YFAB' , 'YLFB' , 'YLAC' , 'YSFAB' , 'YSVM' , 'YSNV')  and (location like 'J%' or location like 'L%' )
) x group by Material_code";
</code>```

then i am using above result (material code) i am trying to generate a report, i have added code below to generate report from two tables.

```<code>$res = $conn->query($sql_srh);

while($res_row = $res->fetch_assoc()){

 $res_open=$conn->query("Select Sum(qty) open_blnc From (
select  qty from opening_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."'   and datee < '".$frm."' and (location like 'J%' or location like 'L%' )
Union all
select  qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."'   and Posting_date < '".$frm."' and
Debit_Credit ='S' and Move_type in ('101' , '511' , '315'  , '309' , '262' , '202' , '123' , '544' ,
'334' , '552'  , '310'  , '314') and (location like 'J%' or location like 'L%' )
Union all
select qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date < '".$frm."' and
Debit_Credit ='H' and  Move_type in ('102' , '512' , '316' , '310' , '261' , '201' , '122' , '543' ,
'333' , '551'  , '309'  , '313') and (location like 'J%' or location like 'L%' )

)x");

$row_open = $res_open->fetch_assoc();

$res_in=$conn->query("select  sum(qty) as in_qty from (
select qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='S' and Move_type in ('101' , '511' , '315' , '309') and
(location like 'J%' or location like 'L%' )
Union all
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='H' and Move_type in ('102' , '512' , '316'  , '310')
and (location like 'J%' or location like 'L%' ) )x");

$row_in = $res_in->fetch_assoc();

$sql_out="select sum(qty) as out_qty from (
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='H' and Move_type in ('261' , '201' , '122' , '543' ,
'333' , '551' , '309' , '313') and (location like 'J%' or location like 'L%' )
Union All
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='S' and Move_type in ('262' , '202' , '123' , '544' ,
'334' , '552' , '310' , '314') and (location like 'J%' or location like 'L%' ))x";
$res_out = $conn->query($sql_out);
$row_out = $res_out->fetch_assoc();

$sql_adj ="Select Sum(adj) as adj_qty , Sum(opname) as opnam_qty from ( select adj , opname  from
tbl_adj_opname where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM' , 'YSNV') and
Material_code = '".$res_row['Material_code']."' and datee >= '".$frm."' and datee <= '".$tdt."' and
(location like 'J%' or location like 'L%' ) and Debit_Credit = 'S'
Union All
select adj , opname  from tbl_adj_opname where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' ,
'YSFB' , 'YSVM' , 'YSNV') and Material_code = '".$res_row['Material_code']."' and datee >= '".$frm."'
and datee <= '".$tdt."' and (location like 'J%' or location like 'L%' ) and Debit_Credit = 'H'
)x";

$res_adj = $conn->query($sql_adj);
$row_adj = $res_adj->fetch_assoc();
</code>```

this is working fine , my issue is it is taking hours to generate report , i have 200000 rows in table.
if i comment above code (means open balance, in quantity and out quantity ) and run only first code (where i am getting material code) its done within seconds , but when i try to generate comelete report its taking hours .

where Mat_type and Move_Type is Fixed.

result will be like:
    ?>

```<code><td class="sn"><?php echo $i;?></td>
<td><?php  echo $res_row['Material_code'];?></td>
<td><?php echo $res_row['Material_Desc'];?></td>
<td><?php echo $res_row['UOM'];?></td>
<td class="lft"><?php echo $open ;?></td>
<td class="lft"><?php echo abs($row_in['in_qty']);?></td>
<td class="lft"><?php echo $outqty= ($row_out['out_qty'])*(-1);?></td>
<td><?php echo $row_adj['adj_qty'];?></td>
<td class="lft"><?php  $balance = (($open+(abs($row_in['in_qty'])))-
(abs($outqty)))+($row_adj['adj_qty']);
echo round($balance,3);
?></td>
<td class="lft"><?php /*echo $opnam = ($open)+($row_in['in_qty'])-
(abs($outqty));*/  $opnam = $row_adj['opnam_qty'];?></td>
<td class="lft"><?php  $diff = ($balance)-($opnam);  echo round($diff,3); ?>
</td>
<td></td>
</tr>
<?php } ?>
</code>```

find table with testing data here
anyone please help me.

答:
USE Inner Join

ex:

```<code> SELECT *
 FROM table1 INNER JOIN table2
 ON table1.column_name = table2.column_name;
</code>```

Body:
hello friend i am generating a report, first i am getting material code like this

$sql_srh="select Material_code,  Mat_type , Material_Desc , UOM from (
select Material_code, Mat_type , Material_Desc , UOM from opening_data where Mat_type in ('YACC' ,
'YFAB' , 'YLFB' , 'YLAC' , 'YSFAB' , 'YSVM' , 'YSNV' ) and datee < '".$frm."' and (location like 'J%' or location like 'L%' ) union all
select Material_code, Mat_type , Material_Desc , UOM from material_data where Mat_type in ('YACC' ,
'YFAB' , 'YLFB' , 'YLAC' , 'YSFAB' , 'YSVM' , 'YSNV')  and (location like 'J%' or location like 'L%' )
) x group by Material_code";

then i am using above result (material code) i am trying to generate a report, i have added code below to generate report from two tables.

$res = $conn->query($sql_srh);

while($res_row = $res->fetch_assoc()){

 $res_open=$conn->query("Select Sum(qty) open_blnc From (
select  qty from opening_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."'   and datee < '".$frm."' and (location like 'J%' or location like 'L%' )
Union all
select  qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."'   and Posting_date < '".$frm."' and
Debit_Credit ='S' and Move_type in ('101' , '511' , '315'  , '309' , '262' , '202' , '123' , '544' ,
'334' , '552'  , '310'  , '314') and (location like 'J%' or location like 'L%' )
Union all
select qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date < '".$frm."' and
Debit_Credit ='H' and  Move_type in ('102' , '512' , '316' , '310' , '261' , '201' , '122' , '543' ,
'333' , '551'  , '309'  , '313') and (location like 'J%' or location like 'L%' )

)x");

$row_open = $res_open->fetch_assoc();

$res_in=$conn->query("select  sum(qty) as in_qty from (
select qty from material_data where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='S' and Move_type in ('101' , '511' , '315' , '309') and
(location like 'J%' or location like 'L%' )
Union all
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='H' and Move_type in ('102' , '512' , '316'  , '310')
and (location like 'J%' or location like 'L%' ) )x");

$row_in = $res_in->fetch_assoc();

$sql_out="select sum(qty) as out_qty from (
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='H' and Move_type in ('261' , '201' , '122' , '543' ,
'333' , '551' , '309' , '313') and (location like 'J%' or location like 'L%' )
Union All
select qty from material_data where  Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM'
, 'YSNV') and Material_code = '".$res_row['Material_code']."' and Posting_date >= '".$frm."' and
Posting_date <= '".$tdt."' and Debit_Credit ='S' and Move_type in ('262' , '202' , '123' , '544' ,
'334' , '552' , '310' , '314') and (location like 'J%' or location like 'L%' ))x";
$res_out = $conn->query($sql_out);
$row_out = $res_out->fetch_assoc();

$sql_adj ="Select Sum(adj) as adj_qty , Sum(opname) as opnam_qty from ( select adj , opname  from
tbl_adj_opname where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' , 'YSFB' , 'YSVM' , 'YSNV') and
Material_code = '".$res_row['Material_code']."' and datee >= '".$frm."' and datee <= '".$tdt."' and
(location like 'J%' or location like 'L%' ) and Debit_Credit = 'S'
Union All
select adj , opname  from tbl_adj_opname where Mat_type in ('YACC' , 'YFAB' , 'YLFB' , 'YLAC' ,
'YSFB' , 'YSVM' , 'YSNV') and Material_code = '".$res_row['Material_code']."' and datee >= '".$frm."'
and datee <= '".$tdt."' and (location like 'J%' or location like 'L%' ) and Debit_Credit = 'H'
)x";

$res_adj = $conn->query($sql_adj);
$row_adj = $res_adj->fetch_assoc();

this is working fine , my issue is it is taking hours to generate report , i have 200000 rows in table.
if i comment above code (means open balance, in quantity and out quantity ) and run only first code (where i am getting material code) its done within seconds , but when i try to generate comelete report its taking hours .

where Mat_type and Move_Type is Fixed.

result will be like:
    ?>

<?php echo $i;?>
<?php  echo $res_row['Material_code'];?>
<?php echo $res_row['Material_Desc'];?>
<?php echo $res_row['UOM'];?>
<?php echo $open ;?>
<?php echo abs($row_in['in_qty']);?>
<?php echo $outqty= ($row_out['out_qty'])*(-1);?>
<?php echo $row_adj['adj_qty'];?>
<?php  $balance = (($open+(abs($row_in['in_qty'])))-
(abs($outqty)))+($row_adj['adj_qty']);
echo round($balance,3);
?>
<?php /*echo $opnam = ($open)+($row_in['in_qty'])-
(abs($outqty));*/  $opnam = $row_adj['opnam_qty'];?>
<?php  $diff = ($balance)-($opnam);  echo round($diff,3); ?>

<?php } ?>

find table with testing data here
anyone please help me.

Body:
USE Inner Join

ex:

 SELECT *
 FROM table1 INNER JOIN table2
 ON table1.column_name = table2.column_name;


问:
How to restore pg_dump file into mysql database?
I have a backup file which I obtained using pg_dump command in linux mint. I want to restore this database file into a mysql database. I am using dbeaver tool. The command I used to get the database backup was this.

```<code>pg_dump -h localhost -p 5432 -U postgres -F c -b -v -f "/home/james/BACKUPFILE.bak" DB_NAME
</code>```

I am able to restore this backupfile into another postgres database fine but I need to restore the same into a mysql database.

Command I am using to restore the backup into postgres database is

```<code>pg_restore -h localhost -p 5432 -U postgres -d DB_NAME_NEW -v "/home/james/BACKUPFILE.bak"
</code>```

Hope someone can help

答:
You cannot simply pg_dump from a Postgres database and expect to be able to load it into a MySQL database, since there are syntactical differences between the two database engines, along with some differences in structure/organization (e.g., storage engines).  In order to perform this task, you'll need to use a third-party migration tool (seems that pg2mysql is a pretty well-known one).

Otherwise, you can try using DBeaver's Export Data function and see if you can map columns/tables (or create tables) as desired.

Disclosure: I work for EnterpriseDB (EDB)

Body:
I have a backup file which I obtained using pg_dump command in linux mint. I want to restore this database file into a mysql database. I am using dbeaver tool. The command I used to get the database backup was this.

pg_dump -h localhost -p 5432 -U postgres -F c -b -v -f "/home/james/BACKUPFILE.bak" DB_NAME

I am able to restore this backupfile into another postgres database fine but I need to restore the same into a mysql database.

Command I am using to restore the backup into postgres database is

pg_restore -h localhost -p 5432 -U postgres -d DB_NAME_NEW -v "/home/james/BACKUPFILE.bak"

Hope someone can help


问:
NEED EXCEL IN COUNTIF AND COUNTIFS
ı am stuck in formula and ı don't know how to solve this problem.
ı want a write a formula which is check the names if the names are same counts data which is in the other column.
Can you help me please.</p>

答:
In the formula below the name is in A2. The formula searches all the column B for duplicates and writes the number of matches found in its own cell. Therefore the formula must be in a column other than A or B.

```<code>=COUNTIF($B:$B, $A2)
</code>```

Say, you have the formula in cell C2, you can copy it down as far as column A has values and do the count for every one of the names in column A.

Title: NEED EXCEL IN COUNTIF AND COUNTIFS

Body:
In the formula below the name is in A2. The formula searches all the column B for duplicates and writes the number of matches found in its own cell. Therefore the formula must be in a column other than A or B.

=COUNTIF($B:$B, $A2)

Say, you have the formula in cell C2, you can copy it down as far as column A has values and do the count for every one of the names in column A.


问:
How to customize Search Suggestion UI which show details in a hierarchical model
How to implement a view which contains an EditText ,whenever we type something it should show categories and items in the individual category as shown in the image.

答: Such view can be implemented as https://developer.android.com/reference/android/widget/PopupWindow.html?hl=en popup windows, which get updated/recreated on each change in EditText</p>


问:
Printing a squares triangle. How to mirror numbers?
So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.

However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:

```<code>          1
       4  1
    9  4  1
16  9  4  1
    9  4  1
       4  1
          1
</code>```

For full credit, each column should be 3 characters wide and the values should be right justified.

Now here is what I have written for my code so far:

import java.util.Scanner;
public class lab6 {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        System.out.println(
                "Enter a number that is between 1 and 9 (inclusive): ");

        // this is the value that the user will enter for # of rows
        int rows = kybd.nextInt();

        for (int i = rows; i > 0; i--) {
            for (int j = rows; j > 0; j--)
                System.out.print((rows - j + 1) < i ?
                        "   " : String.format("%3d", j * j));
            System.out.println();
        }
    }
}
```
<p>And this is what that code PRINTS when I enter <code>4</code>:</p>
```Enter a number that is between 1 and 9 (inclusive):
4
          1
       4  1
    9  4  1
16  9  4  1
```

As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.

答:
Answer is:

```<code>public static void main(String... args) {
    Scanner kybd = new Scanner(System.in);
    System.out.println("Enter a number that is between 1 and 9 (inclusive): ");

    int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

    for (int i = -rows + 1; i < rows; i++) {
        for (int j = -rows; j < 0; j++)
            System.out.print(abs(i) > j + rows ? "   " : String.format("%3d", j * j));
        System.out.println();
    }
}
</code>```

Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):

```<code>y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
</code>```

And here is example result for 4:

And 9:

Body:
So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.

However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:

          1
       4  1
    9  4  1
16  9  4  1
    9  4  1
       4  1
          1

For full credit, each column should be 3 characters wide and the values should be right justified.

Now here is what I have written for my code so far:

import java.util.Scanner;
public class lab6 {
    public static void main(String[] args) {
        Scanner kybd = new Scanner(System.in);
        System.out.println(
                "Enter a number that is between 1 and 9 (inclusive): ");

        // this is the value that the user will enter for # of rows
        int rows = kybd.nextInt();

        for (int i = rows; i > 0; i--) {
            for (int j = rows; j > 0; j--)
                System.out.print((rows - j + 1) < i ?
                        "   " : String.format("%3d", j * j));
            System.out.println();
        }
    }
}

And this is what that code PRINTS when I enter 4:

Enter a number that is between 1 and 9 (inclusive):
4
          1
       4  1
    9  4  1
16  9  4  1

As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.

Body:
Answer is:

public static void main(String... args) {
    Scanner kybd = new Scanner(System.in);
    System.out.println("Enter a number that is between 1 and 9 (inclusive): ");

    int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

    for (int i = -rows + 1; i < rows; i++) {
        for (int j = -rows; j < 0; j++)
            System.out.print(abs(i) > j + rows ? "   " : String.format("%3d", j * j));
        System.out.println();
    }
}

Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):

y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4

And here is example result for 4:

And 9:


问:
Classes & concurrent futures multithreading
I just started understanding the concept of classes in python and I wish to improve my script. Basically my script checks the status of various URLS using the requests library and does other post processing with the data received. Currently my script is full of functions and am passing around the same parameters to each function. The issue I am facing is I am using concurrent.futures multithreading but am unsure of how can I use it to call a class instead of a function.

I am just doing a simple test below to be able to retrive a dictionary back from the class after processing. However, it is returning me a class object and I can't figure out how to extract the data from the class object.

The purpose of my class is that I want to use it for getting the status of each url and doing some post processing and returning back the dictionary.

```<code>from concurrent.futures import ThreadPoolExecutor

class capture_screenshot(object):
    def __init__(self, customer_data):
        self.customer_data = customer_data

    def complex_function(self):
        ....
        self.customer_data = processed_data

url_dict = {"url_0": "https://redacted.com/a", "url_1": "https://redacted.com/b", ...}

with ThreadPoolExecutor(max_workers=16) as executor:
    processed_results = list(executor.map(capture_screenshot, url_dict.items()))

print(processed_results) # This should be "https://redacted.com/a but I am getting a class object
</code>```

```<code>processed_results : [<capture_screenshot object at 0x0000020443...>, <capture_screenshot object at 0x0000020443...>]
</code>```

Many thanks.

答:
I think that the processed_results = list(executor.map(capture_screenshot, url_dict)) just initializes the object (calls the __init__ method).
That is why you receive objects.

I think you also need to execute the objects after initialization.
Try maybe something like this:

```<code>with ThreadPoolExecutor(max_workers=16) as executor:
    processed_results = list(executor.map(capture_screenshot, url_dict.items()))

results = [res.customer_data for res in processed_results]
</code>```

Body:
I just started understanding the concept of classes in python and I wish to improve my script. Basically my script checks the status of various URLS using the requests library and does other post processing with the data received. Currently my script is full of functions and am passing around the same parameters to each function. The issue I am facing is I am using concurrent.futures multithreading but am unsure of how can I use it to call a class instead of a function.

I am just doing a simple test below to be able to retrive a dictionary back from the class after processing. However, it is returning me a class object and I can't figure out how to extract the data from the class object.

The purpose of my class is that I want to use it for getting the status of each url and doing some post processing and returning back the dictionary.

from concurrent.futures import ThreadPoolExecutor

class capture_screenshot(object):
    def __init__(self, customer_data):
        self.customer_data = customer_data

    def complex_function(self):
        ....
        self.customer_data = processed_data

url_dict = {"url_0": "https://redacted.com/a", "url_1": "https://redacted.com/b", ...}

with ThreadPoolExecutor(max_workers=16) as executor:
    processed_results = list(executor.map(capture_screenshot, url_dict.items()))

print(processed_results) # This should be "https://redacted.com/a but I am getting a class object

processed_results : [<capture_screenshot object at 0x0000020443...>, <capture_screenshot object at 0x0000020443...>]

Many thanks.

Body:
I think that the processed_results = list(executor.map(capture_screenshot, url_dict)) just initializes the object (calls the __init__ method).
That is why you receive objects.

I think you also need to execute the objects after initialization.
Try maybe something like this:

with ThreadPoolExecutor(max_workers=16) as executor:
    processed_results = list(executor.map(capture_screenshot, url_dict.items()))

results = [res.customer_data for res in processed_results]


问:
Background image responsive without getting cropped
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page </p>

```<code><div class="inner-banner has-base-color-overlay text-center" style="background: url(header.jpg); background-size: cover; position: center;">
    <div class="container">
        <div class="box">
            <h3>About Us</h3>
        </div>
    </div>
</div>
</code>```

答:
replace your style with below code : -</p>

```<code>background: url(header.jpg); background-size: 100%; position: center;
</code>```

Body:
I've already made the background image to full size in my page, but when I inspect and try to display it in phone mode, my background image get cropped, how can I resist this thing so it can't get cropped but always cover particular part of the page

About Us

Body:
replace your style with below code : -

background: url(header.jpg); background-size: 100%; position: center;


问:
how to use "text.changed" control from code using MVVM (in Xamarin.Forms)
I am trying to make a text box change its color when an entry's text meets some requisites, calling a function form my ViewModel every time a new character is added to the text, and I am using FreshMVVM, meaning that I cant directly use the control "text.changed" since bindings can't be used for controls (if I am not mistaken).

Looking for answers I have found the nugget package "Behaviors.Forms", which would let me do it.
The problem is that I am not using an entry perse, but a custom view that works as an entry, and the previously mentioned package doesn't let me use entry.behaviors for my custom entry.

Most of the posts and discussions about this matter were old (from 2016 or 2017), so is there any way to bind controls to your ViewModel now?, and if not, is there any way to do the specific task that I have explained?

Thank you all for your time, hope you have a good day.

答:
you can try Triggers like below example</p>

```<code><Entry Placeholder="Insert your name"
        BackgroundColor="LightCoral" >
      <Entry.Triggers>
          <Trigger TargetType="Entry"
                   Property="Text"
                   Value="Charlin">
              <Setter Property="BackgroundColor" Value="LightBlue" />
              <Setter Property="Scale" Value="1.1" />
          </Trigger>
      </Entry.Triggers>
 </Entry>
</code>```

Body:
you can try Triggers like below example

<Entry Placeholder="Insert your name"
        BackgroundColor="LightCoral" >
      <Entry.Triggers>
          <Trigger TargetType="Entry"
                   Property="Text"
                   Value="Charlin">
              <Setter Property="BackgroundColor" Value="LightBlue" />
              <Setter Property="Scale" Value="1.1" />
          </Trigger>
      </Entry.Triggers>
 </Entry>


问:
How to submit data to Google forms with Java (jsoup or other)
I want to submit data from Java to a Google form. Using JSoup and the following code I can't achieve this goal. I've tried several different methods and I've searched for few days with still no result. My last resort is to bug some intelligent people on Stackoverflow. Can anybody help me?

```<code>    String url = "http://docs.google.com/forms/d/1OEBmIXG-enn3Yb48JKfRHjHFsTnGUZkIR_7KHR_raF0/viewform";

    try {
        Jsoup.connect(url)
                .data("entry.1278622432", "reply")
                .data("entry.1578309861", "reply")
                //.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .userAgent("Mozilla")
                .post();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

Error:

```<code>org.jsoup.HttpStatusException: HTTP error fetching URL. Status=405, URL=http://doc
</code>```

Html error code:

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

(Solution doesn't have to be with JSoup.)

答:
Add the following dependency

```<code>    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.19.4</version>
    </dependency>
</code>```

Then import the following packages

```<code> import com.sun.jersey.api.client.Client;
 import com.sun.jersey.api.client.ClientResponse;
 import com.sun.jersey.api.client.WebResource;
</code>```

Change the following code snippet accordingly

```<code> String url = "https://docs.google.com/forms/d/e/" + FORM_ID + "/formResponse?" + metaData +
            "&draftResponse=%5B%5D%0D%0A&pageHistory=0&fbzx=-5804634750901421753";

 Client client = Client.create();
 WebResource webResource = client.resource(url);
 ClientResponse response =webResource
                    .accept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Host", "docs.google.com")
                    .header("User-Agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) " +
                            "Gecko/20100101 Firefox/26.0")
                    .header("Accept-Encoding", " gzip, deflate")
                    .header("Accept-Language", "nl,en-us;q=0.7,en;q=0.3")
                    .header("DNT", 1)
                    .header("Referer", "https://docs.google.com/forms/d/e/" + FORM_ID + "/viewform")
                    .header("Cookie", "GDS_PREF=hl=en_US; __utma=184632636.34...1517515.2; PREF=ID=4922e3....:FF=0:LD=nl:TM=1380883655:LM=1381731571:S=JvyU_OhlkQ7rE3x3; NID=67=hy29...sglz4PVeS53BZ4eLkYK_wDm9-jmdj7apqNZv6rEwUPDobxjagtLN5gpl4A7v0oA")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("cookie", "S=spreadsheet_forms=ay7KL1tRTlqur9RqEdI6mxMF6vx3FcsM; CONSENT=YES+LK.en+20180304-09-0; SEARCH_SAMESITE=CgQI5Y4B; HSID=ADSwbqJPF1Qr-Ec-y; SSID=A4q87SuvNBKdb2ple; APISID=gkfURe1KHD3JK_Sw/AEHh8huA9FCjME_AH; SAPISID=BYtObLGnVKKbphJu/AOOdACYgOk7aPfh5h; __Secure-HSID=ADSwbqJPF1Qr-Ec-y; __Secure-SSID=A4q87SuvNBKdb2ple; __Secure-APISID=gkfURe1KHD3JK_Sw/AEHh8huA9FCjME_AH; __Secure-3PAPISID=BYtObLGnVKKbphJu/AOOdACYgOk7aPfh5h; S=billing-ui-v3=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:billing-ui-v3-efe=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:adwords-navi=FttYNTeVNckYg7X8E3ZsxsJ1vM7Zsbb1; SID=tQdHP8MAb80SUf_M7LebR0rky_mob9y0tekyqkfTiK6WCjtIptZqkRG_2zw8vDx7Wyelow.; __Secure-3PSID=tQdHP8MAb80SUf_M7LebR0rky_mob9y0tekyqkfTiK6WCjtIaTSJ2pBkmZ-zBBINW3RhYw.; S=billing-ui-v3=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:billing-ui-v3-efe=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:adwords-navi=FttYNTeVNckYg7X8E3ZsxsJ1vM7Zsbb1:explorer=IK1XkkO0xKJk5bU2F52cs0z1t8mXK5v1; NID=197=rBl9xBCn7YlyxrnqcHF35435sGtnCn6dSss6tr6EPfswg19EFOKGJz_upr5qLgJ922wl0G6ufAnILvoUMx1Csvg9ddVMJE65ALGlSm2u4ERtePDrka2yLQE4XQGvX6WXGNJz9e7HFSmWZTOGD_f0wA2BudviRAbKxqUyPHPxR_uhqAH-andEJDUdosDmuGRg27JKl_IyEd98qlEd-2c_rNx06tE7BnjBkW66v-XB-AGZP0610_JSW2fzemYTPuPC2ZL3iFTFFF4fPP5rhhoNCM2GApidF9yG0hxKFBbTLLphy4IvTl8gBkj10l-DZS_Njr6A8uCts1RfaGL5aq8-yz1IRKEANrheizBWCYNioi1bmgeBl_89WJyYCVfYROBHbPQW0blRimGX4Ql4wcM; 1P_JAR=2020-2-12-4; SIDCC=AN0-TYtB0dfkjw4QetRyEiIaeRH9MuEXLmZe5C8w55MLe8EK_1P0ktruhGOZaXInzu_VfIjkQ8K3")
                    .get(ClientResponse.class);
</code>```

Body:
I want to submit data from Java to a Google form. Using JSoup and the following code I can't achieve this goal. I've tried several different methods and I've searched for few days with still no result. My last resort is to bug some intelligent people on Stackoverflow. Can anybody help me?

    String url = "http://docs.google.com/forms/d/1OEBmIXG-enn3Yb48JKfRHjHFsTnGUZkIR_7KHR_raF0/viewform";

    try {
        Jsoup.connect(url)
                .data("entry.1278622432", "reply")
                .data("entry.1578309861", "reply")
                //.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .userAgent("Mozilla")
                .post();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Error:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=405, URL=http://doc

Html error code:

10.4.6 405 Method Not Allowed

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.

(Solution doesn't have to be with JSoup.)

Body:
Add the following dependency

    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.19.4</version>
    </dependency>

Then import the following packages

 import com.sun.jersey.api.client.Client;
 import com.sun.jersey.api.client.ClientResponse;
 import com.sun.jersey.api.client.WebResource;

Change the following code snippet accordingly

 String url = "https://docs.google.com/forms/d/e/" + FORM_ID + "/formResponse?" + metaData +
            "&draftResponse=%5B%5D%0D%0A&pageHistory=0&fbzx=-5804634750901421753";

 Client client = Client.create();
 WebResource webResource = client.resource(url);
 ClientResponse response =webResource
                    .accept("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Host", "docs.google.com")
                    .header("User-Agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) " +
                            "Gecko/20100101 Firefox/26.0")
                    .header("Accept-Encoding", " gzip, deflate")
                    .header("Accept-Language", "nl,en-us;q=0.7,en;q=0.3")
                    .header("DNT", 1)
                    .header("Referer", "https://docs.google.com/forms/d/e/" + FORM_ID + "/viewform")
                    .header("Cookie", "GDS_PREF=hl=en_US; __utma=184632636.34...1517515.2; PREF=ID=4922e3....:FF=0:LD=nl:TM=1380883655:LM=1381731571:S=JvyU_OhlkQ7rE3x3; NID=67=hy29...sglz4PVeS53BZ4eLkYK_wDm9-jmdj7apqNZv6rEwUPDobxjagtLN5gpl4A7v0oA")
                    .header("Connection", "keep-alive")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("cookie", "S=spreadsheet_forms=ay7KL1tRTlqur9RqEdI6mxMF6vx3FcsM; CONSENT=YES+LK.en+20180304-09-0; SEARCH_SAMESITE=CgQI5Y4B; HSID=ADSwbqJPF1Qr-Ec-y; SSID=A4q87SuvNBKdb2ple; APISID=gkfURe1KHD3JK_Sw/AEHh8huA9FCjME_AH; SAPISID=BYtObLGnVKKbphJu/AOOdACYgOk7aPfh5h; __Secure-HSID=ADSwbqJPF1Qr-Ec-y; __Secure-SSID=A4q87SuvNBKdb2ple; __Secure-APISID=gkfURe1KHD3JK_Sw/AEHh8huA9FCjME_AH; __Secure-3PAPISID=BYtObLGnVKKbphJu/AOOdACYgOk7aPfh5h; S=billing-ui-v3=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:billing-ui-v3-efe=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:adwords-navi=FttYNTeVNckYg7X8E3ZsxsJ1vM7Zsbb1; SID=tQdHP8MAb80SUf_M7LebR0rky_mob9y0tekyqkfTiK6WCjtIptZqkRG_2zw8vDx7Wyelow.; __Secure-3PSID=tQdHP8MAb80SUf_M7LebR0rky_mob9y0tekyqkfTiK6WCjtIaTSJ2pBkmZ-zBBINW3RhYw.; S=billing-ui-v3=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:billing-ui-v3-efe=qCH3rMDDCaZ_xpidA_rUzezuzbz9IcRd:adwords-navi=FttYNTeVNckYg7X8E3ZsxsJ1vM7Zsbb1:explorer=IK1XkkO0xKJk5bU2F52cs0z1t8mXK5v1; NID=197=rBl9xBCn7YlyxrnqcHF35435sGtnCn6dSss6tr6EPfswg19EFOKGJz_upr5qLgJ922wl0G6ufAnILvoUMx1Csvg9ddVMJE65ALGlSm2u4ERtePDrka2yLQE4XQGvX6WXGNJz9e7HFSmWZTOGD_f0wA2BudviRAbKxqUyPHPxR_uhqAH-andEJDUdosDmuGRg27JKl_IyEd98qlEd-2c_rNx06tE7BnjBkW66v-XB-AGZP0610_JSW2fzemYTPuPC2ZL3iFTFFF4fPP5rhhoNCM2GApidF9yG0hxKFBbTLLphy4IvTl8gBkj10l-DZS_Njr6A8uCts1RfaGL5aq8-yz1IRKEANrheizBWCYNioi1bmgeBl_89WJyYCVfYROBHbPQW0blRimGX4Ql4wcM; 1P_JAR=2020-2-12-4; SIDCC=AN0-TYtB0dfkjw4QetRyEiIaeRH9MuEXLmZe5C8w55MLe8EK_1P0ktruhGOZaXInzu_VfIjkQ8K3")
                    .get(ClientResponse.class);


问:
Why do i need to left shift before summing the result?
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

```<code>public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}
</code>```

答:
In the first iteration it indeed has no effect, but thats okay, thats intended. It is better, than writing if (i != 0) result <<= 1;. That would be inefficient to check this in every iteration. But also important to note this that essentially out of the 32 iteration only in 31 it will have an effect and should. So if you put the result <<= 1; line in the end than make sure it is only executing effectively 31 times also keeping in mind, that now it should execute in the first iteration since the order changed, but it should not in the last iteration. That is the reason why the result will be invalid.

Try this. This will work.

```<code>public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result += n&1;
        n >>= 1;
        if (i != 31) // skip the shift in last iteration
            result <<= 1;
    }
    return result;
}
</code>```

Body:
Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1 have to occur before I sum result with the operation n&1?

In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1 line at the END of the for loop, I would still be left shifting result before I sum result with n&1.
My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.

public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result <<= 1;
        result += n&1;
        n >>= 1;
    }
    return result;
}

Body:
In the first iteration it indeed has no effect, but thats okay, thats intended. It is better, than writing if (i != 0) result <<= 1;. That would be inefficient to check this in every iteration. But also important to note this that essentially out of the 32 iteration only in 31 it will have an effect and should. So if you put the result <<= 1; line in the end than make sure it is only executing effectively 31 times also keeping in mind, that now it should execute in the first iteration since the order changed, but it should not in the last iteration. That is the reason why the result will be invalid.

Try this. This will work.

public int reverseBits(int n) {
    int result = 0;
    for(int i=0; i<32; i++){
        result += n&1;
        n >>= 1;
        if (i != 31) // skip the shift in last iteration
            result <<= 1;
    }
    return result;
}


问:
Is it possible to use Standalone filter along with column filters?
I understand we can use a Standalone filter without individual column filters (https://akveo.github.io/ng2-smart-table/#/examples/using-filters) But is it possible to use both?

I tried to implement it but could not. See https://stackblitz.com/edit/angular-2cwakj?file=src%2Fapp%2Ffilter-poc%2Ffilter-poc.component.ts

答:
Change your onSearch function with following function.</p>

```<code>  onSearch(query: string = '') {
   this.source = new LocalDataSource(this.data.filter((obj)=>{
   if(obj.id.toString().indexOf(query)>-1 || obj.name.indexOf(query)>-1 ||
    obj.username.indexOf(query)>-1 ||obj.email.indexOf(query)>-1 ) return true;
   else false;
  }))
 }
</code>```

Body:
Change your onSearch function with following function.

  onSearch(query: string = '') {
   this.source = new LocalDataSource(this.data.filter((obj)=>{
   if(obj.id.toString().indexOf(query)>-1 || obj.name.indexOf(query)>-1 ||
    obj.username.indexOf(query)>-1 ||obj.email.indexOf(query)>-1 ) return true;
   else false;
  }))
 }


问:
TypeError when assigning a random value from a list to a variable?
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

```<code>import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw
</code>```

When I try to run it I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing
</code>```

Body:
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.

import random

cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }

for newCard in range(5):
        newDraw = random.choice(cards)
        playerdeck.append(newDraw)
        if newDraw in playerdeck:
                playermatches = playermatches + 1
        newDraw = oldDraw

When I try to run it I get this error:

Traceback (most recent call last):
  File "C:\Users\Nathaniel\Desktop\Fcard.py", line 6, in <module>
    newDraw = random.choice(cards)
  File "C:\Python32\lib\random.py", line 253, in choice
    return seq[i]
TypeError: 'set' object does not support indexing

Body:
So use a list:

>>> cards = ['2', '3', '4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A']
>>> random.choice(cards)
'9'


问:
How to merge two arrays of objects in Laravel controller?
I have these function to call to sets of data which is using DB query for Data A and CURL for Data B.

Right now I managed to display the output but somehow Data A cannot merge into Data B. My code as below.

Namespace :

```<code>use \stdClass;
</code>```

Code :

```<code>public function find($user = null) {
    if($user)
    {
        // Data A
        $sql            = "SELECT * FROM TABLE WHERE ID = '".$user."' ";
        $arr            = DB::connection('mysql')->select($sql);
        $resultData     = new \stdClass();

        foreach ($arr as $key => $value)
        {
            $resultData->$key = $value; // Extract Data A table
        }

        // Data B
        $url    = "http://localhost/data/curl.php?value=".$user;
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        $row    = json_decode($result, true);

        foreach ($row as $key => $value)
        {
            $resultData->$key = $value; // Extract Data B
        }

        dd($resultData);
        return true;
    }
    return false;
}
</code>```

My goal is to merge these two sets of data (A & B) into one.

What I get right now is like this in my browser if I display output separately. When I combined it, it only show Data B :

Data A

```<code>{#310
  +"0": {#213
    +"id": "1"
    +"name": "MIKE"
    +"acc_no": "AAA001"
    +"email": "mike@col.com"
  }
}
</code>```

Data B

```<code>{#310
  +"0": "CLERK"
  +"TITLE": "CLERK"
  +"1": "Clerk, IT Department"
  +"POSITION": "Clerk, IT Department"
  +"2": "Rozaimi Bin Zamahri"
  +"SECTION": "Office"
}
</code>```

Appreciate if someone can help me. Thanks.

答:
Problem1:
Don't just concat sql string with the params, it has SQL-injection problem, if you want to use DB::select with params, you can do it like this:

$sql  = "SELECT * FROM TABLE WHERE ID = ? ";
$arr  = DB::connection('mysql')->select($sql, [$user]);
```

<p><strong>Problem2:</strong>
Because you are using DB select method, it will return an array nest with objects. you need to get the object first, do something like this:</p>

<pre class="lang-php prettyprint-override"><code>$arr = DB::connection('mysql')->select($sql)[0];
</code>```

And then you can merge them by loop or just turn them to array and merge them.

Body:
I have these function to call to sets of data which is using DB query for Data A and CURL for Data B.

Right now I managed to display the output but somehow Data A cannot merge into Data B. My code as below.

Namespace :

use \stdClass;

Code :

public function find($user = null) {
    if($user)
    {
        // Data A
        $sql            = "SELECT * FROM TABLE WHERE ID = '".$user."' ";
        $arr            = DB::connection('mysql')->select($sql);
        $resultData     = new \stdClass();

        foreach ($arr as $key => $value)
        {
            $resultData->$key = $value; // Extract Data A table
        }

        // Data B
        $url    = "http://localhost/data/curl.php?value=".$user;
        $ch     = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);
        $result = curl_exec($ch);
        curl_close($ch);
        $row    = json_decode($result, true);

        foreach ($row as $key => $value)
        {
            $resultData->$key = $value; // Extract Data B
        }

        dd($resultData);
        return true;
    }
    return false;
}

My goal is to merge these two sets of data (A & B) into one.

What I get right now is like this in my browser if I display output separately. When I combined it, it only show Data B :

Data A

{#310
  +"0": {#213
    +"id": "1"
    +"name": "MIKE"
    +"acc_no": "AAA001"
    +"email": "mike@col.com"
  }
}

Data B

{#310
  +"0": "CLERK"
  +"TITLE": "CLERK"
  +"1": "Clerk, IT Department"
  +"POSITION": "Clerk, IT Department"
  +"2": "Rozaimi Bin Zamahri"
  +"SECTION": "Office"
}

Appreciate if someone can help me. Thanks.

Body:
Problem1:
Don't just concat sql string with the params, it has SQL-injection problem, if you want to use DB::select with params, you can do it like this:

$sql  = "SELECT * FROM TABLE WHERE ID = ? ";
$arr  = DB::connection('mysql')->select($sql, [$user]);

Problem2:
Because you are using DB select method, it will return an array nest with objects. you need to get the object first, do something like this:

$arr = DB::connection('mysql')->select($sql)[0];

And then you can merge them by loop or just turn them to array and merge them.


问:
Using of SQLite TypeError: Cannot read property 'transaction' of null
I use ionic4 + angular8 code flow:

Error code:

Please help me. Thank you.

error code in here
enter image description here

答:
When you open or create db from sqlite , you should use executeSql after to execute query and take action with db. Sqlite for ionic 4 doesn't support transaction anymore.
For more information and example</p>

```<code>this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) => {

    db.executeSql('create table danceMoves(name VARCHAR(32))', [])
      .then(() => console.log('Executed SQL'))
      .catch(e => console.log(e));

  })
  .catch(e => console.log(e));
</code>```

Body:
When you open or create db from sqlite , you should use executeSql after to execute query and take action with db. Sqlite for ionic 4 doesn't support transaction anymore.
For more information and example

this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) => {

    db.executeSql('create table danceMoves(name VARCHAR(32))', [])
      .then(() => console.log('Executed SQL'))
      .catch(e => console.log(e));

  })
  .catch(e => console.log(e));


问:
Retrieving the selected values from Bootstrap dual list in asp.net core
I am building a web app using .NET core 2.1. In one of the views there are multiple select lists, each contains thousands of items for the user to choose from so I decided to use bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/). I have 2 issues with this setup:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)
2- I need to save the items selected by the user so he can have the same list each time he logs in the app (The original not selected list is populated from the database with all the items shown regardless to the user selections from last time he used the app)
Here is my code:

ViewModel.cs:

```<code>public ViewModel()
{
    TradeList = new List<DimTrade>();
    LocationList = new List<DimLocation>();
}
public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }
</code>```

cshtml:

```<code><div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>
</div>

<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>
</div>
<scaript>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>
</code>```

Post action method:

```<code>public IActionResult Edit(ViewModel model)
{
    if (ModelState.IsValid)
    {
         // Process the model
    }
    return View(model);
</code>```

The problem is that the TradeList and LoactionList objects are always null.

I appreciate your help with both issues

答:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)

As @Charles mentioned, if you check the request, you would find only the selected vlaue of dropdown was sent via form data, like below.

To get selected value(s) of ddlTrade and ddlLocation, you can try to modiofy and inclue properties for selected values in your view model class, like below.

```<code>public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }

public List<string> SelectedTradeKeyList { get; set; }
public List<string> SelectedLocationKeyList { get; set; }
</code>```

Then modify the html and js code of these two dropdowns as below.

```<code><div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.SelectedTradeKeyList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple"></select>
</div>

<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.SelectedLocationKeyList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple"></select>
</div>

$('#ddlTrade').bootstrapDualListbox();
$('#ddlLocation').bootstrapDualListbox();
</code>```

Test Result

Note: you can also try another apporach to achieve your requirement. For example, you can dynamically generate form data based on parameter your controller action expected, then submit it using jQuery etc.

2- I need to save the items selected by the user so he can have the same list each time he logs in the app

You can try to maintain user selected options in browser web storage, so that you can perform additional js code logic to set selected options for dropdown(s).

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Body:
I am building a web app using .NET core 2.1. In one of the views there are multiple select lists, each contains thousands of items for the user to choose from so I decided to use bootstrap dual list (https://www.virtuosoft.eu/code/bootstrap-duallistbox/). I have 2 issues with this setup:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)
2- I need to save the items selected by the user so he can have the same list each time he logs in the app (The original not selected list is populated from the database with all the items shown regardless to the user selections from last time he used the app)
Here is my code:

ViewModel.cs:

public ViewModel()
{
    TradeList = new List<DimTrade>();
    LocationList = new List<DimLocation>();
}
public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }

cshtml:

    <select id="ddlTrade" class="form-control" asp-for="@Model.TradeList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="TradeList"></select>

    <select id="ddlLocation" class="form-control" asp-for="@Model.LocationList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple" name="LocationList"></select>

<scaript>
    $('[name=TradeList]').bootstrapDualListbox();
    $('[name=LocationList]').bootstrapDualListbox();
</script>

Post action method:

public IActionResult Edit(ViewModel model)
{
    if (ModelState.IsValid)
    {
         // Process the model
    }
    return View(model);

The problem is that the TradeList and LoactionList objects are always null.

I appreciate your help with both issues

Body:
1- When I hit the submit button, the model coming to the post action method does not contain the items selected by the user in the dual lists (The items in the right hand side of the list)

As @Charles mentioned, if you check the request, you would find only the selected vlaue of dropdown was sent via form data, like below.

To get selected value(s) of ddlTrade and ddlLocation, you can try to modiofy and inclue properties for selected values in your view model class, like below.

public List<DimTrade> TradeList { get; set; }
public List<DimLocation> LocationList { get; set; }

public List<string> SelectedTradeKeyList { get; set; }
public List<string> SelectedLocationKeyList { get; set; }

Then modify the html and js code of these two dropdowns as below.

<div class="col-8">
    <select id="ddlTrade" class="form-control" asp-for="@Model.SelectedTradeKeyList" asp-items="@(new SelectList(Model.TradeList, "TradeKey", "Name"))"
            placeholder="Please select" multiple="multiple"></select>
</div>

<div class="col-8">
    <select id="ddlLocation" class="form-control" asp-for="@Model.SelectedLocationKeyList" asp-items="@(new SelectList(Model.LocationList, "LocationKey", "Name"))"
            placeholder="Please select" multiple="multiple"></select>
</div>

$('#ddlTrade').bootstrapDualListbox();
$('#ddlLocation').bootstrapDualListbox();

Test Result

Note: you can also try another apporach to achieve your requirement. For example, you can dynamically generate form data based on parameter your controller action expected, then submit it using jQuery etc.

2- I need to save the items selected by the user so he can have the same list each time he logs in the app

You can try to maintain user selected options in browser web storage, so that you can perform additional js code logic to set selected options for dropdown(s).

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


问:
How to make an application command?
Is there a way I can make a command such as -apply and the bot sends them a DM starting that you've started your application! Then it asks a question, and the person answers, then it goes to the second question, person answers, then they can say submit or react with a check to send their answers and it sends all of their answers and the questions to a channel I specify in my server?

答: Yes it is possible, you can use the message.collector methods. Here is a nice example that partially fulfills your needs.

Title: How to make an application command?


问:
Is it possible to replicate kafka topics without alias prefix with MirrorMaker2
I'm trying to set up replication between 2 clusters but don't want want the topic names to be changed. for example if i have a topic called "some_topic" it is automatically replicated to "cluster1.some_topic", I'm pretty sure this can be done but haven't found the correct config to change this

My current config "mirrormaker2.properties"

```<code># Sample MirrorMaker 2.0 top-level configuration file
# Run with ./bin/connect-mirror-maker.sh connect-mirror-maker.properties

# specify any number of cluster aliases
clusters = cluster1, cluster2

# connection information for each cluster
cluster1.bootstrap.servers = host1:9092,host2:9092,host3:9092
cluster2.bootstrap.servers = rep_host1:9092,rep_host2:9092,rep_host3:9092

# enable and configure individual replication flows
cluster1->cluster2.enabled = true
cluster1->cluster2.topics = sometopic.*

# customize as needed
# replication.policy.separator = _
# sync.topic.acls.enabled = false
# emit.heartbeats.interval.seconds = 5
</code>```

for reference:

https://cwiki.apache.org/confluence/display/KAFKA/KIP-382%3A+MirrorMaker+2.0#KIP-382:MirrorMaker2.0-RunningastandaloneMirrorMakerconnector

https://kafka.apache.org/24/javadoc/index.html?constant-values.html

答:
I think the answer above is inappropriate.

In Mirror Maker 2.0, if you want to keep the topic unmodified, you have to implement ReplicationPolicy.

You can refer to DefaultReplicationPolicy.class, and then override formatRemoteTopic(), after that you have to remove sourceClusterAlias + separator. In the end, configure replication.policy.class in the mm2.properties

I defined MigrationReplicationPolicy.class

```<code>replication.policy.class = org.apache.kafka.connect.mirror.MigrationReplicationPolicy
</code>```

You should see MirrorClientConfig,class, I know that you will understand

Body:
I'm trying to set up replication between 2 clusters but don't want want the topic names to be changed. for example if i have a topic called "some_topic" it is automatically replicated to "cluster1.some_topic", I'm pretty sure this can be done but haven't found the correct config to change this

My current config "mirrormaker2.properties"

# Sample MirrorMaker 2.0 top-level configuration file
# Run with ./bin/connect-mirror-maker.sh connect-mirror-maker.properties

# specify any number of cluster aliases
clusters = cluster1, cluster2

# connection information for each cluster
cluster1.bootstrap.servers = host1:9092,host2:9092,host3:9092
cluster2.bootstrap.servers = rep_host1:9092,rep_host2:9092,rep_host3:9092

# enable and configure individual replication flows
cluster1->cluster2.enabled = true
cluster1->cluster2.topics = sometopic.*

# customize as needed
# replication.policy.separator = _
# sync.topic.acls.enabled = false
# emit.heartbeats.interval.seconds = 5

for reference:

https://cwiki.apache.org/confluence/display/KAFKA/KIP-382%3A+MirrorMaker+2.0#KIP-382:MirrorMaker2.0-RunningastandaloneMirrorMakerconnector

https://kafka.apache.org/24/javadoc/index.html?constant-values.html

Body:
I think the answer above is inappropriate.

In Mirror Maker 2.0, if you want to keep the topic unmodified, you have to implement ReplicationPolicy.

You can refer to DefaultReplicationPolicy.class, and then override formatRemoteTopic(), after that you have to remove sourceClusterAlias + separator. In the end, configure replication.policy.class in the mm2.properties

I defined MigrationReplicationPolicy.class

replication.policy.class = org.apache.kafka.connect.mirror.MigrationReplicationPolicy

You should see MirrorClientConfig,class, I know that you will understand