问:
Can't call axios function within promise then() method
I am new to promises back-end in general, so apologies if this is a dumb question.  receivePublicToken() is a method being called from a REST endpoint.  I am then trying to call an axios function within that method's then method (aka, if the receivePublicToken() method succeeds, continue on and call another axios function).  The axios function always returns an error.

```<code>import { receivePublicToken } from "./controller";

receivePublicToken(req)
.then(resolve => {
  console.log("Resolved: ", resolve);
  axios.get("/transactions")
  .then(res => console.log("Axios succeeded!"))
  .catch(rej => console.log("Axios failed!")); //this always fails
})
.catch(reject => {
  console.log("Reject: ", reject);
});
</code>```

The error it gives me:

```<code>{ Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
</code>```

Any thoughts?  Alternatively, if anyone has any suggestions on a better approach to this, I'm all ears.  Thank you to all in advance! :)

答:
If your API is implemented in a way that requires a secret token in the header then you probably need to insert the token in the header.

Can you provide a bit more detail about the get request you are executing?

is this line console.log("Resolved: ", resolve); executes?

Body:
I am new to promises back-end in general, so apologies if this is a dumb question.  receivePublicToken() is a method being called from a REST endpoint.  I am then trying to call an axios function within that method's then method (aka, if the receivePublicToken() method succeeds, continue on and call another axios function).  The axios function always returns an error.

import { receivePublicToken } from "./controller";

receivePublicToken(req)
.then(resolve => {
  console.log("Resolved: ", resolve);
  axios.get("/transactions")
  .then(res => console.log("Axios succeeded!"))
  .catch(rej => console.log("Axios failed!")); //this always fails
})
.catch(reject => {
  console.log("Reject: ", reject);
});

The error it gives me:

{ Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)

Any thoughts?  Alternatively, if anyone has any suggestions on a better approach to this, I'm all ears.  Thank you to all in advance! :)


来源: stackexchange

问:
getting "Whitelabel Error Page" running actuator health and mappings urls
I am starting with spring boot, running a demo spring web starter project, I was checking the spring actuator functionality by calling http://localhost:8080/mappings and http://localhost:8080/health  ... It's giving me the "Whitelabel Error Page" ... the log is not showing anything

the project is a very simple boot application created in STS with one @RestController which is working fine

Main class :

```<code>@SpringBootApplication
public class DemoApplication {

    public static HashMap<Long,Student> hmStudent;

    public static void main(String[] args) {
        //dummt code
          SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

Rest Controller :

```<code>import java.util.HashMap;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.DemoApplication;
import com.example.demo.entities.Student;

@RestController
@RequestMapping(value="/rest/student")
class StudentService{

   @RequestMapping(value="/",method = RequestMethod.GET)
   public HashMap<Long,Student> getAllStudents(){
      return DemoApplication.hmStudent;
   }
.
.
.
.
}
</code>```

application properties :

```<code>spring.datasource.url=jdbc:oracle:thin:@localhost:ibmwas
spring.datasource.username=u
spring.datasource.password=p
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
</code>```

pom.xml

```<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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jta-atomikos</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

What is the problem and how can I the logs be more descriptive

ContentLicense: CC BY-SA 3.0

Body:
I am starting with spring boot, running a demo spring web starter project, I was checking the spring actuator functionality by calling http://localhost:8080/mappings and http://localhost:8080/health  ... It's giving me the "Whitelabel Error Page" ... the log is not showing anything

the project is a very simple boot application created in STS with one @RestController which is working fine

Main class :

@SpringBootApplication
public class DemoApplication {

    public static HashMap<Long,Student> hmStudent;

    public static void main(String[] args) {
        //dummt code
          SpringApplication.run(DemoApplication.class, args);
    }
}

Rest Controller :

import java.util.HashMap;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.DemoApplication;
import com.example.demo.entities.Student;

@RestController
@RequestMapping(value="/rest/student")
class StudentService{

   @RequestMapping(value="/",method = RequestMethod.GET)
   public HashMap<Long,Student> getAllStudents(){
      return DemoApplication.hmStudent;
   }
.
.
.
.
}

application properties :

spring.datasource.url=jdbc:oracle:thin:@localhost:ibmwas
spring.datasource.username=u
spring.datasource.password=p
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

pom.xml

<?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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jta-atomikos</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

What is the problem and how can I the logs be more descriptive

Body:
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

ContentLicense: CC BY-SA 4.0


答:
Try this:

```<code># Get all columns from 1 to 328 and stack them into a temp series
tmp = df.loc[:, 1:].stack()

# Get the 1s
ones = tmp[tmp == 1].values.astype('int8')

# Mix with 5% zeros. You can use ceil or floor here
# as long as it makes an integer
n_zero = np.ceil(ones.shape[0] * .05).astype('int')

# Make the 0s
zeros = np.zeros(n_zero, dtype='int8')

# Replace 5% of the 1s with 0s and shuffle them
noise = np.concatenate((ones[n_zero:], zeros))
np.random.shuffle(noise)

# Assign the noise back to `tmp`
tmp.loc[tmp == 1] = noise

# Assign the noise back to the orignal frame
df.loc[:, 1:] = tmp.unstack()
</code>```

You can tell whether 5% of 1s has been replaced with 0s by summing the before and after frames:

```<code># Run this before and after the last line above to verify
df.loc[:, 1:].values.sum()
</code>```

Title: add random noise in a dataframe

Body:
i have a dataframe with this kind of data :

      0    1    2    3    4    5    6    7    8    9    10   11   12   13   14   15   16   17   18   19   ...  309  310  311  312  313  314  315  316  317  318  319  320  321  322  323  324  325  326  327  328
0      18    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0
1      84    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0
2      50    1    0    1    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0  ...    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0

the df shape is (10000, 329)

I would like to turn random 5% of  1 in the dataframe  to 0.

Is this possible?

Body:
Try this:

# Get all columns from 1 to 328 and stack them into a temp series
tmp = df.loc[:, 1:].stack()

# Get the 1s
ones = tmp[tmp == 1].values.astype('int8')

# Mix with 5% zeros. You can use ceil or floor here
# as long as it makes an integer
n_zero = np.ceil(ones.shape[0] * .05).astype('int')

# Make the 0s
zeros = np.zeros(n_zero, dtype='int8')

# Replace 5% of the 1s with 0s and shuffle them
noise = np.concatenate((ones[n_zero:], zeros))
np.random.shuffle(noise)

# Assign the noise back to `tmp`
tmp.loc[tmp == 1] = noise

# Assign the noise back to the orignal frame
df.loc[:, 1:] = tmp.unstack()

You can tell whether 5% of 1s has been replaced with 0s by summing the before and after frames:

# Run this before and after the last line above to verify
df.loc[:, 1:].values.sum()


问:
Find mismatch location across two vectors, including NAs
I'm quite embarrassed to ask this question. An experienced R user should definitely know this, yet here goes:

I need to find the location of the mismatches between two supposedly identical vectors. It's very important in this case that NAs are considered mismatches.

Data example

```<code>> x <- c(1, NA, NA, NA, 5); x
[1]  1 NA NA NA  5
> y <- c(1, NA, NA, 4, 5); y
[1]  1 NA NA  4  5
</code>```

What I want to get

Doesn't matter to me if I get a boolean vector or a numeric vector with the mismatch locations:

```<code>> c(F, T, T, T, F)
[1] FALSE  TRUE  TRUE  TRUE FALSE
> 2:4
[1] 2 3 4
</code>```

Things I've tried:

```<code>> which(x != y)
integer(0)
> setdiff(x, y)
numeric(0)
> !(x %in% y)
[1] FALSE FALSE FALSE FALSE FALSE
</code>```

答:
You can use :

```<code>x != y | is.na(x & y)
#Or checking NA individually
#x != y | is.na(x) | is.na(y)
#[1] FALSE  TRUE  TRUE  TRUE FALSE
</code>```

You can then easily wrap which around this to get numeric vector

```<code>which(x != y | is.na(x & y))
#[1] 2 3 4
</code>```

Body:
I'm quite embarrassed to ask this question. An experienced R user should definitely know this, yet here goes:

I need to find the location of the mismatches between two supposedly identical vectors. It's very important in this case that NAs are considered mismatches.

Data example

> x <- c(1, NA, NA, NA, 5); x
[1]  1 NA NA NA  5
> y <- c(1, NA, NA, 4, 5); y
[1]  1 NA NA  4  5

What I want to get

Doesn't matter to me if I get a boolean vector or a numeric vector with the mismatch locations:

> c(F, T, T, T, F)
[1] FALSE  TRUE  TRUE  TRUE FALSE
> 2:4
[1] 2 3 4

Things I've tried:

> which(x != y)
integer(0)
> setdiff(x, y)
numeric(0)
> !(x %in% y)
[1] FALSE FALSE FALSE FALSE FALSE

Body:
You can use :

x != y | is.na(x & y)
#Or checking NA individually
#x != y | is.na(x) | is.na(y)
#[1] FALSE  TRUE  TRUE  TRUE FALSE

You can then easily wrap which around this to get numeric vector

which(x != y | is.na(x & y))
#[1] 2 3 4


问:
Further Clarification about Previous Question: How do I implement multiple recyclerviews in a viewpager2(+ tablayout) with multiple fragments?
For further information on the problems that I am facing with my code, please refer to the first question. But I have recognized that the level of detail might be a little too extreme for conveying what I need help with. My essential problem is that I want to implement multiple recyclerviews in a viewpager2 that has a tab layout labeling from Monday to Sunday. At the bottom right hand corner, there is a floating action button that is meant to call an intent to this xml file below. Once the button is clicked for the xml file, it should go back to tablayout and should display the "prescription" as described in the previous question for that specific day.

Main Idea/Problem:  A prescription should be added to the end of the list for a specific day. Basically, I need to have multiple recyclerviews for each of the tabs in the tab layout that can manually have items added onto 1 of 7 recyclerviews.

Best Solution: The best and easiest way for someone to help me is to provide sample code that accomplishes this. Sample code that can function with multiple recyclerviews, a viewpager2, and multiple fragments will help me solve my problem.

Another solution: I have read really good advice here on Stack Overflow related to RecyclerView.RecycledViewPool(), and if someone can explain how I could properly integrate this into my code, that would also be a fine answer.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".add_medication_to_list">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cf1874"
        app:layout_constraintTop_toTopOf="parent"
        >
    </android.widget.Toolbar>

    <EditText
        android:id="@+id/medicine_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop='100dp'
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter name of prescription"
        />

    <EditText
        android:id="@+id/medicine_quantity"
        android:layout_width="match_parent"
        android:layout_height="43dp"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:inputType="number"
        android:hint="number of medications"
        />

    <EditText
        android:id="@+id/dosage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:ems="10"
        android:inputType="number"
        android:hint="Enter dosage"
         />

    <EditText
        android:id="@+id/frequency"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:layout_marginTop="250dp"
        android:ems="10"
        android:hint="How often do you take your prescription?"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:ems="10"
        android:inputType="time"
        android:hint="Time to take medicine"
         />

    <Button
        android:id="@+id/addButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="400dp"
        android:text="Add new prescription"
         />
</RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>`

</code>```

答: Resolved the issue. Fixed it with finish(). </p>

Body:
For further information on the problems that I am facing with my code, please refer to the first question. But I have recognized that the level of detail might be a little too extreme for conveying what I need help with. My essential problem is that I want to implement multiple recyclerviews in a viewpager2 that has a tab layout labeling from Monday to Sunday. At the bottom right hand corner, there is a floating action button that is meant to call an intent to this xml file below. Once the button is clicked for the xml file, it should go back to tablayout and should display the "prescription" as described in the previous question for that specific day.

Main Idea/Problem:  A prescription should be added to the end of the list for a specific day. Basically, I need to have multiple recyclerviews for each of the tabs in the tab layout that can manually have items added onto 1 of 7 recyclerviews.

Best Solution: The best and easiest way for someone to help me is to provide sample code that accomplishes this. Sample code that can function with multiple recyclerviews, a viewpager2, and multiple fragments will help me solve my problem.

Another solution: I have read really good advice here on Stack Overflow related to RecyclerView.RecycledViewPool(), and if someone can explain how I could properly integrate this into my code, that would also be a fine answer.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".add_medication_to_list">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#cf1874"
        app:layout_constraintTop_toTopOf="parent"
        >
    </android.widget.Toolbar>

    <EditText
        android:id="@+id/medicine_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop='100dp'
        android:ems="10"
        android:inputType="textPersonName"
        android:hint="Enter name of prescription"
        />

    <EditText
        android:id="@+id/medicine_quantity"
        android:layout_width="match_parent"
        android:layout_height="43dp"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:inputType="number"
        android:hint="number of medications"
        />

    <EditText
        android:id="@+id/dosage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:ems="10"
        android:inputType="number"
        android:hint="Enter dosage"
         />

    <EditText
        android:id="@+id/frequency"
        android:layout_width="match_parent"
        android:layout_height="51dp"
        android:layout_marginTop="250dp"
        android:ems="10"
        android:hint="How often do you take your prescription?"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="300dp"
        android:ems="10"
        android:inputType="time"
        android:hint="Time to take medicine"
         />

    <Button
        android:id="@+id/addButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="400dp"
        android:text="Add new prescription"
         />
</RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>`


问:
Azure DevOps Pipeline Build - register COM DLL
Background:
Few Projects in my solution, are dependent on COM libraries. So these COM DLLs has to be registered before building the actual solution.

In Azure DevOps - Pipeline - Build - Task,
I added a "Command Line" agent job, with the following command,

Scenario 1:

C:\windows\system32\regsvr32.exe /s [DLLFilePath]\[DLLName].dll

Scenario 2:

CD [DLLFilePath]

C:\windows\system32\regsvr32.exe /s [DLLName].dll

But both the scenarios return the same error during build time,

[error]Cmd.exe exited with code '3'.

Note:

The DLL is copied to the above mentioned location using a seperate agent job, before invoking regsvr32.

[DLLFilePath]\[DLLName].dll is a local path in the build agent, say c:\..\someLibrary.dll

答:
In my project a have same problem (I think).
Error after build: COM library no registered.

But I registered my COM library with C:\windows\system32\regsvr32.exe and registered x64 dll.

My solution: I change BuildPlatform from "Any CPU" to "x64".


问:
how to install bottle package in python?
Facing problem while installing bottle package to python 2.7

I am using windows 7 system
which having python 2.7 & 3.4.

'PY' command is for python 2.7 & 'PYTHON' command is for python 3.4

Now how to install bottle package in python 2.7

```<code>C:> py
import bottle
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ImportError: No module named bottle
</code>```

I installed for python 3.4 using easy_install -U bottle command.

It's working fine for python 3.4

```<code>C:>python
import bottle
</code>```

I am facing problem how to install bottle packages in python 2.7

This is how my python 3.4 directory looks

```<code>C:\Python34>dir
 Volume in drive C is System
 Volume Serial Number is 9CA3-A130
 Directory of C:\Python34<br />

 12/08/2014  09:49 PM    <DIR>          .
 12/08/2014  09:49 PM    <DIR>          ..
 12/08/2014  09:49 PM             1,024 add2virtualenv.bat
 12/08/2014  09:49 PM                83 cd-.bat
 12/08/2014  09:49 PM               644 cdproject.bat
 12/08/2014  09:49 PM               368 cdsitepackages.bat
 12/08/2014  09:49 PM               350 cdvirtualenv.bat
 09/28/2014  05:35 PM    <DIR>          distribution
 09/28/2014  01:28 AM    <DIR>          DLLs
 09/28/2014  01:28 AM    <DIR>          Doc
 12/08/2014  09:49 PM               421 folder_delete.bat
 09/28/2014  01:28 AM    <DIR>          include
 01/12/2015  01:36 AM    <DIR>          Lib
 09/28/2014  01:28 AM    <DIR>          libs
 05/18/2014  10:48 AM            31,073 LICENSE.txt
 12/08/2014  09:49 PM               997 lssitepackages.bat
 12/08/2014  09:49 PM               267 lsvirtualenv.bat
 12/08/2014  09:49 PM             1,947 mkvirtualenv.bat
 02/19/2011  01:40 AM           773,968 msvcr100.dll
 05/18/2014  10:33 AM           349,518 NEWS.txt
 05/18/2014  10:37 AM           102,400 py.exe
 05/18/2014  10:38 AM            27,136 python.exe
 05/18/2014  10:38 AM         2,734,592 python34.dll
 05/18/2014  10:39 AM            27,648 pythonw.exe
 05/18/2014  10:37 AM           102,912 pyw.exe
 05/04/2014  10:32 PM             6,942 README.txt
 12/08/2014  09:49 PM             1,000 rmvirtualenv.bat
 01/12/2015  01:35 AM    <DIR>          Scripts
 12/08/2014  09:49 PM               994 setprojectdir.bat
 09/28/2014  01:28 AM    <DIR>          tcl
 12/08/2014  09:49 PM               422 toggleglobalsitepackages.bat
 09/28/2014  01:28 AM    <DIR>          Tools
 12/08/2014  09:49 PM               183 whereis.bat
 12/08/2014  09:49 PM               936 workon.bat
          23 File(s)      4,165,825 bytes
          11 Dir(s)  30,791,503,872 bytes free
 C:\Python34>
</code>```

答:
Going forward, I realized having 2.x and 3.x will give me problems on installing via pip or pip3 I need to be very specific and I can't have multiple 3.x version at same time.

While coming to Linux and Mac there is a feature to differentiate python environments using pyenv, for Windows I have contributed recently called pyenv for windows pyenv-win. Hope this might help.

Body:
Facing problem while installing bottle package to python 2.7

I am using windows 7 system
which having python 2.7 & 3.4.

'PY' command is for python 2.7 & 'PYTHON' command is for python 3.4

Now how to install bottle package in python 2.7

C:> py
import bottle
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ImportError: No module named bottle

I installed for python 3.4 using easy_install -U bottle command.

It's working fine for python 3.4

C:>python
import bottle

I am facing problem how to install bottle packages in python 2.7

This is how my python 3.4 directory looks

C:\Python34>dir
 Volume in drive C is System
 Volume Serial Number is 9CA3-A130
 Directory of C:\Python34

 12/08/2014  09:49 PM    <DIR>          .
 12/08/2014  09:49 PM    <DIR>          ..
 12/08/2014  09:49 PM             1,024 add2virtualenv.bat
 12/08/2014  09:49 PM                83 cd-.bat
 12/08/2014  09:49 PM               644 cdproject.bat
 12/08/2014  09:49 PM               368 cdsitepackages.bat
 12/08/2014  09:49 PM               350 cdvirtualenv.bat
 09/28/2014  05:35 PM    <DIR>          distribution
 09/28/2014  01:28 AM    <DIR>          DLLs
 09/28/2014  01:28 AM    <DIR>          Doc
 12/08/2014  09:49 PM               421 folder_delete.bat
 09/28/2014  01:28 AM    <DIR>          include
 01/12/2015  01:36 AM    <DIR>          Lib
 09/28/2014  01:28 AM    <DIR>          libs
 05/18/2014  10:48 AM            31,073 LICENSE.txt
 12/08/2014  09:49 PM               997 lssitepackages.bat
 12/08/2014  09:49 PM               267 lsvirtualenv.bat
 12/08/2014  09:49 PM             1,947 mkvirtualenv.bat
 02/19/2011  01:40 AM           773,968 msvcr100.dll
 05/18/2014  10:33 AM           349,518 NEWS.txt
 05/18/2014  10:37 AM           102,400 py.exe
 05/18/2014  10:38 AM            27,136 python.exe
 05/18/2014  10:38 AM         2,734,592 python34.dll
 05/18/2014  10:39 AM            27,648 pythonw.exe
 05/18/2014  10:37 AM           102,912 pyw.exe
 05/04/2014  10:32 PM             6,942 README.txt
 12/08/2014  09:49 PM             1,000 rmvirtualenv.bat
 01/12/2015  01:35 AM    <DIR>          Scripts
 12/08/2014  09:49 PM               994 setprojectdir.bat
 09/28/2014  01:28 AM    <DIR>          tcl
 12/08/2014  09:49 PM               422 toggleglobalsitepackages.bat
 09/28/2014  01:28 AM    <DIR>          Tools
 12/08/2014  09:49 PM               183 whereis.bat
 12/08/2014  09:49 PM               936 workon.bat
          23 File(s)      4,165,825 bytes
          11 Dir(s)  30,791,503,872 bytes free
 C:\Python34>


问:
In C++, how do you initialize an array of pointers to wchar_t* (resulting in wchar_t**)?
I'm calling a COM function that requires a wchar_t** argument. What I would like to do is:

```<code>wchar_t* arr[3] = {L"str1", L"str2", L"str3"};
</code>```

What I get back is a const wchar_t**, which the compiler rejects.

I also tried:

```<code>wchar_t* arr[3];
wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;
</code>```

What I get back is wchar_t* (*)[3], which the compiler also rejects.

I'm new to C++ and really struggling with how string literals are handled.

ETA: The function I'm trying to use is GetIDsOfNames and the second parameter is where I'm having a problem. I want to pass 3 names in that parameter (I can successfully pass one name with wchar_t ptName[] = L"namestring" but can't figure out how to combine multiple names in an array).

```<code>HRESULT GetIDsOfNames(
REFIID   riid,
LPOLESTR *rgszNames,
UINT     cNames,
LCID     lcid,
DISPID   *rgDispId
);
</code>```

答:
The main problem you are encountering is that the array must be an array of pointers to non-constant characters, however you are trying to use string literals which are constant characters.

Most examples you find online of calling this function ignore this problem because the Microsoft compiler allowed this type error up until recently (and still does if you don't invoke it in strict standard mode, AFAIK).

To set up the array in Standard C++ the code could be:

```<code>wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
wchar_t* arr[3] = { p1, p2, p3 };
</code>```

and so the whole call might be:

```<code>DISPID dispid[3];
HRESULT result = iFoo->GetIDsOfNames( IID_NULL, arr, 3, LOCALE_SYSTEM_DEFAULT, dispid);
</code>```

The code you described as "I also tried:" would be correct but I guess you mistakenly went on to put &arr as argument to GetIDsOfNames, instead of arr.

It's normal practice in COM programming for C++ to use wrapper classes that provide a more convenient C++ interface to these underlying C Win32 API functions .

Body:
I'm calling a COM function that requires a wchar_t** argument. What I would like to do is:

wchar_t* arr[3] = {L"str1", L"str2", L"str3"};

What I get back is a const wchar_t**, which the compiler rejects.

I also tried:

wchar_t* arr[3];
wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
arr[0] = p1;
arr[1] = p2;
arr[2] = p3;

What I get back is wchar_t* (*)[3], which the compiler also rejects.

I'm new to C++ and really struggling with how string literals are handled.

ETA: The function I'm trying to use is GetIDsOfNames and the second parameter is where I'm having a problem. I want to pass 3 names in that parameter (I can successfully pass one name with wchar_t ptName[] = L"namestring" but can't figure out how to combine multiple names in an array).

HRESULT GetIDsOfNames(
REFIID   riid,
LPOLESTR *rgszNames,
UINT     cNames,
LCID     lcid,
DISPID   *rgDispId
);

Body:
The main problem you are encountering is that the array must be an array of pointers to non-constant characters, however you are trying to use string literals which are constant characters.

Most examples you find online of calling this function ignore this problem because the Microsoft compiler allowed this type error up until recently (and still does if you don't invoke it in strict standard mode, AFAIK).

To set up the array in Standard C++ the code could be:

wchar_t p1[] = L"str1";
wchar_t p2[] = L"str2";
wchar_t p3[] = L"str3";
wchar_t* arr[3] = { p1, p2, p3 };

and so the whole call might be:

DISPID dispid[3];
HRESULT result = iFoo->GetIDsOfNames( IID_NULL, arr, 3, LOCALE_SYSTEM_DEFAULT, dispid);

The code you described as "I also tried:" would be correct but I guess you mistakenly went on to put &arr as argument to GetIDsOfNames, instead of arr.

It's normal practice in COM programming for C++ to use wrapper classes that provide a more convenient C++ interface to these underlying C Win32 API functions .


问:
A justification for remote code use is required. - Chrome Extenstion
My Extension is not getting published because of 2 error

A justification for remote code use is required.

The single purpose description is required.

Here's my manifest:

```<code>{
  "name": "Spotlight",
  "icons": {
    "128": "icon_128.png",
    "96": "icon.png"
  },
  "description": "Spotlight - Browse open tabs, search history, bookmarks, downloads, and do much more!",
  "version": "1.19",
  "manifest_version": 2,
  "permissions": [],
  "update_url": "https://clients2.google.com/service/update2/crx",
  "homepage_url": "https://usespotlight.co",
  "optional_permissions" : [
    "<all_urls>",
    "tabs",
    "bookmarks",
    "history",
    "downloads",
    "storage"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "commands": {
    "toggle-feature": {
      "suggested_key": {
        "default": "Ctrl+M",
        "mac": "Command+M"
       },
      "description": "Toggle spotlight"
    }
  }
}
</code>```

答: Go to https://chrome.google.com/webstore/devconsole/ then click on  Privacy menu (3th tab on the left) then fill all your purpose description. After that you can release your extension normally

Body:
My Extension is not getting published because of 2 error

A justification for remote code use is required.

The single purpose description is required.

Here's my manifest:

{
  "name": "Spotlight",
  "icons": {
    "128": "icon_128.png",
    "96": "icon.png"
  },
  "description": "Spotlight - Browse open tabs, search history, bookmarks, downloads, and do much more!",
  "version": "1.19",
  "manifest_version": 2,
  "permissions": [],
  "update_url": "https://clients2.google.com/service/update2/crx",
  "homepage_url": "https://usespotlight.co",
  "optional_permissions" : [
    "<all_urls>",
    "tabs",
    "bookmarks",
    "history",
    "downloads",
    "storage"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "commands": {
    "toggle-feature": {
      "suggested_key": {
        "default": "Ctrl+M",
        "mac": "Command+M"
       },
      "description": "Toggle spotlight"
    }
  }
}


问:
Is there a way to read binary data in JavaScript?
I would like to inject binary data into an object in JavaScript. Is there a way to do this?

i.e.

```<code>var binObj = new BinaryObject('101010100101011');
</code>```

Something to that effect. Any help would be great.

答:
Percent encoding can unescape strings into a direct 1<->1 representaion of any binary blob and is also portable across browsers;

```<code>unescape("%uFFFF%uFFFF%uFFFF");
</code>```

Most browser exploit's use this technique for embedding shellcode into HTML pages, it works very well for creating arbitrary binary streams.

LastEditorDisplayName: Kent Fredric

Body:
I would like to inject binary data into an object in JavaScript. Is there a way to do this?

i.e.

var binObj = new BinaryObject('101010100101011');

Something to that effect. Any help would be great.

Body:
Percent encoding can unescape strings into a direct 1<->1 representaion of any binary blob and is also portable across browsers;

unescape("%uFFFF%uFFFF%uFFFF");

Most browser exploit's use this technique for embedding shellcode into HTML pages, it works very well for creating arbitrary binary streams.


问:
Postgres query for daily occupancy?
The table e_log has columns time_event (timestamp) and event_type ('E' or 'X' for entry or exit). There are no people overnight so on a given day the occupancy is the Es minus the Xs where time_event is that day. I'm trying to query for each day's occupancy of 2019, the result is supposed to be

Day                    Occupancy

2019-01-01            14

2109-01-02            22

.

.

.

Any suggestions? The closest is hard-coding each specific day and counting the number of entries but I am unsure of how to get the point in the day where the entries - exits is max. For example this query will always return 0 because everyone leaves by midnight -

```<code>select sum(case when event_type ='E' then 1 else -1 end)
from e_log
where e_log.time_event > cast('2019-01-01 00:00:00' as timestamp) and
      e_log.time_event < cast('2019-01-01 23:59:00' as timestamp);
</code>```

Thanks for any suggestions!

答:
If I understand correctly I would be inclined to write this as:</p>

```<code>select date_trunc('day', time_event) as dte,
       (count(*) filter (where event_type = 'E') -
        count(*) filter (where event_type = 'X')
       )
from e_log l
where e.time_event >= '2019-01-01'::timestamp
      e.time_event < '2020-01-01'::timestamp
group by dte
order by dte;
</code>```

Title: Postgres query for daily occupancy?

Body:
The table e_log has columns time_event (timestamp) and event_type ('E' or 'X' for entry or exit). There are no people overnight so on a given day the occupancy is the Es minus the Xs where time_event is that day. I'm trying to query for each day's occupancy of 2019, the result is supposed to be

Day                    Occupancy

2019-01-01            14

2109-01-02            22

.

.

.

Any suggestions? The closest is hard-coding each specific day and counting the number of entries but I am unsure of how to get the point in the day where the entries - exits is max. For example this query will always return 0 because everyone leaves by midnight -

select sum(case when event_type ='E' then 1 else -1 end)
from e_log
where e_log.time_event > cast('2019-01-01 00:00:00' as timestamp) and
      e_log.time_event < cast('2019-01-01 23:59:00' as timestamp);

Thanks for any suggestions!

Body:
If I understand correctly I would be inclined to write this as:

select date_trunc('day', time_event) as dte,
       (count(*) filter (where event_type = 'E') -
        count(*) filter (where event_type = 'X')
       )
from e_log l
where e.time_event >= '2019-01-01'::timestamp
      e.time_event < '2020-01-01'::timestamp
group by dte
order by dte;


问:
remove margin between QLabel and QLineEdit
I'm trying to create Login Window, which has QLineEdit below QLabel, but the current QLabel taking too many space in Window, i don't know why, here is the picture :

```<code>QLabel { background-color: red; }
</code>```

My Code :

```<code>self.text = QLabel("LOGIN")

# self.text.setStyleSheet("QLabel { background-color: red; color : white;margin-top: 50px;margin-bottom: 0px; }")
self.text.setAlignment(Qt.AlignCenter)
# self.text.setContentsMargins(0, 0, 0, 0)
# self.text.setGeometry(QRect(10,10,30,80))

font = QFont("Sans-Serif", 30)
self.text.setFont(font)

form = QLineEdit("Write my name here..")
form.setAlignment(Qt.AlignCenter)
# form.setAlignment(Qt.AlignHCenter)

self.layout = QVBoxLayout()
# self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.layout.addWidget(self.text)
self.layout.addWidget(form)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
</code>```

答:
I do not see the relationship between the code provided by the OP and the LOGIN window from which you want to copy the structure, so create the following code from scratch.

from PySide2 import QtCore, QtGui, QtWidgets

class LoginPage(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.image_label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.login_label = QtWidgets.QLabel(
            text=self.tr("LOG IN"), alignment=QtCore.Qt.AlignCenter
        )
        self.email_username_lineedit = QtWidgets.QLineEdit(
            placeholderText=self.tr("Email or username")
        )
        self.password_lineedit = QtWidgets.QLineEdit(
            placeholderText=self.tr("Password"), echoMode=QtWidgets.QLineEdit.Password
        )
        self.enter_button = QtWidgets.QPushButton(self.tr("Enter"))
        self.forgot_password_label = QtWidgets.QLabel(
            self.tr("Forgot password?"), alignment=QtCore.Qt.AlignCenter
        )

        self.image_label.setPixmap(QtGui.QPixmap("so-icon.png"))

        # font = self.
        font = self.login_label.font()
        font.setPointSize(30)
        self.login_label.setFont(font)

        self.login_label.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed
        )
        self.forgot_password_label.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed
        )

        lay = QtWidgets.QVBoxLayout(self)
        lay.setSpacing(0)
        lay.addWidget(self.image_label)
        lay.addWidget(self.login_label)
        lay.addWidget(self.email_username_lineedit)
        lay.addWidget(self.password_lineedit)
        lay.addWidget(self.enter_button)
        lay.addWidget(self.forgot_password_label)

        self.resize(320, 480)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = LoginPage()
    w.show()
    sys.exit(app.exec_())
```

Body:
I'm trying to create Login Window, which has QLineEdit below QLabel, but the current QLabel taking too many space in Window, i don't know why, here is the picture :

QLabel { background-color: red; }

My Code :

self.text = QLabel("LOGIN")

# self.text.setStyleSheet("QLabel { background-color: red; color : white;margin-top: 50px;margin-bottom: 0px; }")
self.text.setAlignment(Qt.AlignCenter)
# self.text.setContentsMargins(0, 0, 0, 0)
# self.text.setGeometry(QRect(10,10,30,80))

font = QFont("Sans-Serif", 30)
self.text.setFont(font)

form = QLineEdit("Write my name here..")
form.setAlignment(Qt.AlignCenter)
# form.setAlignment(Qt.AlignHCenter)

self.layout = QVBoxLayout()
# self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.layout.addWidget(self.text)
self.layout.addWidget(form)
self.layout.addWidget(self.button)
self.setLayout(self.layout)


问:
Force Install-Module to always install to user folders
I want to force PowerShell to always install Modules into user space. Weirdly, Microsoft have a facility to force installation to System folders requiring Admin with Install-Module <Name> -Scope AllUser but do not have a way to force installation to user folders.

```<code>$ModulePath = "$(Split-Path $Profile)\Modules"   # Want all modules here.
$ModulePathTest = foreach ($i in ($env:PSModulePath).split(";")) { if ($i -like $ModulePath) { $True } }   # $ModulePathTest will be $true if $ModulePath is on the $env:PSModulePath
if ($ModulePathTest -eq $null) { <do stuff> }
</code>```

So I got this far and now stuck. If I am logged on Admin, I think it installs by default to C:\Program Files and if as a normal user, it will go to $ModulePath.

• Is there a quick way to add $ModulePath to $env:PSModulePath (and permanently, so I think this means it must be pushed into the registry right? I do not see a PowerShell command that can permanently update an environment variable - if I am wrong, would be good to know)?

• Is there a way that someone can think of to make Install-Module always install into $ModulePath in the above (i.e. C:\Users\<Username>\Documents\WindowsPowerShell\Modules)?

答:
Why not simply set the preference globally.

About Parameters Default Values

Short description Describes how to set custom default values for
  cmdlet parameters and advanced functions.

Long description The $PSDefaultParameterValues preference variable
  lets you specify custom default values for any cmdlet or advanced
  function. Cmdlets and advanced functions use the custom default value
  unless you specify another value in the command.

Syntax The $PSDefaultParameterValues variable is a hash table that
  validates the format of keys as an object type of
  System.Management.Automation.DefaultParameterDictionary. The hash
  table contains Key/Value pairs. A Key is in the format
  CmdletName:ParameterName. A Value is the DefaultValue or ScriptBlock
  assigned to the key.

The syntax of the $PSDefaultParameterValues preference variable is as
  follows:

```<code>$PSDefaultParameterValues=@{"CmdletName:ParameterName"="DefaultValue"}
$PSDefaultParameterValues=@{ "CmdletName:ParameterName"={{ScriptBlock}} }
$PSDefaultParameterValues["Disabled"]=$True | $False
</code>```

Using $PSDefaultParameterValues in PowerShell

Let’s say we want to make sure that we do not accidently stop any
  processes using Stop-Process. We can force WhatIf to always be used
  with Stop-Process to better protect ourselves:

```<code>$PSDefaultParameterValues.Add("Stop-Process:WhatIf",$True)
</code>```

So, for what you are after,  ...

What’s in your PowerShell $PSDefaultParameterValues Preference Variable?

```<code>$PSDefaultParameterValues = @{
    'Out-Default:OutVariable' = 'LastResult'
    'Out-File:Encoding' = 'utf8'
    'Export-Csv:NoTypeInformation' = $true
    'ConvertTo-Csv:NoTypeInformation' = $true
    'Receive-Job:Keep' = $true
    'Install-Module:Scope' = 'CurrentUser'
    'Install-Module:AllowClobber' = $true
    'Install-Module:Force' = $true
    'Install-Module:SkipPublisherCheck' = $true
}
</code>```

Body:
I want to force PowerShell to always install Modules into user space. Weirdly, Microsoft have a facility to force installation to System folders requiring Admin with Install-Module <Name> -Scope AllUser but do not have a way to force installation to user folders.

$ModulePath = "$(Split-Path $Profile)\Modules"   # Want all modules here.
$ModulePathTest = foreach ($i in ($env:PSModulePath).split(";")) { if ($i -like $ModulePath) { $True } }   # $ModulePathTest will be $true if $ModulePath is on the $env:PSModulePath
if ($ModulePathTest -eq $null) { <do stuff> }

So I got this far and now stuck. If I am logged on Admin, I think it installs by default to C:\Program Files and if as a normal user, it will go to $ModulePath.

• Is there a quick way to add $ModulePath to $env:PSModulePath (and permanently, so I think this means it must be pushed into the registry right? I do not see a PowerShell command that can permanently update an environment variable - if I am wrong, would be good to know)?

• Is there a way that someone can think of to make Install-Module always install into $ModulePath in the above (i.e. C:\Users\<Username>\Documents\WindowsPowerShell\Modules)?

Body:
Why not simply set the preference globally.

About Parameters Default Values

Short description Describes how to set custom default values for
  cmdlet parameters and advanced functions.

Long description The $PSDefaultParameterValues preference variable
  lets you specify custom default values for any cmdlet or advanced
  function. Cmdlets and advanced functions use the custom default value
  unless you specify another value in the command.

Syntax The $PSDefaultParameterValues variable is a hash table that
  validates the format of keys as an object type of
  System.Management.Automation.DefaultParameterDictionary. The hash
  table contains Key/Value pairs. A Key is in the format
  CmdletName:ParameterName. A Value is the DefaultValue or ScriptBlock
  assigned to the key.

The syntax of the $PSDefaultParameterValues preference variable is as
  follows:

$PSDefaultParameterValues=@{"CmdletName:ParameterName"="DefaultValue"}
$PSDefaultParameterValues=@{ "CmdletName:ParameterName"={{ScriptBlock}} }
$PSDefaultParameterValues["Disabled"]=$True | $False

Using $PSDefaultParameterValues in PowerShell

Let’s say we want to make sure that we do not accidently stop any
  processes using Stop-Process. We can force WhatIf to always be used
  with Stop-Process to better protect ourselves:

$PSDefaultParameterValues.Add("Stop-Process:WhatIf",$True)

So, for what you are after,  ...

What’s in your PowerShell $PSDefaultParameterValues Preference Variable?

$PSDefaultParameterValues = @{
    'Out-Default:OutVariable' = 'LastResult'
    'Out-File:Encoding' = 'utf8'
    'Export-Csv:NoTypeInformation' = $true
    'ConvertTo-Csv:NoTypeInformation' = $true
    'Receive-Job:Keep' = $true
    'Install-Module:Scope' = 'CurrentUser'
    'Install-Module:AllowClobber' = $true
    'Install-Module:Force' = $true
    'Install-Module:SkipPublisherCheck' = $true
}


问:
Mysql finding count of previous date of occurences for each record
I have a table to store id, sid with a date time.
id is used as primary key and no meaning in data.
sid is used to identify entity.

eg.

```<code>id  sid     date
--------------------
1   1    2020-01-12
2   2    2020-01-01
3   1    2019-12-31
4   2    2019-12-31
5   1    2019-12-31
6   1    2019-11-01
7   3    2019-11-01
8   3    2018-12-21
9   2    2018-12-21
</code>```

Then I would like to query for each record, count occurrences in the same table with the previous date of current date, and with the same sid, like:

```<code>id  sid  date       previous_count
----------------------------------
1    1  2020-01-12      2
2    2  2020-01-01      1
3    1  2019-12-31      1
4    2  2019-12-31      1
5    1  2019-12-31      1
6    1  2019-11-01      0
7    3  2019-11-01      1
8    3  2018-12-21      0
9    2  2018-12-21      0
</code>```

Explanation:
for row 1, since sid 1 has two records in 2019-12-31, which is the previous date of 2020-01-12 for sid 1 in the table, it has 2 in previous_count;

while in row 2, since sid 2 has only 1 record in 2019-12-31, which is the previous date of 2020-01-01 for sid 2, it has 1 in previous_count.
Thanks

答:
Your are looking for dense_rank() - 1:

```<code>select t.*,
       (dense_rank() over (partition by sid order by date) - 1) as previous_count
from t
order by id;
</code>```

In older versions of MySQL, you could use variables or a correlated subquery:

```<code>select t.*,
       (select count(distinct t2.date)
        from t t2
        where t2.sid = t.sid and t2.date < t.date
       ) as previous_count
from t
order by id;
</code>```

EDIT:

Ahh, I think I may have misunderstood the problem.  I think this does what you want:

```<code>select t.*, lag(cnt, 1, 0) over (partition by sid order by date)
from (select t.*,
             count(*) over (partition by sid, date) as cnt
      from t
     ) t
order by id;
</code>```

Here is a db<>fiddle.

Body:
I have a table to store id, sid with a date time.
id is used as primary key and no meaning in data.
sid is used to identify entity.

eg.

id  sid     date
--------------------
1   1    2020-01-12
2   2    2020-01-01
3   1    2019-12-31
4   2    2019-12-31
5   1    2019-12-31
6   1    2019-11-01
7   3    2019-11-01
8   3    2018-12-21
9   2    2018-12-21

Then I would like to query for each record, count occurrences in the same table with the previous date of current date, and with the same sid, like:

id  sid  date       previous_count
----------------------------------
1    1  2020-01-12      2
2    2  2020-01-01      1
3    1  2019-12-31      1
4    2  2019-12-31      1
5    1  2019-12-31      1
6    1  2019-11-01      0
7    3  2019-11-01      1
8    3  2018-12-21      0
9    2  2018-12-21      0

Explanation:
for row 1, since sid 1 has two records in 2019-12-31, which is the previous date of 2020-01-12 for sid 1 in the table, it has 2 in previous_count;

while in row 2, since sid 2 has only 1 record in 2019-12-31, which is the previous date of 2020-01-01 for sid 2, it has 1 in previous_count.
Thanks

Body:
Your are looking for dense_rank() - 1:

select t.*,
       (dense_rank() over (partition by sid order by date) - 1) as previous_count
from t
order by id;

In older versions of MySQL, you could use variables or a correlated subquery:

select t.*,
       (select count(distinct t2.date)
        from t t2
        where t2.sid = t.sid and t2.date < t.date
       ) as previous_count
from t
order by id;

EDIT:

Ahh, I think I may have misunderstood the problem.  I think this does what you want:

select t.*, lag(cnt, 1, 0) over (partition by sid order by date)
from (select t.*,
             count(*) over (partition by sid, date) as cnt
      from t
     ) t
order by id;

Here is a db<>fiddle.


问:
Getting fancy with Android menu button layouts
I am making an Android game and I would like to have a nice menu.  I have only every used the combination of <LinearLayout> and <ImageView> for placing my buttons, which sets them up in a straight line.  Here are my buttons:

I want to place them as seen below.  Is it possible to place a button like that and still make it click-able?

答: You can also use a OnTouchListern which can be set to any kind of View. </p>


答:
A string literal is const data in C++. You can't assign a pointer-to-const to a pointer-to-non-const without using a typecast, eg:

const wchar_t* arr[3] =
{
    L"str1",
    L"str2",
    L"str3"
};

...->GetIDsOfNames(..., const_cast<LPOLESTR*>(arr), 3, ...);
```

<p>Alternatively:</p>

<pre class="lang-cpp prettyprint-override"><code>wchar_t* arr[3] =
{
    const_cast<wchar_t*>(L"str1"),
    const_cast<wchar_t*>(L"str2"),
    const_cast<wchar_t*>(L"str3")
};

...->GetIDsOfNames(..., arr, 3, ...);
</code>```

Otherwise, you will have to make a copy of the const data into non-const arrays, like M.M.'s answer shows.

Title: In C++, how do you initialize an array of pointers to wchar_t* (resulting in wchar_t**)?

Body:
A string literal is const data in C++. You can't assign a pointer-to-const to a pointer-to-non-const without using a typecast, eg:

const wchar_t* arr[3] =
{
    L"str1",
    L"str2",
    L"str3"
};

...->GetIDsOfNames(..., const_cast<LPOLESTR*>(arr), 3, ...);

Alternatively:

wchar_t* arr[3] =
{
    const_cast<wchar_t*>(L"str1"),
    const_cast<wchar_t*>(L"str2"),
    const_cast<wchar_t*>(L"str3")
};

...->GetIDsOfNames(..., arr, 3, ...);

Otherwise, you will have to make a copy of the const data into non-const arrays, like M.M.'s answer shows.


问:
Parallelizing attribute assignment objects within a numpy array using python
I'm looking for a way to parallelize attribute assignments to objects within a numpy array using python. In the example below, I update the attribute (attribute) of each ExampleObject within objects, given a numpy array of the same size of objects containing new attribute values for each object.

```<code>import numpy as np
import math
import random

class ExampleObject():

    def __init__(self):
        self.attribute = random.random()

rows, columns = (5, 5)
objects = np.empty((rows, columns), dtype=object)
objects.flat = [ExampleObject() for _ in objects.flat]
attributes = np.zeros((rows, columns))
attributes = np.vectorize(lambda x: x.attribute)(objects)
new_attributes = np.random.rand(rows, columns)

for i in range(rows):
    for j in range(columns):
        objects[i][j].attribute = new_attributes[i][j]
</code>```

I know this can be accomplished using two for loops, and I have included code to do this above, however, I can't find a way to parallelize this code. I have tried to use multiprocessing, however, it appears to be unable to pickle my code.

答:
np.frompyfunc seems to handiest and fastest tool for manipulating custom class object arrays.  It can be twice as fast as a list comprehension (not that big of gain), and handles broadcasting.

Your class with a small enhancement:

```<code>In [418]: class Foo():
     ...:     def __init__(self, val):
     ...:         self.attribute = val
     ...:     def __repr__(self):
     ...:         return f'<Foo> {self.attribute}'
     ...:
In [419]: Foo(1)
Out[419]: <Foo> 1
</code>```

Simple list comprehension - not a bad way to go:

```<code>In [420]: alist = [Foo(i) for i in range(5)]
In [421]: alist
Out[421]: [<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4]
In [422]: arr = np.array(alist)
In [423]: arr
Out[423]: array([<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4], dtype=object)
</code>```

equivalent with frompyfunc.  I defined __init__ to take an argument, so I could pass a value to it.  That can be changed:

```<code>In [424]: arr = np.frompyfunc(Foo,1,1)(range(5))
In [425]: arr
Out[425]: array([<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4], dtype=object)
</code>```

Fetching values:

```<code>In [426]: np.frompyfunc(lambda f: f.attribute,1,1)(arr)
Out[426]: array([0, 1, 2, 3, 4], dtype=object)
</code>```

Modifying values (can't do that with a lambda):

```<code>In [427]: def setfoo(foo, val):
     ...:     foo.attribute = val
     ...:
In [428]: np.frompyfunc(setfoo,2,0)
Out[428]: <ufunc '? (vectorized)'>
In [429]: _(arr, [10,np.ones((3,2)),np.arange(3),None, 'foobar'])
Out[429]: ()
In [430]: arr
Out[430]:
array([<Foo> 10, <Foo> [[1. 1.]
 [1. 1.]
 [1. 1.]], <Foo> [0 1 2],
       <Foo> None, <Foo> foobar], dtype=object)
</code>```

A 2d array creation:

```<code>In [432]: M = np.frompyfunc(lambda i,j: Foo((i,j)), 2,1)(*np.ix_([1,2,3],[10,20]))
In [433]: M
Out[433]:
array([[<Foo> (1, 10), <Foo> (1, 20)],
       [<Foo> (2, 10), <Foo> (2, 20)],
       [<Foo> (3, 10), <Foo> (3, 20)]], dtype=object)
</code>```

Body:
I'm looking for a way to parallelize attribute assignments to objects within a numpy array using python. In the example below, I update the attribute (attribute) of each ExampleObject within objects, given a numpy array of the same size of objects containing new attribute values for each object.

import numpy as np
import math
import random

class ExampleObject():

    def __init__(self):
        self.attribute = random.random()

rows, columns = (5, 5)
objects = np.empty((rows, columns), dtype=object)
objects.flat = [ExampleObject() for _ in objects.flat]
attributes = np.zeros((rows, columns))
attributes = np.vectorize(lambda x: x.attribute)(objects)
new_attributes = np.random.rand(rows, columns)

for i in range(rows):
    for j in range(columns):
        objects[i][j].attribute = new_attributes[i][j]

I know this can be accomplished using two for loops, and I have included code to do this above, however, I can't find a way to parallelize this code. I have tried to use multiprocessing, however, it appears to be unable to pickle my code.

Body:
np.frompyfunc seems to handiest and fastest tool for manipulating custom class object arrays.  It can be twice as fast as a list comprehension (not that big of gain), and handles broadcasting.

Your class with a small enhancement:

In [418]: class Foo():
     ...:     def __init__(self, val):
     ...:         self.attribute = val
     ...:     def __repr__(self):
     ...:         return f'<Foo> {self.attribute}'
     ...:
In [419]: Foo(1)
Out[419]: <Foo> 1

Simple list comprehension - not a bad way to go:

In [420]: alist = [Foo(i) for i in range(5)]
In [421]: alist
Out[421]: [<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4]
In [422]: arr = np.array(alist)
In [423]: arr
Out[423]: array([<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4], dtype=object)

equivalent with frompyfunc.  I defined __init__ to take an argument, so I could pass a value to it.  That can be changed:

In [424]: arr = np.frompyfunc(Foo,1,1)(range(5))
In [425]: arr
Out[425]: array([<Foo> 0, <Foo> 1, <Foo> 2, <Foo> 3, <Foo> 4], dtype=object)

Fetching values:

In [426]: np.frompyfunc(lambda f: f.attribute,1,1)(arr)
Out[426]: array([0, 1, 2, 3, 4], dtype=object)

Modifying values (can't do that with a lambda):

In [427]: def setfoo(foo, val):
     ...:     foo.attribute = val
     ...:
In [428]: np.frompyfunc(setfoo,2,0)
Out[428]: <ufunc '? (vectorized)'>
In [429]: _(arr, [10,np.ones((3,2)),np.arange(3),None, 'foobar'])
Out[429]: ()
In [430]: arr
Out[430]:
array([<Foo> 10, <Foo> [[1. 1.]
 [1. 1.]
 [1. 1.]], <Foo> [0 1 2],
       <Foo> None, <Foo> foobar], dtype=object)

A 2d array creation:

In [432]: M = np.frompyfunc(lambda i,j: Foo((i,j)), 2,1)(*np.ix_([1,2,3],[10,20]))
In [433]: M
Out[433]:
array([[<Foo> (1, 10), <Foo> (1, 20)],
       [<Foo> (2, 10), <Foo> (2, 20)],
       [<Foo> (3, 10), <Foo> (3, 20)]], dtype=object)


问:
How can we use SDA or SCL lines for I2C Addresses?
TMP102 chip( http://www.ti.com/lit/ds/symlink/tmp102.pdf ) can have multiple I2c slave addresses. It has an address pin called ADD0(Section 5) which can be used to select multiple addresses(Section 7.3.4). The logic level at that pin can be used to select a particular TMP102 slave device. According to table 4, 4 addresses are possible. I do understand that connecting the pin to high or low voltage will produce two different addresses. But the table mentions that we can use SDA and SCL pins for two different addresses. I am not sure how this works. Can anyone explain how can this be used and how can we use multiple TMP102 devices based on SDA and SCL pins.

答: You connect ADD0 to SDA/SCL to get those other addresses. The table shows the address you get based on what ADD0 is connected to.</p>


问:
How to show the output of 'l' in python pdb after every command entered
I would like to have the output of the python pdb 'l' command printed to the screen after every command I enter in an interactive debugging session.

Is there a way to setup python pdb to do this?

答:
';;' allow to separate commands</p>

```
<code>
[crchemist@test tmp]$ python t.py
> /home/crchemist/tmp/t.py(7)()
-> a()
(Pdb) p a ;; l
function a at 0xb7e96df4
  2         b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7  -> a() [EOF]
(Pdb) s ;; l
--Call--
> /home/crchemist/tmp/t.py(1)a()
-> def a():
  1  -> def a():
  2         b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7     a() [EOF]
(Pdb) s ;; l
> /home/crchemist/tmp/t.py(2)a()
-> b = 49 + 45
  1     def a():
  2  ->     b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7     a() [EOF]
(Pdb)
</code>
```

OwnerDisplayName: Paul D. Eden

ContentLicense: CC BY-SA 2.5

Body:
';;' allow to separate commands

[crchemist@test tmp]$ python t.py
> /home/crchemist/tmp/t.py(7)()
-> a()
(Pdb) p a ;; l
function a at 0xb7e96df4
  2         b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7  -> a() [EOF]
(Pdb) s ;; l
--Call--
> /home/crchemist/tmp/t.py(1)a()
-> def a():
  1  -> def a():
  2         b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7     a() [EOF]
(Pdb) s ;; l
> /home/crchemist/tmp/t.py(2)a()
-> b = 49 + 45
  1     def a():
  2  ->     b = 49 + 45
  3         v = 'fff'
  4         return v
  5
  6     import pdb; pdb.set_trace()
  7     a() [EOF]
(Pdb)

OwnerDisplayName: Mykola Kharechko


问:
Eclipse & Intellij DE - Unable to connect to mysql database
I followed the instructions of downloading the connector driver (version 8.0.19) of MYSQL database (5.1) and getting connected to eclipse IDE(13 version), but shows the error message as

```<code>java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/employee
at java.sql.DriverManager.getConnection(DriverManager.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:258)
at jdbcdemo.Driver.main(Driver.java:14
</code>```

I first downloaded the driver connector jar file and saved it in the folder.
I tired every possible options in Eclipse and Intellij IDE, but failed to connect.
Do I need to set up anything such as environment variables in advanced system settings under control panel home?

Please could you help me with this connection?

答:
Create a 'lib' folder inside the project folder, and put the Jar file in there. You then need to tell eclipse to include it in your classpath so your code will compile and run inside eclipse.

To do that: - Go into the properties of your project - Select 'Java Build Path' in the left-hand column - select the 'Libraries' tab in the centre part of the window - Click the Add JARs button - this will give you a list of your projects in eclipse - expand your project and into the lib folder - your jar will be there. - Select the JAR, click OK, and OK again out of the properties window.

Or, you can just right-click the jar and click BuildPath->Add to Build Path.

Reference: how to setup JDBC in Eclipse?

Body:
I followed the instructions of downloading the connector driver (version 8.0.19) of MYSQL database (5.1) and getting connected to eclipse IDE(13 version), but shows the error message as

java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/employee
at java.sql.DriverManager.getConnection(DriverManager.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:258)
at jdbcdemo.Driver.main(Driver.java:14

I first downloaded the driver connector jar file and saved it in the folder.
I tired every possible options in Eclipse and Intellij IDE, but failed to connect.
Do I need to set up anything such as environment variables in advanced system settings under control panel home?

Please could you help me with this connection?


问:
List files recursively with folder and file size
I want to share a summary of a directory with file names and sizes in plain text.

This thread shows a file list with human-readable file sizes, e.g. on macOS:

```
$ du -h -d 10
 14G    ./190803 Aaah
 13G    ./190804 (no sound)
```

This post lists a file structure with a nice tree:

```
$ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
.
|____.DS_Store
|____190803 Aaah
| |____190803 Aaah.mp4
| |____DSC_0011.MOV
| |____DSC_0012.MOV
| |____DSC_0013.MOV
| |____DSC_0014.MOV
| |____DSC_0015.MOV
| |____DSC_0016.MOV
|____190804 (no sound)
| |_____DSC0018.MOV
| |_____DSC0019.MOV
| |_____DSC0020.MOV
| |_____DSC0021.MOV
| |_____DSC0022.MOV
| |_____DSC0023.MOV
| |____DSC_0017.MOV
```

How can I combine both and show the human-readable file size next to each item, file or folder, in the latter tree display?

答:
Try this:

```<code>find . -print0 |
  xargs -0 -I% du -h "%" |
  awk ' {
      size = $1
      $1 = ""
      print $0, "(" size ")" }
  ' |
  sed -e 's;[^/]*/;|____;g;s;____|; |;g'
</code>```

If you want the file sizes up in the front of the line, you can try this instead:

```<code>find . -print0 | xargs -0 -I% du -h "%" | awk ' { size = $1 ; $1 = ""; print $0, size }' | sed -e 's;[^/]*/;|____;g;s;____|; |;g' | awk ' {size=$NF ; $NF=""; printf("(%5s) %s\n", size, $0) }'
</code>```

The print0 and -0 deals with cases filepaths with quotes, as in Getting error "xargs unterminated quote" when tried to print the number of lines in terminal .

Body:
I want to share a summary of a directory with file names and sizes in plain text.

This thread shows a file list with human-readable file sizes, e.g. on macOS:

$ du -h -d 10
 14G    ./190803 Aaah
 13G    ./190804 (no sound)

This post lists a file structure with a nice tree:

$ find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
.
|____.DS_Store
|____190803 Aaah
| |____190803 Aaah.mp4
| |____DSC_0011.MOV
| |____DSC_0012.MOV
| |____DSC_0013.MOV
| |____DSC_0014.MOV
| |____DSC_0015.MOV
| |____DSC_0016.MOV
|____190804 (no sound)
| |_____DSC0018.MOV
| |_____DSC0019.MOV
| |_____DSC0020.MOV
| |_____DSC0021.MOV
| |_____DSC0022.MOV
| |_____DSC0023.MOV
| |____DSC_0017.MOV

How can I combine both and show the human-readable file size next to each item, file or folder, in the latter tree display?

Body:
Try this:

find . -print0 |
  xargs -0 -I% du -h "%" |
  awk ' {
      size = $1
      $1 = ""
      print $0, "(" size ")" }
  ' |
  sed -e 's;[^/]*/;|____;g;s;____|; |;g'

If you want the file sizes up in the front of the line, you can try this instead:

find . -print0 | xargs -0 -I% du -h "%" | awk ' { size = $1 ; $1 = ""; print $0, size }' | sed -e 's;[^/]*/;|____;g;s;____|; |;g' | awk ' {size=$NF ; $NF=""; printf("(%5s) %s\n", size, $0) }'

The print0 and -0 deals with cases filepaths with quotes, as in Getting error "xargs unterminated quote" when tried to print the number of lines in terminal .


问:
How can I change the sizes of overlapping circles using JavaScript and the canvas arc() Method?
I was able to stub out a static image using the canvas arch() method, and I have a for loop, but I'm stuck on why the for loop doesn't subtract from the circle variable down to number selected. I'm stuck on how create a for loop that would make the circles change size and appropriately alternate color as a user moves the slider.

//Canvas constants
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 200;

//Slider
let slider = document.getElementById("myRange");
let bandWidth = document.getElementById("bandWidth");

bandWidth.innerHTML = slider.value;

slider.oninput = function() {
bandWidth.innerHTML = this.value;
// console.log(this.value);
let input = this.value;
let circle = radius;

  for(input; input <= circle; circle -= input){
    //console.log(circle);
    //I don't know why the loop does work correctly above 30...
    }
  }

//Figure out how to get the below in a for loop...
//Stubbed out what circles would look like at 25.
// the first circle has a band with of 25
//first circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Second circle
ctx.beginPath();
ctx.arc(centerX, centerY, 175, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Third Circle
ctx.beginPath();
ctx.arc(centerX, centerY, 150, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Fourth Circle
ctx.beginPath();
ctx.arc(centerX, centerY, 125, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Fifth
ctx.beginPath();
ctx.arc(centerX, centerY, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Sixth
ctx.beginPath();
ctx.arc(centerX, centerY, 75, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Seventh
ctx.beginPath();
ctx.arc(centerX, centerY, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Eigth
ctx.beginPath();
ctx.arc(centerX, centerY, 25, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BullsEye</title>
</head>
<body>
  <canvas id="myCanvas" width="400" height="400" style="border: 2px solid black"></canvas>
  <br>
  <div>BandWidth:</div>
  <!--Slider input-->
  <!--onChnage will update the bandwith value-->
  <input type="range" id="myRange" value="25" min="5" max="50" step="5">

  <p>Current BandWith:
    <span id="bandWidth"></span>
  </p>

  <script src="bullsEye.js"></script>
</body>
</html></code>```

答:
Your code seems to work fine with some minor corrections.

I've introduced an additional variable i in the loop to keep track of the current iteration and alternate between colors.

//Canvas constants
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 200;

//Slider
let slider = document.getElementById("myRange");
let bandWidth = document.getElementById("bandWidth");

bandWidth.innerHTML = slider.value;

function draw() {
  bandWidth.innerHTML = this.value;
  // console.log(this.value);
  let input = this.value;
  let circle = radius;
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  for(let i = 0; input <= circle; circle -= input, i++){
    // console.log(circle);
    ctx.beginPath();
    ctx.arc(centerX, centerY, circle, 0, 2 * Math.PI, false);
    ctx.fillStyle = i % 2 === 0 ? 'red' : 'blue';
    ctx.fill();
  }
}

slider.oninput = draw;
draw.call(slider);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" width="400" height="400" style="border: 2px solid black"></canvas>
<br>
<div>BandWidth:</div>
<!--Slider input-->
<!--onChnage will update the bandwith value-->
<input type="range" id="myRange" value="25" min="5" max="50" step="5">

<p>Current BandWith:
  <span id="bandWidth"></span>
</p></code>```

Body:
I was able to stub out a static image using the canvas arch() method, and I have a for loop, but I'm stuck on why the for loop doesn't subtract from the circle variable down to number selected. I'm stuck on how create a for loop that would make the circles change size and appropriately alternate color as a user moves the slider.

//Canvas constants
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 200;

//Slider
let slider = document.getElementById("myRange");
let bandWidth = document.getElementById("bandWidth");

bandWidth.innerHTML = slider.value;

slider.oninput = function() {
bandWidth.innerHTML = this.value;
// console.log(this.value);
let input = this.value;
let circle = radius;

  for(input; input <= circle; circle -= input){
    //console.log(circle);
    //I don't know why the loop does work correctly above 30...
    }
  }

//Figure out how to get the below in a for loop...
//Stubbed out what circles would look like at 25.
// the first circle has a band with of 25
//first circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Second circle
ctx.beginPath();
ctx.arc(centerX, centerY, 175, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Third Circle
ctx.beginPath();
ctx.arc(centerX, centerY, 150, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Fourth Circle
ctx.beginPath();
ctx.arc(centerX, centerY, 125, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Fifth
ctx.beginPath();
ctx.arc(centerX, centerY, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Sixth
ctx.beginPath();
ctx.arc(centerX, centerY, 75, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

//Seventh
ctx.beginPath();
ctx.arc(centerX, centerY, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();

//Eigth
ctx.beginPath();
ctx.arc(centerX, centerY, 25, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();

<!DOCTYPE html>

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

  <canvas id="myCanvas" width="400" height="400" style="border: 2px solid black"></canvas>

BandWidth:

  <input type="range" id="myRange" value="25" min="5" max="50" step="5">

Current BandWith:

Body:
Your code seems to work fine with some minor corrections.

I've introduced an additional variable i in the loop to keep track of the current iteration and alternate between colors.

//Canvas constants
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 200;

//Slider
let slider = document.getElementById("myRange");
let bandWidth = document.getElementById("bandWidth");

bandWidth.innerHTML = slider.value;

function draw() {
  bandWidth.innerHTML = this.value;
  // console.log(this.value);
  let input = this.value;
  let circle = radius;
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  for(let i = 0; input <= circle; circle -= input, i++){
    // console.log(circle);
    ctx.beginPath();
    ctx.arc(centerX, centerY, circle, 0, 2 * Math.PI, false);
    ctx.fillStyle = i % 2 === 0 ? 'red' : 'blue';
    ctx.fill();
  }
}

slider.oninput = draw;
draw.call(slider);

<canvas id="myCanvas" width="400" height="400" style="border: 2px solid black"></canvas>
<br>
<div>BandWidth:</div>
<!--Slider input-->
<!--onChnage will update the bandwith value-->
<input type="range" id="myRange" value="25" min="5" max="50" step="5">

<p>Current BandWith:
  <span id="bandWidth"></span>
</p>


问:
How to know if an image is created using OpenCV in Python?
I'm in a situation where I need to identify different kinds of input, including files, folders, images, etc. In case of images, I need to specifically know if an image is created using OpenCV (for the fact that it may be BGR), or any other types of images.

I noticed images created using skimage.io.imread, matplotlib.pyplot.imread, and opencvs cv2.imread(), are all numpy.ndarray, and there is no way I can distinguish between them.

I tried to use opencv's cv2.cvtColor(img, cv2.COLOR_BGR2RGB) on the input image, hoping the non-opencv images would cause an exception and thus I can identify if the image is opencvs or not.

Unfortunately only PIL, images fail this this and both matplotlibs and skimages run just fine (they change from RGB to BGR so thats not good either).

I tried to find the underlying dtype, but they are all the same(uint8).
I tried to find an attribute specific to opencv so others cant have it, so by querying that attribute, I may be able to know if that's an opencv image to no avail!

I only receive an object from the input and in case of images, there is no way of knowing in advance, what was the source of the sent image (was it read using opencv? should I use the conversion to RGB, or else, you get the idea and down the pipeline, each input has its own set of operations to execute.

Update:

Using type(), I can distinguish between all images except matplotlibs and opencvs. I cant seem to find a way to distiguish between these two!

答:
TLDR:

In order to distinguish between openCV and Matplotlib (and also Skimage) which all are represented as ndarrays, one can query base or flags attributes.

Long explanation:

Based on further investigation, I found out that the objects created using Matplotlib and openCV differ at several places which can be used to distinuish between them.

The base and flags attributes are only two of such attributes one can use to find which is which.

Among all of these methods, only openCV's base attribute is None.

Therefore one can utilize this to infer whether he/she is dealing with an image created using openCV's imread or Matplotlibs imread.

Concerning flags attrbiute, only OpenCV owns the data, here are different flags for opencv, Matplotlib and also Skimage:

In [48]: img_cv.flags
Out[48]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

In [49]: img_mtplotlib.flags
Out[49]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : False
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

In [50]: img_skimage.flags
Out[50]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

```

<p>So simply by checking the <code>OWNDATA</code>, one can decide if an image is comming form <code>opencv</code> end! :</p>

<pre class="lang-py prettyprint-override"><code>if s.flags['OWNDATA'] == True :
    print('opencv'):
else :
    ....
</code>```

based on these facts, other attributes such as itemset() are readonly on Matplotlib side and trying to set any value will result in a ValueError exception.

second TLDR:

so based on ones need, one can use type, or these attributes to achieve whats needed here.

Important note :

as @DanMašek rightfully pointed out, if the object is deepcopied, the flags and base are not reliable any more, as the OWNDATA and WRITEABLE fields will be True.

Body:
TLDR:

In order to distinguish between openCV and Matplotlib (and also Skimage) which all are represented as ndarrays, one can query base or flags attributes.

Long explanation:

Based on further investigation, I found out that the objects created using Matplotlib and openCV differ at several places which can be used to distinuish between them.

The base and flags attributes are only two of such attributes one can use to find which is which.

Among all of these methods, only openCV's base attribute is None.

Therefore one can utilize this to infer whether he/she is dealing with an image created using openCV's imread or Matplotlibs imread.

Concerning flags attrbiute, only OpenCV owns the data, here are different flags for opencv, Matplotlib and also Skimage:

In [48]: img_cv.flags
Out[48]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

In [49]: img_mtplotlib.flags
Out[49]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : False
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

In [50]: img_skimage.flags
Out[50]:
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

So simply by checking the OWNDATA, one can decide if an image is comming form opencv end! :

if s.flags['OWNDATA'] == True :
    print('opencv'):
else :
    ....

based on these facts, other attributes such as itemset() are readonly on Matplotlib side and trying to set any value will result in a ValueError exception.

second TLDR:

so based on ones need, one can use type, or these attributes to achieve whats needed here.

Important note :

as @DanMašek rightfully pointed out, if the object is deepcopied, the flags and base are not reliable any more, as the OWNDATA and WRITEABLE fields will be True.


问:
Social networking integration with OAuth in iPhone
I am new to iPhone programming.

Can someone please explain me what is OAuth and how it can be used in social networking integration?

How many social networking sites provide an API?

答: Use - ShareKit</p>

Body: Use - ShareKit


问:
Getting Undefined Method "Error" in Rails
I am creating a survey tool with Rails. I am trying to set up validation for the Answer where the participant has to submit an answer that is longer than 5 characters. I am getting the following error when I try to add a new answer.

undefined method `errors'

I have read in other posts that it is likely to be caused because you haven't initialised the answer object in the answers controller. My problem with this is that I have - it just doesn't look like this:

```<code>def new
  @answer = Answer.new
end
</code>```

It looks like this in my code:

```<code>  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end
</code>```

This is the code for my Answer Model:

```<code>class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :answer, presence: true,
            length: { minimum: 5 }
end

</code>```

And this is the full error that I am getting in my server:

```<code>Started GET "/studies/32/questions/63/answers/new" for ::1 at 2020-02-18 10:14:41 +1300
   (2.1ms)  SELECT sqlite_version(*)
Processing by AnswersController#new as HTML
  Parameters: {"study_id"=>"32", "question_id"=>"63"}
  Study Load (1.1ms)  SELECT "studies".* FROM "studies" WHERE "studies"."id" = ? LIMIT ?  [["id", 32], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:3:in `new'
  Question Load (1.5ms)  SELECT "questions".* FROM "questions" WHERE "questions"."study_id" = ? AND "questions"."id" = ? LIMIT ?  [["study_id", 32], ["id", 63], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:4:in `new'
   (0.5ms)  begin transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Participant Create (4.5ms)  INSERT INTO "participants" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2020-02-17 21:14:45.571329"], ["updated_at", "2020-02-17 21:14:45.571329"]]
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
   (3.0ms)  commit transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Rendering answers/new.html.erb within layouts/application
  Answer Load (1.5ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ?  [["question_id", 63]]
  Rendered answers/new.html.erb within layouts/application (Duration: 1228.1ms | Allocations: 13885323)
Completed 500 Internal Server Error in 4106ms (ActiveRecord: 12.0ms | Allocations: 37401284)

ActionView::Template::Error (undefined method `errors' for #<Answer::ActiveRecord_Associations_CollectionProxy:0x00007fae2e5792f0>):
    4:   <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    5:     <%= form.hidden_field :participant_id %>
    6:
    7:     <% if @question.answers.errors.any? %>
    8:
    9:
   10:     <% end %>
</code>```

This is my first rails project and I'm not sure what I'm missing - can anyone help me out here?

Thanks

答:
The issue is that @question.answers is a collection of multiple objects.  You can't just call .errors on that.  You will have to either loop through the objects and call errors on each,

```<code><% @question.answers.each do |answer| %>
  <% if answer.errors.any? %>

  <% end %>
<% end %>
</code>```

or, what I think you want to do from looking at the view file, is call that on the specific @answer variable for the form.

```<code><% if @answer.errors.any? %>
</code>```

Body:
I am creating a survey tool with Rails. I am trying to set up validation for the Answer where the participant has to submit an answer that is longer than 5 characters. I am getting the following error when I try to add a new answer.

undefined method `errors'

I have read in other posts that it is likely to be caused because you haven't initialised the answer object in the answers controller. My problem with this is that I have - it just doesn't look like this:

def new
  @answer = Answer.new
end

It looks like this in my code:

  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

This is the code for my Answer Model:

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :answer, presence: true,
            length: { minimum: 5 }
end

And this is the full error that I am getting in my server:

Started GET "/studies/32/questions/63/answers/new" for ::1 at 2020-02-18 10:14:41 +1300
   (2.1ms)  SELECT sqlite_version(*)
Processing by AnswersController#new as HTML
  Parameters: {"study_id"=>"32", "question_id"=>"63"}
  Study Load (1.1ms)  SELECT "studies".* FROM "studies" WHERE "studies"."id" = ? LIMIT ?  [["id", 32], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:3:in `new'
  Question Load (1.5ms)  SELECT "questions".* FROM "questions" WHERE "questions"."study_id" = ? AND "questions"."id" = ? LIMIT ?  [["study_id", 32], ["id", 63], ["LIMIT", 1]]
  ↳ app/controllers/answers_controller.rb:4:in `new'
   (0.5ms)  begin transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Participant Create (4.5ms)  INSERT INTO "participants" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2020-02-17 21:14:45.571329"], ["updated_at", "2020-02-17 21:14:45.571329"]]
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
   (3.0ms)  commit transaction
  ↳ app/controllers/answers_controller.rb:33:in `find_participant'
  Rendering answers/new.html.erb within layouts/application
  Answer Load (1.5ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ?  [["question_id", 63]]
  Rendered answers/new.html.erb within layouts/application (Duration: 1228.1ms | Allocations: 13885323)
Completed 500 Internal Server Error in 4106ms (ActiveRecord: 12.0ms | Allocations: 37401284)

ActionView::Template::Error (undefined method `errors' for #<Answer::ActiveRecord_Associations_CollectionProxy:0x00007fae2e5792f0>):
    4:   <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    5:     <%= form.hidden_field :participant_id %>
    6:
    7:     <% if @question.answers.errors.any? %>
    8:
    9:
   10:     <% end %>

This is my first rails project and I'm not sure what I'm missing - can anyone help me out here?

Thanks

Body:
The issue is that @question.answers is a collection of multiple objects.  You can't just call .errors on that.  You will have to either loop through the objects and call errors on each,

<% @question.answers.each do |answer| %>
  <% if answer.errors.any? %>

  <% end %>
<% end %>

or, what I think you want to do from looking at the view file, is call that on the specific @answer variable for the form.

<% if @answer.errors.any? %>


问:
Why is this F# sequence expression cubic time instead of linear?
I stumbled upon a strange time complexity behaviour when using Seq.unfold. Here's the minimal case I could come up with to reproduce this.

```<code>let idUnfolder sequence =
   sequence
   |> Seq.tryHead
   |> Option.map (fun head -> (head, Seq.tail sequence))

let seqIdWithUnfold sequence =
   Seq.unfold idUnfolder sequence
</code>```

The function seqIdWithUnfold returns the given sequence itself. I would expect the resulting sequence to be iterated in linear time as Seq.unfold is O(n), Seq.tryHead and Seq.tail are O(1) (correct me if I'm wrong). However, against all my knowledge, it has a cubic complexity.

I tested the execution time with the following function with a set of n values.

```<code>let test n =
   let start = System.DateTime.Now
   Seq.init n id
   |> seqIdWithUnfold
   |> Seq.iter ignore
   let duration = System.DateTime.Now - start
   printfn "%f" duration.TotalSeconds
</code>```

What makes this operation cubic in complexity?

答:
As Philip Carter mentioned in the comments Seq.tail is O(n).

I'm not sure why an F# List would be unacceptable, F# Lists are singly linked lists so you can get the constant time tail. If you need to accept any sequence as your signature just convert to a List before unfolding, it still makes it O(n), This example you presented can't be lazy anyway unless you really didn't need the tail.

```<code>let seqIdWithUnfold sequence =
       sequence
           |> Seq.toList
           |> List.unfold idUnfolder
           |> List.toSeq
</code>```

Your processing example still works with the List module

```<code> let idUnfolder listSeq =
        listSeq
        |> List.tryHead
        |> Option.map (fun head -> (head, List.tail listSeq))
</code>```

But I think it would look a bit cleaner as

```<code>let idUnfolder =
    function | [] -> None
             | h::t -> Some(h, t);
</code>```

Benchamarks

```<code>|          Method |        Mean |     Error |    StdDev |
|---------------- |------------:|----------:|----------:|
|        Original | 4,683.88 us | 36.462 us | 34.106 us |
|  ListConversion |    15.63 us |  0.202 us |  0.179 us |

// * Hints *
Outliers
  Benchmarkem.ListConversion: Default -> 1 outlier  was  removed (16.53 us)

// * Legends *
  Mean   : Arithmetic mean of all measurements
  Error  : Half of 99.9% confidence interval
  StdDev : Standard deviation of all measurements
  1 us   : 1 Microsecond (0.000001 sec)
</code>```

Body:
I stumbled upon a strange time complexity behaviour when using Seq.unfold. Here's the minimal case I could come up with to reproduce this.

let idUnfolder sequence =
   sequence
   |> Seq.tryHead
   |> Option.map (fun head -> (head, Seq.tail sequence))

let seqIdWithUnfold sequence =
   Seq.unfold idUnfolder sequence

The function seqIdWithUnfold returns the given sequence itself. I would expect the resulting sequence to be iterated in linear time as Seq.unfold is O(n), Seq.tryHead and Seq.tail are O(1) (correct me if I'm wrong). However, against all my knowledge, it has a cubic complexity.

I tested the execution time with the following function with a set of n values.

let test n =
   let start = System.DateTime.Now
   Seq.init n id
   |> seqIdWithUnfold
   |> Seq.iter ignore
   let duration = System.DateTime.Now - start
   printfn "%f" duration.TotalSeconds

What makes this operation cubic in complexity?

Body:
As Philip Carter mentioned in the comments Seq.tail is O(n).

I'm not sure why an F# List would be unacceptable, F# Lists are singly linked lists so you can get the constant time tail. If you need to accept any sequence as your signature just convert to a List before unfolding, it still makes it O(n), This example you presented can't be lazy anyway unless you really didn't need the tail.

let seqIdWithUnfold sequence =
       sequence
           |> Seq.toList
           |> List.unfold idUnfolder
           |> List.toSeq

Your processing example still works with the List module

 let idUnfolder listSeq =
        listSeq
        |> List.tryHead
        |> Option.map (fun head -> (head, List.tail listSeq))

But I think it would look a bit cleaner as

let idUnfolder =
    function | [] -> None
             | h::t -> Some(h, t);

Benchamarks

|          Method |        Mean |     Error |    StdDev |
|---------------- |------------:|----------:|----------:|
|        Original | 4,683.88 us | 36.462 us | 34.106 us |
|  ListConversion |    15.63 us |  0.202 us |  0.179 us |

// * Hints *
Outliers
  Benchmarkem.ListConversion: Default -> 1 outlier  was  removed (16.53 us)

// * Legends *
  Mean   : Arithmetic mean of all measurements
  Error  : Half of 99.9% confidence interval
  StdDev : Standard deviation of all measurements
  1 us   : 1 Microsecond (0.000001 sec)