问:
How do I hide a button until all elements are clicked in HTML?
I am trying to hide a button until all required elements on the page have been clicked. I found how to hide an element until one item is clicked but not sure how to set this to hide the button until all items are clicked.

The elements I want the users to click on are accordion panels with the ID's as "collaspeone", "collaspetwo" and so on. I want the user to click on each panel (which causes them to expand) then once they have clicked on each panel, show a button on the bottom of the page which allows them to continue to the next page.

Here is the element I want to show only when every panel has been clicked on.

```<code><button id="Continue" class="btn btn-primary"><a href="AddSupplier-SubmitReq.aspx" style="color:white">Continue to Set-Up<i class="fa fa-arrow-right" aria-hidden="true"></i></a></button>
</code>```

Here is my full HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<meta name="WebPartPageExpansion" content="full" />
<meta charset="utf-8"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="canonical" href="http://html5-templates.com/" />
 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/>
 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/>
 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/>
 <link rel="manifest" href="/manifest.json"/>
 <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"/>
 <meta name="theme-color" content="#ffffff"/>
    <title>MySLM Portal</title>
 <meta name="description" content="A minimalist Bootstrap theme by StartBootstrap. Contains everything you need to get started building your website. All you have to do is change the text and images.">
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/modern-business.css" rel="stylesheet"/>
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="css/footer.css" rel="stylesheet" type="text/css"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Scope

                        General Questions

                        FAQ's

                        Processes

                                Create a New Supplier

                                Update an Existing Supplier

                                Reactivate a Supplier

                                Deactivate a Supplier

                        Contact

                        Resources

                                ERS Agreement Library

                                Corp Record List

                                Sanctioned Supplier List

                                Supplier Deactivation Listing

                                RemedyForce Training

                                Select Supplier Search

                                Yammer: Source to Pay NA

                                Job Aids

                                Knowledge/Self Help Articles

                                Policies

Sourcing and Purchasing Policy

Anti-bribery Policy

Bank Account & Payment Control Policy

Competition Policy

Conflicts of Interest Policy

Country Risk Policy

Insider Trading Policy

Legal Services Policy

Supplier Code of Conduct

Trade Sanctions Policy

United states & Canada Purchasing Cards Procedure

                        Links

                                Ariba

                                P2P Business Stakeholder Library

                                RemedyForce

                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Wait! Make Your Job Easier!

Source through CSSP!

By sourcing through CSSP you can avoid having to navigate the entire complex supplier setup process and focus on your job while CSSP works for you in the background sourcing you a supplier and having them set-up in the appropriate ERP system for your use!

                 <button class="btn btn-primary">Lets go!  </button>

                  <button type="button" class="btn btn-default" data-dismiss="modal">No, I do not want to make my job easier</button>

Set-up a New Supplier
                    First Steps

The following steps should be completed by the requester prior to submitting a request to set-up a new supplier. Failure to perform these steps may result in rejection of, or delays on your request.

                        1

                    Panel Title

Panel Body

                        2

                    Panel Title

Panel Body

                        3

                    Panel Title

Panel Body

                        4

                    Panel Title

Panel Body

                        5

                    Panel Title

Panel Body

        <button id="Continue" class="btn btn-primary hidden disabled">Continue to Set-Up</button>

Questions? Check out our FAQ's

                    Go to FAQ's!

                            Code of Conduct

                            Supplier Code of Conduct

                            Policy Center

© 2017 Cargill, Incorporated. All Rights Reserved

```

答:
The easiest way I can think of is to keep track of the clicked elements.
If the array you're keeping track of is the same length as the number of elements to click, display the nutton.

$(function(){

  // an array to keep track of the clicked elements
  var clicked = [];

  $('.panel').click(function(e){

    // only add them if they are not already clicked before
    if(!clicked.includes(event.target.id)){
     clicked.push(event.target.id);

      // once the clicked elements array is the same length as all the
    // elements that need to be clicked, display the button
    if(clicked.length === $('.panel').length){
     $('#theButton').show();
    };
    }

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.panel{
  float: left;
  width: 30px;
  height: 20px;
  border: 1px solid black;
}

.hidden{
  display: none;
}</code>```

1

2

3

4

<button id="theButton" class="hidden">move on</button>```

Body:
I am trying to hide a button until all required elements on the page have been clicked. I found how to hide an element until one item is clicked but not sure how to set this to hide the button until all items are clicked.

The elements I want the users to click on are accordion panels with the ID's as "collaspeone", "collaspetwo" and so on. I want the user to click on each panel (which causes them to expand) then once they have clicked on each panel, show a button on the bottom of the page which allows them to continue to the next page.

Here is the element I want to show only when every panel has been clicked on.

<button id="Continue" class="btn btn-primary">Continue to Set-Up</button>

Here is my full HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ Page Language="C#" %>
<%@ Register tagprefix="SharePoint" namespace="Microsoft.SharePoint.WebControls" assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<meta name="WebPartPageExpansion" content="full" />
<meta charset="utf-8"/>
    <meta http-equiv="x-ua-compatible" content="ie=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link rel="canonical" href="http://html5-templates.com/" />
 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/>
 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"/>
 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"/>
 <link rel="manifest" href="/manifest.json"/>
 <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"/>
 <meta name="theme-color" content="#ffffff"/>
    <title>MySLM Portal</title>
 <meta name="description" content="A minimalist Bootstrap theme by StartBootstrap. Contains everything you need to get started building your website. All you have to do is change the text and images.">
    <link href="css/bootstrap.min.css" rel="stylesheet"/>
    <link href="css/modern-business.css" rel="stylesheet"/>
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
    <link href="css/footer.css" rel="stylesheet" type="text/css"/>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Scope

                        General Questions

                        FAQ's

                        Processes

                                Create a New Supplier

                                Update an Existing Supplier

                                Reactivate a Supplier

                                Deactivate a Supplier

                        Contact

                        Resources

                                ERS Agreement Library

                                Corp Record List

                                Sanctioned Supplier List

                                Supplier Deactivation Listing

                                RemedyForce Training

                                Select Supplier Search

                                Yammer: Source to Pay NA

                                Job Aids

                                Knowledge/Self Help Articles

                                Policies

Sourcing and Purchasing Policy

Anti-bribery Policy

Bank Account & Payment Control Policy

Competition Policy

Conflicts of Interest Policy

Country Risk Policy

Insider Trading Policy

Legal Services Policy

Supplier Code of Conduct

Trade Sanctions Policy

United states & Canada Purchasing Cards Procedure

                        Links

                                Ariba

                                P2P Business Stakeholder Library

                                RemedyForce

                 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Wait! Make Your Job Easier!

Source through CSSP!

By sourcing through CSSP you can avoid having to navigate the entire complex supplier setup process and focus on your job while CSSP works for you in the background sourcing you a supplier and having them set-up in the appropriate ERP system for your use!

                 <button class="btn btn-primary">Lets go!  </button>

                  <button type="button" class="btn btn-default" data-dismiss="modal">No, I do not want to make my job easier</button>

Set-up a New Supplier
                    First Steps

The following steps should be completed by the requester prior to submitting a request to set-up a new supplier. Failure to perform these steps may result in rejection of, or delays on your request.

                        1

                    Panel Title

Panel Body

                        2

                    Panel Title

Panel Body

                        3

                    Panel Title

Panel Body

                        4

                    Panel Title

Panel Body

                        5

                    Panel Title

Panel Body

        <button id="Continue" class="btn btn-primary hidden disabled">Continue to Set-Up</button>

Questions? Check out our FAQ's

                    Go to FAQ's!

                            Code of Conduct

                            Supplier Code of Conduct

                            Policy Center

© 2017 Cargill, Incorporated. All Rights Reserved

Body:
The easiest way I can think of is to keep track of the clicked elements.
If the array you're keeping track of is the same length as the number of elements to click, display the nutton.

$(function(){

  // an array to keep track of the clicked elements
  var clicked = [];

  $('.panel').click(function(e){

    // only add them if they are not already clicked before
    if(!clicked.includes(event.target.id)){
     clicked.push(event.target.id);

      // once the clicked elements array is the same length as all the
    // elements that need to be clicked, display the button
    if(clicked.length === $('.panel').length){
     $('#theButton').show();
    };
    }

  });

});

.panel{
  float: left;
  width: 30px;
  height: 20px;
  border: 1px solid black;
}

.hidden{
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p1" class="panel">1</div>
<div id="p2" class="panel">2</div>
<div id="p3" class="panel">3</div>
<div id="p4" class="panel">4</div>
<button id="theButton" class="hidden">move on</button>


来源: stackexchange

问:
How to delete a global variable from inside a function?
I have a global variable ser which I need to delete under certain circumstances:

```<code>global ser
ser = ['some', 'stuff']

def reset_ser():
    print('deleting serial configuration...')
    del ser
</code>```

If I call reset_ser() I get the error:

```<code>UnboundLocalError: local variable 'ser' referenced before assignment
</code>```

If I give the global variable to the function as an input I do not get the error, but the variable does not get deleted (I guess only inside the function itself). Is there a way of deleting the variable, or do I e.g.have to overwrite it to get rid of its contents?

答:
Just use global ser inside the function:

```<code>ser = "foo"
def reset_ser():
    global ser
    del ser

print(ser)
reset_ser()
print(ser)
</code>```

Output:

```<code>foo
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(ser)
NameError: name 'ser' is not defined
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a global variable ser which I need to delete under certain circumstances:

global ser
ser = ['some', 'stuff']

def reset_ser():
    print('deleting serial configuration...')
    del ser

If I call reset_ser() I get the error:

UnboundLocalError: local variable 'ser' referenced before assignment

If I give the global variable to the function as an input I do not get the error, but the variable does not get deleted (I guess only inside the function itself). Is there a way of deleting the variable, or do I e.g.have to overwrite it to get rid of its contents?

Body:
Just use global ser inside the function:

ser = "foo"
def reset_ser():
    global ser
    del ser

print(ser)
reset_ser()
print(ser)

Output:

foo
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(ser)
NameError: name 'ser' is not defined


问:
Convert UTC datetime string to local datetime
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

```<code>datetime.utcfromtimestamp(timestamp)
</code>```

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

```<code>"2011-01-21 02:37:21"
</code>```

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

答:
If you don't want to provide your own tzinfo objects, check out the python-dateutil library.  It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

```<code>from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)
</code>```

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)

ContentLicense: CC BY-SA 4.0

Body:
I've never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I've been running myself in circles. Lots of information on converting local time to UTC, which I found fairly elementary (maybe I'm doing that wrong as well), but I can not find any information on easily converting the UTC time to the end-users timezone.

In a nutshell, and android app sends me (appengine app) data and within that data is a timestamp. To store that timestamp to utc time I am using:

datetime.utcfromtimestamp(timestamp)

That seems to be working. When my app stores the data, it is being store as 5 hours ahead (I am EST -5)

The data is being stored on appengine's BigTable, and when retrieved it comes out as a string like so:

"2011-01-21 02:37:21"

How do I convert this string to a DateTime in the users correct time zone?

Also, what is the recommended storage for a users timezone information?  (How do you typically store tz info ie: "-5:00" or "EST" etc etc ?) I'm sure the answer to my first question might contain a parameter the answers the second.

Body:
If you don't want to provide your own tzinfo objects, check out the python-dateutil library.  It provides tzinfo implementations on top of a zoneinfo (Olson) database such that you can refer to time zone rules by a somewhat canonical name.

from datetime import datetime
from dateutil import tz

# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
central = utc.astimezone(to_zone)

Edit Expanded example to show strptime usage

Edit 2 Fixed API usage to show better entry point method

Edit 3 Included auto-detect methods for timezones (Yarin)


问:
Create column based on condition in SQLite
I am trying to create a new column in a SQLite database from Python. I would like the column to be either 1 or 0 if a criteria is met. I have tried the following without success:

```<code>query = 'SELECT codes CASE WHEN codes LIKE 'X10' THEN 1 ELSE 0 END as I10X FROM processed_data'

cur.execute(query)
</code>```

Example data:

```<code>+--------------+
| codes   |    |
+--------------+
| X10, X11|    |
| x11, X9 |    |
| x10     |    |
| x13     |    |
+-------+------+
</code>```

Example target data:

```<code>+----------+-----+
| codes    | X10 |
+----------+-----+
| X10, X11 |   1 |
| x11, X9  |   0 |
| x10      |   0 |
| x13      |   0 |
| x10      |   1 |
+-------+--------+
</code>```

Can anyone suggest how to do this?

答:
Just to get the result you asked, without actually creating a column, use</p>

```<code>select *, codes like 'x10' from codes;
</code>```

Body:
I am trying to create a new column in a SQLite database from Python. I would like the column to be either 1 or 0 if a criteria is met. I have tried the following without success:

query = 'SELECT codes CASE WHEN codes LIKE 'X10' THEN 1 ELSE 0 END as I10X FROM processed_data'

cur.execute(query)

Example data:

+--------------+
| codes   |    |
+--------------+
| X10, X11|    |
| x11, X9 |    |
| x10     |    |
| x13     |    |
+-------+------+

Example target data:

+----------+-----+
| codes    | X10 |
+----------+-----+
| X10, X11 |   1 |
| x11, X9  |   0 |
| x10      |   0 |
| x13      |   0 |
| x10      |   1 |
+-------+--------+

Can anyone suggest how to do this?

Body:
Just to get the result you asked, without actually creating a column, use

select *, codes like 'x10' from codes;


问:
Plot time series as one year
I have a time series of monthly data for 10 years:

```<code>myts <- ts(rnorm(12*10), frequency = 12, start = 2001)
</code>```

Now, I'd like to plot the data but with the x-axis restricted to a range/ticks from Jan - Dec (generic year). Thus, the whole time series should be broken in ten lines where each line starts at Jan and ends at Dec. So multiple lines should be overplotted each other which I'd like to use to visually compare different years. Is there a straight forward command to do that in R?

So far I came up with following solution using matplot which might not be the most sophisticated one:

```<code>mydf <- as.data.frame(matrix(myts, 12))
matplot(mydf,type="l")
</code>```

Or even better would be a way to calculate an average value and the corresponding CI/standard deviation for each month and plot then the average from Jan - Dec as a line and the corresponding CI/standard deviation as a band around the line for the average.

答:
Consider using ggplot2.

```<code>library(ggplot2)
library(ggfortify)
d <- fortify(myts)
d$year <- format(d$Index, "%Y")
d$month <- format(d$Index, "%m")
</code>```

It's useful to start by reshaping the ts object into a long dataframe.  Given the dataframe, it's straightforward to create the plots you have in mind:

```<code>ggplot(d, aes(x = month, y = Data, group = year, colour = year)) +
  geom_line()

ggplot(d, aes(x = month, y = Data, group = month)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult = 1.96))
</code>```

Result:

You can also summarise the data yourself, then plot it:

```<code>d_sum <- do.call(rbind, (lapply(split(d$Data, d$month), mean_se, mult = 1.96)))
d_sum$month <- rownames(d_sum)
ggplot(d_sum, aes(x = month, y = y, ymin = ymin, ymax = ymax)) +
  geom_errorbar() +
  geom_point() +
  geom_line(aes(x = as.numeric(month)))
</code>```

Result:

Title: Plot time series as one year

Body:
I have a time series of monthly data for 10 years:

myts <- ts(rnorm(12*10), frequency = 12, start = 2001)

Now, I'd like to plot the data but with the x-axis restricted to a range/ticks from Jan - Dec (generic year). Thus, the whole time series should be broken in ten lines where each line starts at Jan and ends at Dec. So multiple lines should be overplotted each other which I'd like to use to visually compare different years. Is there a straight forward command to do that in R?

So far I came up with following solution using matplot which might not be the most sophisticated one:

mydf <- as.data.frame(matrix(myts, 12))
matplot(mydf,type="l")

Or even better would be a way to calculate an average value and the corresponding CI/standard deviation for each month and plot then the average from Jan - Dec as a line and the corresponding CI/standard deviation as a band around the line for the average.

Body:
Consider using ggplot2.

library(ggplot2)
library(ggfortify)
d <- fortify(myts)
d$year <- format(d$Index, "%Y")
d$month <- format(d$Index, "%m")

It's useful to start by reshaping the ts object into a long dataframe.  Given the dataframe, it's straightforward to create the plots you have in mind:

ggplot(d, aes(x = month, y = Data, group = year, colour = year)) +
  geom_line()

ggplot(d, aes(x = month, y = Data, group = month)) +
  stat_summary(fun.data = mean_se, fun.args = list(mult = 1.96))

Result:

You can also summarise the data yourself, then plot it:

d_sum <- do.call(rbind, (lapply(split(d$Data, d$month), mean_se, mult = 1.96)))
d_sum$month <- rownames(d_sum)
ggplot(d_sum, aes(x = month, y = y, ymin = ymin, ymax = ymax)) +
  geom_errorbar() +
  geom_point() +
  geom_line(aes(x = as.numeric(month)))

Result:


问:
How to stop the sound/audio when you press the back button in the phone
how can i stop the audio from playing when i press the back button in my phone. when i go to another activity the audio is still playing unless i close the app. here's my code:</p>

```<code>    FloatingActionButton fab7 = (FloatingActionButton) this.findViewById(R.id.fab7);
    final MediaPlayer mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {;

            if(mp.isPlaying()){
                mp.pause();
            } else {
                mp.start();
            }

        }
    });
</code>```

答:
Use this to detect and pause the Mediaplayer</p>

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
    Log.d(this.getClass().getName(), "Back button pressed Song paused");
    mp.pause();

}
return super.onKeyDown(keyCode, event);
}
</code>```

Body:
how can i stop the audio from playing when i press the back button in my phone. when i go to another activity the audio is still playing unless i close the app. here's my code:

    FloatingActionButton fab7 = (FloatingActionButton) this.findViewById(R.id.fab7);
    final MediaPlayer mp = MediaPlayer.create( this, R.raw.cebu);
    fab7.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {;

            if(mp.isPlaying()){
                mp.pause();
            } else {
                mp.start();
            }

        }
    });

Body:
Use this to detect and pause the Mediaplayer

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
    Log.d(this.getClass().getName(), "Back button pressed Song paused");
    mp.pause();

}
return super.onKeyDown(keyCode, event);
}


答:
You first need to alter your processed_data table to add the X10 column, and then you can update the X10 field based on the codes field. For example:

```<code>cursor = connection.cursor()  # fetch a cursor from your SQLite connection

# let's first check if we already have the X10 column in our table
x10_exists = False
cursor.execute("PRAGMA table_info(processed_data)")  # get info on the table
for column in cursor:
    if column[1] == 'X10':
        x10_exists = True
        break
if not x10_exists:  # if X10 doesn't exist...
    cursor.execute("ALTER TABLE processed_data ADD COLUMN X10")  # add the X10 column

cursor.execute('''
    UPDATE processed_data
    SET X10=CASE
        WHEN codes LIKE 'X10' THEN 1
        ELSE 0
    END
''')  # update the values

db.commit()  # commit the transaction
</code>```

Title: Create column based on condition in SQLite

Body:
You first need to alter your processed_data table to add the X10 column, and then you can update the X10 field based on the codes field. For example:

cursor = connection.cursor()  # fetch a cursor from your SQLite connection

# let's first check if we already have the X10 column in our table
x10_exists = False
cursor.execute("PRAGMA table_info(processed_data)")  # get info on the table
for column in cursor:
    if column[1] == 'X10':
        x10_exists = True
        break
if not x10_exists:  # if X10 doesn't exist...
    cursor.execute("ALTER TABLE processed_data ADD COLUMN X10")  # add the X10 column

cursor.execute('''
    UPDATE processed_data
    SET X10=CASE
        WHEN codes LIKE 'X10' THEN 1
        ELSE 0
    END
''')  # update the values

db.commit()  # commit the transaction


问:
spring boot jar NoSuchBeanDefinitionException
I builded spring boot application which works well if I start it with mvn spring-boot:run but trying to run it java -jar jarName.jar results in error Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'HomeService' available

here is my pom.xml with spring-boot-maven-plugin like it is described here https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html and here Spring-Boot Executable-Jar NoSuchBeanDefinitionException

```<code>    <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
        <resource>
            <directory>src/main/resources/${profileName}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-proc:none</compilerArgument>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.bsc.maven</groupId>
            <artifactId>maven-processor-plugin</artifactId>
            <version>2.2.4</version>
            <executions>
                <execution>
                    <id>process</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>
                        <!-- source output directory -->
                        <outputDirectory>target/metamodel</outputDirectory>
                        <!-- <processors> -->
                        <!-- <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor> -->
                        <!-- </processors> -->
                        <overwrite>true</overwrite>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.8.RELEASE</version>
            <configuration>
                <executable>true</executable>
                <profiles>
                    <profile>dev</profile>
                    <profile>live</profile>
                </profiles>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>live</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <delete file="src/main/resources/application.properties" />
                                    <copy file="src/main/resources/application-live.properties"
                                        tofile="src/main/resources/application.properties" />
                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>dev</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <delete file="src/main/resources/application.properties" />
                                    <copy file="src/main/resources/application-dev.properties"
                                        tofile="src/main/resources/application.properties" />
                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</code>```

here is App class

```<code>@Configuration
@EnableAutoConfiguration
@ComponentScan (basePackages = { "myProject.status" })
public class App {

private static final Logger logger = LogManager.getLogger(App.class);

public static void main(String[] args) throws BeansException, IOException, InterruptedException {
    logger.info("APPLICATION STARTED");

    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
    logger.info(context.getBean(HomeService.class).home());

}
</code>```

here is HomeService

```<code>package myProject.status.service;
@Service
public class HomeService {

    public String home() {
        return "application works";
    }
}
</code>```

I tried also to get a bean in @PostConstruct method, where everything and all Autowires should be ready, it also does not work.

What is the difference between mvn spring-boot:run and mvn package ? How could I build correct jar?

Thanks!

答:
You can just use $ mvn package spring-boot:repackage to build a standalone executable jar.

The difference between mvn spring-boot:run and mvn spring-boot:repackage is that spring-boot:run for local run and debug, while spring-boot:repackage is to package for deployment.

Also, you need to specify <packaging>jar</packaging>.

Another comment for App.java, you can just use one annotation as @SpringBootApplication. It would cover all your three annotations, assuming App.java is in Package myProject.status.

Body:
I builded spring boot application which works well if I start it with mvn spring-boot:run but trying to run it java -jar jarName.jar results in error Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'HomeService' available

here is my pom.xml with spring-boot-maven-plugin like it is described here https://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html and here Spring-Boot Executable-Jar NoSuchBeanDefinitionException

    <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
        <resource>
            <directory>src/main/resources/${profileName}</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-proc:none</compilerArgument>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.bsc.maven</groupId>
            <artifactId>maven-processor-plugin</artifactId>
            <version>2.2.4</version>
            <executions>
                <execution>
                    <id>process</id>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>

                        <outputDirectory>target/metamodel</outputDirectory>

                        <overwrite>true</overwrite>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.5.8.RELEASE</version>
            <configuration>
                <executable>true</executable>
                <profiles>
                    <profile>dev</profile>
                    <profile>live</profile>
                </profiles>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

<profiles>
    <profile>
        <id>live</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <delete file="src/main/resources/application.properties" />
                                    <copy file="src/main/resources/application-live.properties"
                                        tofile="src/main/resources/application.properties" />
                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>dev</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                            <configuration>
                                <tasks>
                                    <delete file="src/main/resources/application.properties" />
                                    <copy file="src/main/resources/application-dev.properties"
                                        tofile="src/main/resources/application.properties" />
                                </tasks>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

here is App class

@Configuration
@EnableAutoConfiguration
@ComponentScan (basePackages = { "myProject.status" })
public class App {

private static final Logger logger = LogManager.getLogger(App.class);

public static void main(String[] args) throws BeansException, IOException, InterruptedException {
    logger.info("APPLICATION STARTED");

    ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
    logger.info(context.getBean(HomeService.class).home());

}

here is HomeService

package myProject.status.service;
@Service
public class HomeService {

    public String home() {
        return "application works";
    }
}

I tried also to get a bean in @PostConstruct method, where everything and all Autowires should be ready, it also does not work.

What is the difference between mvn spring-boot:run and mvn package ? How could I build correct jar?

Thanks!


问:
api yandex maps on different pages of wordpress site
I have 4 pages in wordpress site where i need to inculde api yandex maps. So i created 4 scripts, which works. I included script tags in my footer:

```<code>        <!-- Yandex map scripts -->
    <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="application/javascript"></script>
    <script src="/wp-content/themes/bla" type="application/javascript"></script>
    <script src="/wp-content/themes/blabla" type="application/javascript"></script>
    <script src="/wp-content/themes/blablabla" type="application/javascript"></script>
    <script src="/wp-content/themes/blablablabla" type="application/javascript"></script>
</code>```

All scripts have different ids for div blocks, different variable names.
But when i put my divs inside 4 pages, only the first script is working, in this example i will see map only on the page that contains this script

```<code><script src="/wp-content/themes/bla" type="application/javascript"></script>
</code>```

Other pages will be blank.

In browser it looks like this, so script is not working

If i load all 4 maps on 1 page it is working. But i want each map on certain page.

What should i do to get things work?

Body:
I have 4 pages in wordpress site where i need to inculde api yandex maps. So i created 4 scripts, which works. I included script tags in my footer:

All scripts have different ids for div blocks, different variable names.
But when i put my divs inside 4 pages, only the first script is working, in this example i will see map only on the page that contains this script

Other pages will be blank.

In browser it looks like this, so script is not working

If i load all 4 maps on 1 page it is working. But i want each map on certain page.

What should i do to get things work?

Body:
Problem solved.
I guess we have to load yandex json every time.

<!-- Yandex map scripts -->
        <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
        <script src="/wp-content/themes/bbbb" type="application/javascript"></script>
        <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
        <script src="/wp-content/themes/b" type="application/javascript"></script>
        <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
        <script src="/wp-content/themes/bbb" type="application/javascript"></script>
        <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
        <script src="/wp-content/themes/bb" type="application/javascript"></script>
        <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>


问:
Unexpected behaviour when casting time.time() to float32

I want to store an array of epoch time as numpy array of dtype32. I expect to lose accuracy, but not 30 seconds difference!

```<code>np.float64(np.float32((time.time()))) - time.time()
</code>```

Can someone explain what is happening? How can I store epoch time as float32 without losing accuracy?

答:
Seconds since epoch is a big number. Currently, it's about 1.5e9. You get precision errors that are in the 10s at this range.

First off, you're calling time.time() twice, which is exacerbating the time difference---the methods obviously take time to call. The better way to see your error would be to store the time:

```<code>>>> import time
>>> import numpy as np
>>> t = time.time()
>>> np.float32(t) - t
62.610707998275757
</code>```

You can see the actual decimal number stored by getting the string representation from numpy:

```<code>>>> t
1512746305.389292
>>> np.float32(t).astype(str)
'1512746368.0'
</code>```

Remember, a digit is not a bit---just 0s and 1s are bits. In a 32-bit float, you're storing the number in scientific notation, but in binary. This kills the accuracy. The range of values expressible as a 32-bit float is -3.4e38 to +3.4e38. There are 2^32 numbers expressible with 32 bits...so clearly, you're missing a ton of (infinitely many...) possible numbers in the 32-bit float range.

There are two super easy solutions.

First, if you don't care about sub-seconds...then just store it as an integer. Epoch time won't even hit 32-bit max until 2038. (Hello to SO users in 2037 worried about the Year 2038 Problem. Is Wikipedia still a thing?)

```<code>>>> np.int32(t) - t
-0.38929200172424316
</code>```

Of course if you want some more decimal precision...multiply by 10, or 100, or 1000 before casting as an int. Well, you can accumulate errors doing this but with 64-bit floats you should be okay.

The second way to deal with this is to just store a new epoch time, and take the difference with the times you want to save in the array. The error with these smaller numbers will be far into the decimal range.

```<code>>>> new_epoch = time.time()
>>> t = time.time() - new_epoch
>>> np.float32(t) - t
-2.384185791015625e-07
</code>```

Then just save new_epoch in 64-bit glory along with your 32-bit float array of times so you know how to convert back.

However, do note that, from the Python time module docs:

even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.

Also I do highly recommend David Goldberg's famous article What every computer scientist should know about floating-point arithmetic. Even just the first few pages give a great overview on floating-point arithmetic and how to calculate the size of your approximation errors!

Body:
I want to store an array of epoch time as numpy array of dtype32. I expect to lose accuracy, but not 30 seconds difference!

np.float64(np.float32((time.time()))) - time.time()

Can someone explain what is happening? How can I store epoch time as float32 without losing accuracy?

Body:
Seconds since epoch is a big number. Currently, it's about 1.5e9. You get precision errors that are in the 10s at this range.

First off, you're calling time.time() twice, which is exacerbating the time difference---the methods obviously take time to call. The better way to see your error would be to store the time:

>>> import time
>>> import numpy as np
>>> t = time.time()
>>> np.float32(t) - t
62.610707998275757

You can see the actual decimal number stored by getting the string representation from numpy:

>>> t
1512746305.389292
>>> np.float32(t).astype(str)
'1512746368.0'

Remember, a digit is not a bit---just 0s and 1s are bits. In a 32-bit float, you're storing the number in scientific notation, but in binary. This kills the accuracy. The range of values expressible as a 32-bit float is -3.4e38 to +3.4e38. There are 2^32 numbers expressible with 32 bits...so clearly, you're missing a ton of (infinitely many...) possible numbers in the 32-bit float range.

There are two super easy solutions.

First, if you don't care about sub-seconds...then just store it as an integer. Epoch time won't even hit 32-bit max until 2038. (Hello to SO users in 2037 worried about the Year 2038 Problem. Is Wikipedia still a thing?)

>>> np.int32(t) - t
-0.38929200172424316

Of course if you want some more decimal precision...multiply by 10, or 100, or 1000 before casting as an int. Well, you can accumulate errors doing this but with 64-bit floats you should be okay.

The second way to deal with this is to just store a new epoch time, and take the difference with the times you want to save in the array. The error with these smaller numbers will be far into the decimal range.

>>> new_epoch = time.time()
>>> t = time.time() - new_epoch
>>> np.float32(t) - t
-2.384185791015625e-07

Then just save new_epoch in 64-bit glory along with your 32-bit float array of times so you know how to convert back.

However, do note that, from the Python time module docs:

even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.

Also I do highly recommend David Goldberg's famous article What every computer scientist should know about floating-point arithmetic. Even just the first few pages give a great overview on floating-point arithmetic and how to calculate the size of your approximation errors!


问:
How to make EF code first work under `IIS AppPool\MySiteName`?
I am learning MVC 3 from asp.net site.

My MVC 3 application already has been tested under IIS AppPool\MySiteName and it works well.

Using Sql Server Management Studio, I created a new account for IIS AppPool\MySiteName.

I followed this tutorial "creating db on the fly" and I got an error as follows:

```<code>Server Error in '/' Application.
--------------------------------------------------------------------------------

Cannot open database "Movies" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\Getting Started'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
</code>```

答:
The following things is all you should have to do imo:

Create and configure a new AppPool,
say AppPoolFoo, running under the
identity of a local user account,
say User1

Configure your site in IIS to run
under AppPoolFoo

Grant User1 appropriate rights with
SQL Server Management Studio

It's unclear to me whether you followed these steps, or have a different scenario.

ContentLicense: CC BY-SA 2.5

Body:
I am learning MVC 3 from asp.net site.

My MVC 3 application already has been tested under IIS AppPool\MySiteName and it works well.

Using Sql Server Management Studio, I created a new account for IIS AppPool\MySiteName.

I followed this tutorial "creating db on the fly" and I got an error as follows:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Cannot open database "Movies" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\Getting Started'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.


问:
How to serve another repos built files from NodeJS?
I have two repos:

A Vue client interface;

A NodeJS socket and web server.

I need to serve the built files of the Vue interface with the server and don't know how to proceed...

I have two ideas of how to solve this:

Create a script that would clone the Vue repo, build it and move the
builded files in a folder server by the server.

Declare the Vue repo as a dependency of the server and find a way to
build and access to the dependency files.

The second one seems cleaner but I don't know how to begin approaching this. Could someone please provide some thoughts on the better approach and how I might get started?

答:
You've tagged git so I'm going to say use approach 2 but use git sub-modules. You could create some sort of webpack task to build your Vuejs project within the Vuejs repository. Then you can submodule your vuejs repository to the web server / socket project.

You can then use some sort of gulp or webpack script to call into the vuejs project to instruct it to build. Once that is built you can use the express.static function to serve up the build from your web server on whatever route you want (probably just the / route).

With submodules you can simply bump the submodule when you're ready to do a new release of the frontend and then re-deploy the web server with the new version of the dependency. This is how the Ghost project do their frontend deployments.

Git Submodules documentation - https://git-scm.com/book/en/v2/Git-Tools-Submodules.


问:
Props is a deprecated symbol in React with Typescript
I have a problem: My IDE is complaining about deprecation.

I use react 16 and typescript 2.5.3

Following code given:

```<code>import React, { Props, StatelessComponent } from 'react';
import PropTypes from 'prop-types';

interface IProps {
    id: string;
}

const Foo: StatelessComponent<IProps> = (props: IProps) => {
    props.ref = nodeRef;
    return (<div id={props.id}></div>);
};

Foo.propTypes = {
    id: PropTypes.string,
};

Foo.defaultProps = {
    id: 'bar',
};

export default Foo;
</code>```

At this point I am getting at props.ref 'Property ref does not exist on Partial'

When I extend my interface IProps, like this:

```<code>interface IProps extends Props {
    id: string;
}
</code>```

At this point my IDE suggest to add an Generic Type

```<code>interface IProps extends Props<any> {
    id: string;
}
</code>```

Now I get deprecation warning to consult online docs, BUT I do not find anything. BUT my initial error with ref-property is gone.

Now my question: How to deal with this when I use a StatelessComponent? How to deal with it, when Using Component (or is there no error)? And how can I avoid any?

Thanks for helping me

答:
You've accidentally masked the real problem by extending Props<T>! There's a comment in the type definitions explaining why that interface is deprecated:

This was used to allow clients to pass ref and key to createElement, which is no longer necessary due to intersection types.

In other words, you used to have to extend Props<T> for your prop type definitions so that ref/key/children would be included, but new features in TypeScript have made this unnecessary. You can just pass in a plain interface as you were doing initially.

However, this still leaves you with your 'Property ref does not exist' error - this is because you cannot use refs on stateless functional components. The type definitions are actually doing the right thing here and stopping you from writing code that won't work!

Body:
I have a problem: My IDE is complaining about deprecation.

I use react 16 and typescript 2.5.3

Following code given:

import React, { Props, StatelessComponent } from 'react';
import PropTypes from 'prop-types';

interface IProps {
    id: string;
}

const Foo: StatelessComponent<IProps> = (props: IProps) => {
    props.ref = nodeRef;
    return (

);
};

Foo.propTypes = {
    id: PropTypes.string,
};

Foo.defaultProps = {
    id: 'bar',
};

export default Foo;

At this point I am getting at props.ref 'Property ref does not exist on Partial'

When I extend my interface IProps, like this:

interface IProps extends Props {
    id: string;
}

At this point my IDE suggest to add an Generic Type

interface IProps extends Props<any> {
    id: string;
}

Now I get deprecation warning to consult online docs, BUT I do not find anything. BUT my initial error with ref-property is gone.

Now my question: How to deal with this when I use a StatelessComponent? How to deal with it, when Using Component (or is there no error)? And how can I avoid any?

Thanks for helping me


问:
How to Concatenate table name with with a variable value in mySQL
I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :

//that's how I get my variable the value for example is = 3

```<code>$pid = $GLOBALS["localid"];
</code>```

//the table name for example is tablename_3

```<code>$strTable = "tablename_" .$pid;
</code>```

//here's how the query should look like

```<code>$query = "SELECT * FROM . $strTable . where .....;
</code>```

I'm making a mistake somewhere but can't figure it out and would appreciate a little help please

答:
Remove the dots and also make sure you have single quotes aroung where</p>

```<code>$query = "SELECT * FROM $strTable where '.....';
</code>```

Body:
I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :

//that's how I get my variable the value for example is = 3

$pid = $GLOBALS["localid"];

//the table name for example is tablename_3

$strTable = "tablename_" .$pid;

//here's how the query should look like

$query = "SELECT * FROM . $strTable . where .....;

I'm making a mistake somewhere but can't figure it out and would appreciate a little help please

Body:
Remove the dots and also make sure you have single quotes aroung where

$query = "SELECT * FROM $strTable where '.....';


问:
Write efficient update query by joining multiple tables in Oracle
I have a complex requirement to update some records in one table by joining multiple tables to find correct records. I have written the following query which is working but it is taking 2.5 minutes to get executed which is causing my DB connection timeout. Is there a way to improve the efficiency of this query by rewriting it? I have also tried MERGE approach as well which is also taking too long. I have more than 2 million records in EVENT_DYNAMIC_ATTRIBUTE table and 1 million records in EVENT table and 100 thousand records in CATEGORY table.

```<code>UPDATE EVENT_DYNAMIC_ATTRIBUTE eda
SET eda.ATTRIBUTE_VALUE = 'claim',
    eda.LAST_UPDATED_DATE = SYSDATE,
    eda.LAST_UPDATED_BY = 'superUsers'
WHERE eda.DYNAMIC_ATTRIBUTE_NAME_ID=4002
  AND eda.EVENT_ID IN
    (SELECT e.EVENT_ID
     FROM EVENT e
     WHERE e.PRIMARY_CATEGORY_ID IN
         (SELECT CATEGORY_ID
          FROM CATEGORY START WITH CATEGORY_ID = 495984 CONNECT BY PARENT_ID =
          PRIOR CATEGORY_ID));
</code>```

This is the merge query:

```<code> MERGE INTO EVENT_DYNAMIC_ATTRIBUTE eda
    USING (SELECT DISTINCT e.EVENT_ID FROM (
         SELECT CATEGORY_ID
         FROM CATEGORY
         START WITH CATEGORY_ID=495984
         CONNECT BY PARENT_ID =
         PRIOR CATEGORY_ID) CATEGORIES
    INNER JOIN  EVENT E ON e.PRIMARY_CATEGORY_ID = CATEGORY_ID
    INNER JOIN  EVENT_DYNAMIC_ATTRIBUTE ed on ed.EVENT_ID = E.EVENT_ID) temp
    ON (eda.EVENT_ID = temp.EVENT_ID )
    WHEN MATCHED THEN
       UPDATE SET eda.ATTRIBUTE_VALUE = 'claim',
                  eda.LAST_UPDATED_DATE = SYSDATE,
                  eda.LAST_UPDATED_BY = 'superUser'
    WHERE eda.DYNAMIC_ATTRIBUTE_NAME_ID=4002
</code>```

答:
You can try something like

```<code>update
  (
    select
      eda.*
    from
      (select * from event_dynamic_attribute where dynamic_attribute_name_id = 4002) eda,
      (select category_id from category start with category_id = 495984 connect by parent_id = prior category_id) c,
      event e
    where
      e.primary_category_id = c.category_id and
      e.event_id = eda.event_id
  )
set
  attribute_value = 'claim',
  last_updated_date = sysdate,
  last_updated_by = 'superUsers'
</code>```

but I doubt it helps. Generally, that's very very low speed, even if works on old hardware. You should trace these updates and check their execution, affected blocks etc.

First of all, I'd ask you to execute

```<code>explain plan for <<your update statement text>>;
select * from table(dbms_xplan.display());
</code>```

and write it's result into the question. Yet another... is there any triggers on the event_dynamic_attribute table?

Body:
I have a complex requirement to update some records in one table by joining multiple tables to find correct records. I have written the following query which is working but it is taking 2.5 minutes to get executed which is causing my DB connection timeout. Is there a way to improve the efficiency of this query by rewriting it? I have also tried MERGE approach as well which is also taking too long. I have more than 2 million records in EVENT_DYNAMIC_ATTRIBUTE table and 1 million records in EVENT table and 100 thousand records in CATEGORY table.

UPDATE EVENT_DYNAMIC_ATTRIBUTE eda
SET eda.ATTRIBUTE_VALUE = 'claim',
    eda.LAST_UPDATED_DATE = SYSDATE,
    eda.LAST_UPDATED_BY = 'superUsers'
WHERE eda.DYNAMIC_ATTRIBUTE_NAME_ID=4002
  AND eda.EVENT_ID IN
    (SELECT e.EVENT_ID
     FROM EVENT e
     WHERE e.PRIMARY_CATEGORY_ID IN
         (SELECT CATEGORY_ID
          FROM CATEGORY START WITH CATEGORY_ID = 495984 CONNECT BY PARENT_ID =
          PRIOR CATEGORY_ID));

This is the merge query:

 MERGE INTO EVENT_DYNAMIC_ATTRIBUTE eda
    USING (SELECT DISTINCT e.EVENT_ID FROM (
         SELECT CATEGORY_ID
         FROM CATEGORY
         START WITH CATEGORY_ID=495984
         CONNECT BY PARENT_ID =
         PRIOR CATEGORY_ID) CATEGORIES
    INNER JOIN  EVENT E ON e.PRIMARY_CATEGORY_ID = CATEGORY_ID
    INNER JOIN  EVENT_DYNAMIC_ATTRIBUTE ed on ed.EVENT_ID = E.EVENT_ID) temp
    ON (eda.EVENT_ID = temp.EVENT_ID )
    WHEN MATCHED THEN
       UPDATE SET eda.ATTRIBUTE_VALUE = 'claim',
                  eda.LAST_UPDATED_DATE = SYSDATE,
                  eda.LAST_UPDATED_BY = 'superUser'
    WHERE eda.DYNAMIC_ATTRIBUTE_NAME_ID=4002

Body:
You can try something like

update
  (
    select
      eda.*
    from
      (select * from event_dynamic_attribute where dynamic_attribute_name_id = 4002) eda,
      (select category_id from category start with category_id = 495984 connect by parent_id = prior category_id) c,
      event e
    where
      e.primary_category_id = c.category_id and
      e.event_id = eda.event_id
  )
set
  attribute_value = 'claim',
  last_updated_date = sysdate,
  last_updated_by = 'superUsers'

but I doubt it helps. Generally, that's very very low speed, even if works on old hardware. You should trace these updates and check their execution, affected blocks etc.

First of all, I'd ask you to execute

explain plan for <<your update statement text>>;
select * from table(dbms_xplan.display());

and write it's result into the question. Yet another... is there any triggers on the event_dynamic_attribute table?


问:
How to add a window to a specific node in Write window of CANoe

How can I a write window to a specific node in CANoe configuration? I can see a write window for node SSC EV but I wanted to add another one more for a node.

答:
first of all take a look in CANoe manual

CANoe» Analysis Windows » Write Window

here you will find important note about limitations for lines in Write-Window.
Thereafter you can find short explanation about standard pages in Write-Window here:

Write Window » Views

There is also a link to CAPL function writeCreate() which can be used to create new page. The return value of this function shall be used as parameter for function writeConfigure() to write onto created page. See also example for this functions in help.


问:
Django Queryset - Sort alphabetical then move specific entries to top

Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

```<code>class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)
</code>```

I'm now attempting to use this class like:

```<code>calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )
</code>```

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

```<code>group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)
</code>```

Which just raises the error:

```<code>DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements
</code>```

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

```<code>total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")
</code>```

Which raises error:

```<code>SyntaxError: positional argument follows keyword argument
</code>```

Edit

Following rajkris' suggestion of using itertools I tried:

```<code>total_list = list(chain(group_members, everyone_else))
</code>```

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

```<code>total_qs = User.objects.filter(username__in=total_list)
</code>```

But this only got me an unsorted list with all users mixed together without any ordering.

答:
Could you try something like this?    </p>

```<code>group_members = User.objects.order_by("first_name", "last_name")
sorted_group_members = sorted(group_members.all(), reverse=True, key = lambda a: a.some_function_returning_the_user_group_of_each_user())
</code>```

Body:
Edit (Background info)

I've created a custom UserModelChoiceField class that takes a QuerySet of users and populates a select field with their full names:

class UserModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return "{} ({})".format(obj.get_full_name(), obj.username)

I'm now attempting to use this class like:

calibrated_by_internal = UserModelChoiceField(
                                              queryset=total_qs,
                                              required=False,
                                              widget=forms.Select(attrs={"class": "form-control"})
                                              )

.

Original Question

I'm trying to create a custom sorted QuerySet that will allow me to put a User ModelChoice select field on a form that is sorted alphabetically, but 3 members of a particular permissions group are put at the top.

For example:

Members of the group:
Charlie, Alan, Brian

Not members of the group:
Ben, Chris, Alicia... etc.

Required QuerySet / Select Field ordering:
Alan, Brian, Charlie, Alicia, Ben, Chris... etc.

Given that I'm using Django 1.11 I thought I'd try the new .union ORM function:

group_members = User.objects.filter(groups__name="AddEditCalibrations").order_by("first_name", "last_name")
everyone_else = User.objects.exclude(username__in="group_members").order_by("first_name", "last_name")
total_qs = group_members.union(everyone_else)

Which just raises the error:

DATABASE ERROR - ORDER BY not allowed in subqueries of compound statements

It seems to work OK without the 2 ORDER_BYs, but then the list isn't sorted alphabetically and the members of that group that need to be at the top of the select (first in the QS) are just mixed in with everyone else.

So I tried the even simpler:

total_qs = User.objects.order_by(groups__name="AddEditCalibrations", "first_name", "last_name")

Which raises error:

SyntaxError: positional argument follows keyword argument

Edit

Following rajkris' suggestion of using itertools I tried:

total_list = list(chain(group_members, everyone_else))

Given that I need a QS to populate the select field I then tried to convert it back to a QS with:

total_qs = User.objects.filter(username__in=total_list)

But this only got me an unsorted list with all users mixed together without any ordering.

Body:
Could you try something like this?

group_members = User.objects.order_by("first_name", "last_name")
sorted_group_members = sorted(group_members.all(), reverse=True, key = lambda a: a.some_function_returning_the_user_group_of_each_user())


问:
How to run cmd through LabView that will stop or start a Windows service?
I need to start or stop a Windows servicy through LabVIEW. In order to do that, i need to run cmd as  administrator. Actually I didn't know how to run cmd as an admin through LabVIEW so I created another cmd by way described here (OPTION TWO). After that I need to type "net start SERVICE_NAME" or "net stop SERVICE_NAME", but I dont know how to programmatically run one of those commands . How can I do that?

Thank you

答:
I would use System Exec.vi. Instead of following option two in your link for a command window shortcut, follow those same instructions for your LabVIEW executable (or for your development environment if you are not making an executable). Thus, whenever you access System Exec.vi in your program, it inherits admin privileges.

Here is some more reading on System Exec.vi


答:
write mediaplayer.stop();
on start of back activity when u gone </p>

Title: How to stop the sound/audio when you press the back button in the phone


问:
To update a template, must all registrations be updated?
I can register a device with a template. If I want to update the template for all devices, do I need to update every registration?

In other words, can I register a template in one place and only update that?

答: You can upload or generate Automation script and add to library and later use this template.enter image description here</p>


问:
How to stop repo:push if webhooks condition fails in BitBucket
I'm trying to stop the repo push in Bitbucket if the commit statement doesn't have the defined Jira issue id in the remark.
I have successfully invoked the URL for checking the commit remark via webhooks but unable to figure out the way to stop the push in case of failure.</p>

答:
Customise the following script from this example of a msg-commit git hook.

```<code>#!/bin/bash

MSG="$1"

if ! grep -qE "updated" "$MSG";then
    cat "$MSG"
    echo "Your commit message must contain the word 'updated'"
    exit 1
fi
</code>```

Check this code into git, and then run

```<code># give the script "execute" permission
chmod 755 commit-msg
# put the script in the correct place
cp commit-msg .git/hooks/commit-msg
</code>```

If you try and create a commit without the word 'updated' in the message, then this hook will prevent the commit from being created successfully.

Source: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer. If this script exits non-zero, Git aborts the commit process, so you can use it to validate your project state or commit message before allowing a commit to go through. In the last section of this chapter, We’ll demonstrate using this hook to check that your commit message is conformant to a required pattern.

Note that anyone else who clones your repository will also need to copy the hook into .git/hooks/commit-msg

Body:
Customise the following script from this example of a msg-commit git hook.

#!/bin/bash

MSG="$1"

if ! grep -qE "updated" "$MSG";then
    cat "$MSG"
    echo "Your commit message must contain the word 'updated'"
    exit 1
fi

Check this code into git, and then run

# give the script "execute" permission
chmod 755 commit-msg
# put the script in the correct place
cp commit-msg .git/hooks/commit-msg

If you try and create a commit without the word 'updated' in the message, then this hook will prevent the commit from being created successfully.

Source: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

The commit-msg hook takes one parameter, which again is the path to a temporary file that contains the commit message written by the developer. If this script exits non-zero, Git aborts the commit process, so you can use it to validate your project state or commit message before allowing a commit to go through. In the last section of this chapter, We’ll demonstrate using this hook to check that your commit message is conformant to a required pattern.

Note that anyone else who clones your repository will also need to copy the hook into .git/hooks/commit-msg


问:
PHP read .DBF file in script
I have a large DBF file that I would simply like to read like a .csv or .txt file by converting it into an array.

```<code>$file = file_get_contents('data.dbf');
</code>```

Doing this just imports it as one huge blob of text. I tried

explode("\n\r", $file);

but that doesn't seem to work either as it treats it like one giant string with no line breaks. Excel btw reads it perfectly.

I don't have the dbase extension installed (not even sure if I can do that easily). Is there any other way I can read it properly line-by-line?

答:
It's better to use dBase PECL-extension for DBF-files, it allows you to read them properly and separate fields into array.

If you still want to use file() take into account a note from manual:

If PHP is not properly recognizing the line endings when reading files
  either on or created by a Macintosh computer, enabling the
  auto_detect_line_endings run-time configuration option may help
  resolve the problem.

Title: PHP read .DBF file in script

Body:
I have a large DBF file that I would simply like to read like a .csv or .txt file by converting it into an array.

$file = file_get_contents('data.dbf');

Doing this just imports it as one huge blob of text. I tried

explode("\n\r", $file);

but that doesn't seem to work either as it treats it like one giant string with no line breaks. Excel btw reads it perfectly.

I don't have the dbase extension installed (not even sure if I can do that easily). Is there any other way I can read it properly line-by-line?