问:
How to select table colums using wildcards
Having a SQLite table with a column containing names:

```<code>Names

ThingA_1
ThingF_1
ThingF_2
ThingB_1
ThingB_2
ThingB_3
ThingB_4
</code>```

I would like to remove all rows containing "ThingF_*"
I could loop over the whole table using the Standard DELETE FROM command:

```<code>DB eval { DELETE FROM 'MyTable' WHERE Names = 'ThingF_1' }
DB eval { DELETE FROM 'MyTable' WHERE Names = 'ThingF_2' }
</code>```

I have tried the LIKE command but with no success (and no error message)

```<code>set Name ThingF_

DB eval { DELETE FROM 'MyTable' WHERE Names LIKE $Name }
</code>```

I also tried

```<code>DB eval { DELETE FROM 'MyTable' WHERE Names LIKE '$Name%' }
</code>```

答:
User either LIKE or GLOB):

```<code>... WHERE Names LIKE 'ThingF_%'
... WHERE Names GLOB 'ThingF_*'
</code>```

Only GLOB is case sensitive.

Body:
Having a SQLite table with a column containing names:

Names

ThingA_1
ThingF_1
ThingF_2
ThingB_1
ThingB_2
ThingB_3
ThingB_4

I would like to remove all rows containing "ThingF_*"
I could loop over the whole table using the Standard DELETE FROM command:

DB eval { DELETE FROM 'MyTable' WHERE Names = 'ThingF_1' }
DB eval { DELETE FROM 'MyTable' WHERE Names = 'ThingF_2' }

I have tried the LIKE command but with no success (and no error message)

set Name ThingF_

DB eval { DELETE FROM 'MyTable' WHERE Names LIKE $Name }

I also tried

DB eval { DELETE FROM 'MyTable' WHERE Names LIKE '$Name%' }

Body:
User either LIKE or GLOB):

... WHERE Names LIKE 'ThingF_%'
... WHERE Names GLOB 'ThingF_*'

Only GLOB is case sensitive.


来源: stackexchange

问:
Using Highcharts Export Server, how to include commas in labels?
I am creating a Highcharts configuration object in Java (EDIT: yes, Java, on the server side, NOT JavaScript), and sending it to the Highcharts Export Server to get a PNG to use in a PDF.

Highcharts, by default, doesn't include commas in its data labels.

If I were just creating this chart on the client side, I'd add this to the javascript:

```<code>Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    }
});
</code>```

Then, I could make the commas show up.

The problem is, I don't know how to send an equivalent message to the Highcharts Export Server. Currently, I am sending an object like this (EDIT: from the server side, using Java) to the Highcharts Export Server and not getting commas in the labels of the PNG it returns:

```<code>{
    series: [{
        data: [1000, 2000, 1500],
    }],
    plotOptions: {
        series: {
          dataLabels: {
            enabled: true
          }
        }
    }
}
</code>```

What can I do or send to the Highcharts Export Server to get the desired effect of putting commas in the labels?

(you can test out objects in the Highcharts Export Server here: http://export.highcharts.com/)

答:
You can you globalOptions parameter in your request to achieve the desired result.

Live demo: http://jsfiddle.net/kkulig/0s7uwsgg/

```<code>var optionsStr = JSON.stringify({
    "series": [{
        dataLabels: {
        enabled: 'true'
      },
      "data": [1000, 1000]
    }]
  }),
  globalOptions = JSON.stringify({
    lang: {
          thousandsSep: ','
    }
  }),
  dataString = encodeURI('async=true&type=jpeg&width=400&options=' + optionsStr + '&globalOptions=' + globalOptions);
</code>```

API reference for request parameters: https://github.com/highcharts/node-export-server/blob/master/README.md

ContentLicense: CC BY-SA 3.0

Body:
I am creating a Highcharts configuration object in Java (EDIT: yes, Java, on the server side, NOT JavaScript), and sending it to the Highcharts Export Server to get a PNG to use in a PDF.

Highcharts, by default, doesn't include commas in its data labels.

If I were just creating this chart on the client side, I'd add this to the javascript:

Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    }
});

Then, I could make the commas show up.

The problem is, I don't know how to send an equivalent message to the Highcharts Export Server. Currently, I am sending an object like this (EDIT: from the server side, using Java) to the Highcharts Export Server and not getting commas in the labels of the PNG it returns:

{
    series: [{
        data: [1000, 2000, 1500],
    }],
    plotOptions: {
        series: {
          dataLabels: {
            enabled: true
          }
        }
    }
}

What can I do or send to the Highcharts Export Server to get the desired effect of putting commas in the labels?

(you can test out objects in the Highcharts Export Server here: http://export.highcharts.com/)

Body:
You can you globalOptions parameter in your request to achieve the desired result.

Live demo: http://jsfiddle.net/kkulig/0s7uwsgg/

var optionsStr = JSON.stringify({
    "series": [{
        dataLabels: {
        enabled: 'true'
      },
      "data": [1000, 1000]
    }]
  }),
  globalOptions = JSON.stringify({
    lang: {
          thousandsSep: ','
    }
  }),
  dataString = encodeURI('async=true&type=jpeg&width=400&options=' + optionsStr + '&globalOptions=' + globalOptions);

API reference for request parameters: https://github.com/highcharts/node-export-server/blob/master/README.md


问:
HTML Dropdown Menu very slow to load
I am working on a project for a client to make their roster viewing and entry paper-free. Some things rely on user input, but others are varied constants and are pulled from a database. One of the dropdowns pulling its information from said database is loading very slowly in my testing environment - I click it, and it takes two to three seconds for the items to actually show up.

I assume this is because the dropdown contains easily close to 400 items. What I'd like to know is if there is any way I can optimize this to make the loading faster. Cutting off at halfway or even a fourth of the way and making more dropdowns is outside of specification for the project, so a suggestion like that would have to go through the client for the go ahead. If that's the only solution, though, I'll do that.

Thanks in advance for suggestions.

EDIT:

This is the kind of oversight that makes me laugh, but I was wrong about my conservative estimate of 400 items - the list contains 12,700 items.

For all who assume the SQL query may be slow - I am doing a simple SELECT DISTINCT from one table, with only one WHERE condition.

答:
You could use an infinite scroll to break up the amount of data being returned. Take a look at this answer:

infinite scroll select

This may not be the underlying issue though. I would check the performance of your query to ensure that is not where the issue lies.

Title: HTML Dropdown Menu very slow to load


问:
Browser does not recoginize JQuery prettyPhoto() when using asp.net Masterpage
```<code><script src="Scripts/jquery.prettyPhoto.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>

<a href="http://www.youtube-nocookie.com/v/Bkjv9SscotY&hl=it_IT&fs=1?rel=0" rel="prettyPhoto" title="">you tube
</a>
<script type="text/javascript">

    $(document).ready(
function () {
    $(
"a[rel^='prettyPhoto']").prettyPhoto();
});

</script>
</code>```

答:
If your folder structure looks like this

```<code>/Scripts/jquery.prettyPhoto.js
/Scripts/someOtherscript.js
/SomeFolder/bob.aspx
sam.aspx
default.aspx
</code>```

If you reference your js file using src="scripts/file.js" it will work on sam.aspx and default.aspx, but it won't work on bob.aspx

When you don't include a leading slash, it looks in your current folder.  So if you reference that script on bob.aspx, it is looking for this file /somefolder/script/file.js

So, to answer your question (assuming I've made a good assumption), you just need to add a leading slash to src="script..   It should be src="/script/...

ContentLicense: CC BY-SA 2.5

Body: you tube

Body:
If your folder structure looks like this

/Scripts/jquery.prettyPhoto.js
/Scripts/someOtherscript.js
/SomeFolder/bob.aspx
sam.aspx
default.aspx

If you reference your js file using src="scripts/file.js" it will work on sam.aspx and default.aspx, but it won't work on bob.aspx

When you don't include a leading slash, it looks in your current folder.  So if you reference that script on bob.aspx, it is looking for this file /somefolder/script/file.js

So, to answer your question (assuming I've made a good assumption), you just need to add a leading slash to src="script..   It should be src="/script/...


问:
Getting JSON and cross to another class in AsyckTask
I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code

class when I click button:

```<code>public void onHistoryCheckIn(View view) {
  String nCar = numberCar; // to send number car for receive all data json
  String type = "historyChckIn";
  PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
  preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}
</code>```

Know I go to doInBackground, and I use the onPostExecute

```<code>protected void onPostExecute(String s) {
  // jsonResult ==> I NEED THE DATA!!!
  Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
  context.startActivity(intent);
  // alertDialog.setMessage(jsonResult);
  // alertDialog.show();
}
</code>```

I come to class HistoryCheckIn but without JSON, what I can do?

I want to bring jsonResult and I want to come to HistoryCheckIn.class

答:
the fastest way is to add json to your inent

```<code> protected void onPostExecute(String s) {
   Intent i =new Intent(context, NextActivity.class);
   i.putExtra("json", s)
   context.startActivity(intent);
}
</code>```

on other end call

```<code>String s= getIntent().getStringExtra("json");
</code>```

but it is not the best way

Body:
I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code

class when I click button:

public void onHistoryCheckIn(View view) {
  String nCar = numberCar; // to send number car for receive all data json
  String type = "historyChckIn";
  PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
  preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}

Know I go to doInBackground, and I use the onPostExecute

protected void onPostExecute(String s) {
  // jsonResult ==> I NEED THE DATA!!!
  Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
  context.startActivity(intent);
  // alertDialog.setMessage(jsonResult);
  // alertDialog.show();
}

I come to class HistoryCheckIn but without JSON, what I can do?

I want to bring jsonResult and I want to come to HistoryCheckIn.class

Body:
the fastest way is to add json to your inent

 protected void onPostExecute(String s) {
   Intent i =new Intent(context, NextActivity.class);
   i.putExtra("json", s)
   context.startActivity(intent);
}

on other end call

String s= getIntent().getStringExtra("json");

but it is not the best way


问:
Using PIL open a picture but got wrong color
I am new to image processing, when I was using PIL to process the image, I got the wrong color with this picture:
https://upload.wikimedia.org/wikipedia/commons/d/d9/Big_Bear_Valley,_California.jpg

Here is the demo code:

```<code>from PIL import Image

img = Image.open('/path/to/this/picture')
img.show()
</code>```

What's the reason about this problem ? Thanks!

答:
Probably only what you need to do is to attach image's Color Profile to 'sRGB IEC61966-2.1'. At least that's what helped me. You can do it with a ColorSync macOS app.

I did test on image filled with pure green color and got some weird values like [114 246  74] instead of [0 255 0].

It appears that image had 'Display P3' by default.

Body:
I am new to image processing, when I was using PIL to process the image, I got the wrong color with this picture:
https://upload.wikimedia.org/wikipedia/commons/d/d9/Big_Bear_Valley,_California.jpg

Here is the demo code:

from PIL import Image

img = Image.open('/path/to/this/picture')
img.show()

What's the reason about this problem ? Thanks!


问:
How can I include records based on when they first appear, and exclude other records based on a certain date?
I need to select criteria based on inclusions and exclusions of the same attributes and on different dates and I am having a hard time wrapping my head around how to do this.  Here is a list of my criteria.

The record was first added to the database with a transaction of 222 or 223 and an activity code of ‘A’.

The record does not have a status code of 7

Any records where the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745) after 10/01/2009 should not be included in the results,

There are 2 tables involved with a join on the employee ID.

Table 1:

```<code>|id  |  statcode
|  1     |  1
|  2     |  3
|  3     |  7
|  4     |  2
</code>```

Table 2:

```<code>|id       |  date      | act_code   |  trans
|   1     |  1/1/17    |   Z        |    109
|   1     |  3/4/12    |   A        |    222
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    223
|   2     |  6/6/13    |   V        |    109
|   3     |  11/23/14  |   A        |    222
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    223
</code>```

What I’d like to return is:

```<code>|    id  | statcode|  date      | act_code   |  trans
|   1    |   1     |  3/4/12    |   A        |    222
</code>```

ID 2 would not be selected because the first trans is not one of the correct values. ID 3 would not be included due to a incorrect status code. ID 4 would not be selected because the latest act_code is not one of the correct values. Anyone have an idea as to how to go about this? Thanks in advance.

edit: Here is the query as attempted. It seems to return everything.

```<code>SELECT *
FROM firsttable a
join secondtable b on a.id=b.id
where exists (select id, min(date) from
secondtable
where c.TRANS in ('222','223') and (TRANS NOT IN ('109', '154', '982',
'745')
AND ACT_CODE NOT IN  ('A', 'V', 'W', 'J') and date>= to_date('10/01/2009',
'MM/DD/YYYY'))
group by id)
and a.statcode <> '07'
;
</code>```

答:
*Updated: now tested and working.</p>

```<code>SELECT * FROM
tbl1 a INNER JOIN tbl2 b on a.id = b.id
where b.trans IN (222,223)
AND a.statcode <> 7
AND b.act_code = 'A'
AND NOT EXISTS(
SELECT 1 from tbl2 t2
    WHERE t2.id = a.id
    AND t2.act_code IN ('A','V','W','J')
    AND t2.trans IN (109,154,982,745)
    AND t2."date" > to_date('10/01/2009', 'MM/DD/YY'));
GO
</code>```

Body:
I need to select criteria based on inclusions and exclusions of the same attributes and on different dates and I am having a hard time wrapping my head around how to do this.  Here is a list of my criteria.

The record was first added to the database with a transaction of 222 or 223 and an activity code of ‘A’.

The record does not have a status code of 7

Any records where the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745) after 10/01/2009 should not be included in the results,

There are 2 tables involved with a join on the employee ID.

Table 1:

|id  |  statcode
|  1     |  1
|  2     |  3
|  3     |  7
|  4     |  2

Table 2:

|id       |  date      | act_code   |  trans
|   1     |  1/1/17    |   Z        |    109
|   1     |  3/4/12    |   A        |    222
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    223
|   2     |  6/6/13    |   V        |    109
|   3     |  11/23/14  |   A        |    222
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    223

What I’d like to return is:

|    id  | statcode|  date      | act_code   |  trans
|   1    |   1     |  3/4/12    |   A        |    222

ID 2 would not be selected because the first trans is not one of the correct values. ID 3 would not be included due to a incorrect status code. ID 4 would not be selected because the latest act_code is not one of the correct values. Anyone have an idea as to how to go about this? Thanks in advance.

edit: Here is the query as attempted. It seems to return everything.

SELECT *
FROM firsttable a
join secondtable b on a.id=b.id
where exists (select id, min(date) from
secondtable
where c.TRANS in ('222','223') and (TRANS NOT IN ('109', '154', '982',
'745')
AND ACT_CODE NOT IN  ('A', 'V', 'W', 'J') and date>= to_date('10/01/2009',
'MM/DD/YYYY'))
group by id)
and a.statcode <> '07'
;

Body:
*Updated: now tested and working.

SELECT * FROM
tbl1 a INNER JOIN tbl2 b on a.id = b.id
where b.trans IN (222,223)
AND a.statcode <> 7
AND b.act_code = 'A'
AND NOT EXISTS(
SELECT 1 from tbl2 t2
    WHERE t2.id = a.id
    AND t2.act_code IN ('A','V','W','J')
    AND t2.trans IN (109,154,982,745)
    AND t2."date" > to_date('10/01/2009', 'MM/DD/YY'));
GO


问:
Conditional value bolding or annotation for a barplot
The following query generates a barplot for top tickers:

```<code>df2=final_df.groupby(['ticker'])['ticker'].count().rename(columns={'ticker':''}).reset_index().rename(columns={0:'number_tickers_uploaded'}).reset_index(drop=True)
print(df2)
sns.set(style='darkgrid')
plt.title('Top tickers uploaded in the last week')
result = df2.sort_values('number_tickers_uploaded',ascending=False)
sns.barplot(x='ticker', y='number_tickers_uploaded', data=result.head(8), palette='Set2')
</code>```

This a sample of the data:

```<code>        ticker    number_tickers_uploaded
0       BWM       50
1       IND       25
2       RIA       18
3       X         10
4       Y         6
</code>```

The resulting barplot lists tickers by number_tickers_uploaded in descending order, but I would like the value to be bolded (either the ticker or the bar itself) and annotated with let's say "Z Fund," if it is equal to x or y .

Thank you!

--Edit--

I know I can annotate like so:

```<code># Annotate with text + Arrow
plt.annotate(
# Label and coordinate
'Z Fund', xy=(25, 50), xytext=(0, 80),

# Custom arrow
arrowprops=dict(facecolor='black', shrink=0.05)
)
</code>```

But I am trying to annotate conditionally (before you know the position the arrow and annotation should go)- not after seeing the data is plotted

答:
The question is a bit chaotic and I'm having problems understanding what you want to do under which conditions. As far as I understand, the aim is to make the ticklabels bold, add an annotation with an arrow and have an edge on bars for those bars which belong to some special label. The following code does that:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"name" : list("ABCDXY"), "value" : [5,6,3,5,7,4]})
result = df.sort_values("value",ascending=False)

ax = sns.barplot(x="name", y="value", data=result, palette='Set2')

for i,t in enumerate(ax.get_xticklabels()):
    if t.get_text() in ["X", "Y"]:
        ## bold ticklabels
        t.set_weight("bold")
        ## bar edges
        ax.patches[i].set_edgecolor("k")
        ax.patches[i].set_linewidth(2)
        ## arrow annotations
        ax.annotate("Z Fund",(i, ax.patches[i].get_height()),
                    xytext=(0,30), textcoords='offset points', ha="center",
                    arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()
</code>```

Body:
The following query generates a barplot for top tickers:

df2=final_df.groupby(['ticker'])['ticker'].count().rename(columns={'ticker':''}).reset_index().rename(columns={0:'number_tickers_uploaded'}).reset_index(drop=True)
print(df2)
sns.set(style='darkgrid')
plt.title('Top tickers uploaded in the last week')
result = df2.sort_values('number_tickers_uploaded',ascending=False)
sns.barplot(x='ticker', y='number_tickers_uploaded', data=result.head(8), palette='Set2')

This a sample of the data:

        ticker    number_tickers_uploaded
0       BWM       50
1       IND       25
2       RIA       18
3       X         10
4       Y         6

The resulting barplot lists tickers by number_tickers_uploaded in descending order, but I would like the value to be bolded (either the ticker or the bar itself) and annotated with let's say "Z Fund," if it is equal to x or y .

Thank you!

--Edit--

I know I can annotate like so:

# Annotate with text + Arrow
plt.annotate(
# Label and coordinate
'Z Fund', xy=(25, 50), xytext=(0, 80),

# Custom arrow
arrowprops=dict(facecolor='black', shrink=0.05)
)

But I am trying to annotate conditionally (before you know the position the arrow and annotation should go)- not after seeing the data is plotted

Body:
The question is a bit chaotic and I'm having problems understanding what you want to do under which conditions. As far as I understand, the aim is to make the ticklabels bold, add an annotation with an arrow and have an edge on bars for those bars which belong to some special label. The following code does that:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({"name" : list("ABCDXY"), "value" : [5,6,3,5,7,4]})
result = df.sort_values("value",ascending=False)

ax = sns.barplot(x="name", y="value", data=result, palette='Set2')

for i,t in enumerate(ax.get_xticklabels()):
    if t.get_text() in ["X", "Y"]:
        ## bold ticklabels
        t.set_weight("bold")
        ## bar edges
        ax.patches[i].set_edgecolor("k")
        ax.patches[i].set_linewidth(2)
        ## arrow annotations
        ax.annotate("Z Fund",(i, ax.patches[i].get_height()),
                    xytext=(0,30), textcoords='offset points', ha="center",
                    arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()


问:
Variables of tensorflow generate error in a loop
I have a similar problem to TensorFlow: varscope.reuse_variables().

I am doing cross-validation on a dataset.

Each time I call a function e.g. myFunctionInFile1()) with new data (currently due to limited space, I am omitting the data assigning details). This function is not in same python file. Because of Which I import this function from that file in my main python file (file2). This function creates a complete CNN and train and test a model on the given training and testing data with newly initialized and trained parameters.

From the main file (file2), at first validation, myFunctionInFile1 is called and the CNN model train and test it and returns results to the main file (file2). However, in the second iteration with new data, following code:

def myFunctionInFile1():
    # Nodes for the input variables
    x = tf.placeholder("float", shape=[None, D], name='Input_data')
    y_ = tf.placeholder(tf.int64, shape=[None], name='Ground_truth')
    keep_prob = tf.placeholder("float")
    bn_train = tf.placeholder(tf.bool)  # Boolean value to guide batchnorm

    def bias_variable(shape, name):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial, name=name)

    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')

    with tf.name_scope("Reshaping_data") as scope:
        x_image = tf.reshape(x, [-1, D, 1, 1])

    initializer = tf.contrib.layers.xavier_initializer()
    """Build the graph"""
    # ewma is the decay for which we update the moving average of the
    # mean and variance in the batch-norm layers

    with tf.name_scope("Conv1") as scope:
        # reuse = tf.AUTO_REUSE
        W_conv1 = tf.get_variable("Conv_Layer_1", shape=[5, 1, 1, num_filt_1], initializer=initializer)
        b_conv1 = bias_variable([num_filt_1], 'bias_for_Conv_Layer_1')
        a_conv1 = conv2d(x_image, W_conv1) + b_conv1
    with tf.name_scope('Batch_norm_conv1') as scope:
        a_conv1 = tf.contrib.layers.batch_norm(a_conv1,is_training=bn_train,updates_collections=None)
```

<p>give me following error:</p>

<pre class="lang-python prettyprint-override"><code>ValueError: Variable BatchNorm_2/beta does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope?
</code>```

What is the problem, as generally in programming in C/C++/Java if you exit a function, the local variables in that called function are deleted automatically at return. And at each time new call it should create a new set of parameters. Than why it gives this error. How can I fix this?

答:
TensorFlow layers like batch_norm are implemented using tf.get_variable. tf.get_variable has a reuse argument (which it can also get from a variable_scope), defaulting to False, and when called with reuse=False it always creates variables. You can call it with reuse=True which means it will reuse existing variables or fail if the variables do not exist.

In your case you're calling batch norm with reuse=True for the first time, so it's having a hard time creating the variables. Try setting reuse=False in your variable scope or using, as the error message suggests, tf.AUTO_REUSE.

Body:
I have a similar problem to TensorFlow: varscope.reuse_variables().

I am doing cross-validation on a dataset.

Each time I call a function e.g. myFunctionInFile1()) with new data (currently due to limited space, I am omitting the data assigning details). This function is not in same python file. Because of Which I import this function from that file in my main python file (file2). This function creates a complete CNN and train and test a model on the given training and testing data with newly initialized and trained parameters.

From the main file (file2), at first validation, myFunctionInFile1 is called and the CNN model train and test it and returns results to the main file (file2). However, in the second iteration with new data, following code:

def myFunctionInFile1():
    # Nodes for the input variables
    x = tf.placeholder("float", shape=[None, D], name='Input_data')
    y_ = tf.placeholder(tf.int64, shape=[None], name='Ground_truth')
    keep_prob = tf.placeholder("float")
    bn_train = tf.placeholder(tf.bool)  # Boolean value to guide batchnorm

    def bias_variable(shape, name):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial, name=name)

    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                          strides=[1, 2, 2, 1], padding='SAME')

    with tf.name_scope("Reshaping_data") as scope:
        x_image = tf.reshape(x, [-1, D, 1, 1])

    initializer = tf.contrib.layers.xavier_initializer()
    """Build the graph"""
    # ewma is the decay for which we update the moving average of the
    # mean and variance in the batch-norm layers

    with tf.name_scope("Conv1") as scope:
        # reuse = tf.AUTO_REUSE
        W_conv1 = tf.get_variable("Conv_Layer_1", shape=[5, 1, 1, num_filt_1], initializer=initializer)
        b_conv1 = bias_variable([num_filt_1], 'bias_for_Conv_Layer_1')
        a_conv1 = conv2d(x_image, W_conv1) + b_conv1
    with tf.name_scope('Batch_norm_conv1') as scope:
        a_conv1 = tf.contrib.layers.batch_norm(a_conv1,is_training=bn_train,updates_collections=None)

give me following error:

ValueError: Variable BatchNorm_2/beta does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=tf.AUTO_REUSE in VarScope?

What is the problem, as generally in programming in C/C++/Java if you exit a function, the local variables in that called function are deleted automatically at return. And at each time new call it should create a new set of parameters. Than why it gives this error. How can I fix this?


问:
Running CUDA on a virtual machine without a physical NVidia GPU card
Is it possible to run a CUDA program on a virtual machine without having a physical NVidia GPU card on the host machine?

PCIe passthrough is only viable if the host machine has an NVidia card and that's not available.

One possible option to run CUDA programs without a GPU installed is to use an emulator/simulator (ex: http://gpgpu-sim.org/ ) but these simulators are usually limited.

I would appreciate a clear answer on that matter.
Thanks!

答:
You can't run any modern version of CUDA (e.g. 6.0 or newer) unless you have actual GPU hardware available on the machine or virtual machine.

The various simulators and other methods all depend on very old versions of CUDA.


问:
Exception Handling Ordering
Why is the stack trace Exception in thread "main" java.lang.ArithmeticException: 3
and not Exception in thread "main" java.lang.ArithmeticException: 1?
Isn't ArithmeticException("1") thrown first?

```<code> try{
        try{
            throw new ArithmeticException("1");
        }finally{
            throw new ArithmeticException("2");
        }
    }finally{
        throw new ArithmeticException("3");
    }
</code>```

答:
Yes, the "1" exception is thrown first. However:

Your finallys overwrite the exceptions thrown in the try blocks, so the finally exceptions are the only ones seen by the exception handling code.

Don't throw or return in a finally block, for precisely this reason.

See the description of this problem in Google's Error Prone documentation for a lot more detail.

Title: Exception Handling Ordering

Body:
Why is the stack trace Exception in thread "main" java.lang.ArithmeticException: 3
and not Exception in thread "main" java.lang.ArithmeticException: 1?
Isn't ArithmeticException("1") thrown first?

 try{
        try{
            throw new ArithmeticException("1");
        }finally{
            throw new ArithmeticException("2");
        }
    }finally{
        throw new ArithmeticException("3");
    }


问:
Dynamic height for UITableViewCell not working correctly
I'm having some height problems with my dynamic UITableViewCell (sew picture below). Some cells have the correct height and some not, and when I drag the tableView some of the cells become correct and some don't.

I'm using this code to get the cell's height to be dynamic and reloading it in viewDidAppear and viewDidLoad.

```<code>tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableView.rowHeight
</code>```

As mentioned the cells are sometimes correct and sometimes not. Is there another way to do it or am I doing something wrong? I have tried many different solutions, all mentioned here as well as other suggestions both here at StackOverflow and other sites.

I appreciate all help!

Edit!

TableView

```<code>extension ChatVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMessages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "groupFeedCell", for: indexPath) as? GroupFeedCell else { return UITableViewCell() }

        let message = groupMessages[indexPath.row]

            DataService.instance.getUsername(forUID: message.senderId, handler: { (name) in
                cell.configureCell(name: name, content: message.content)
            })

        cell.layoutSubviews()
        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}
</code>```

Cell

```<code>@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var contentLbl: UILabel!

func configureCell(name: String, content: String) {
    self.nameLbl.text = name //email
    self.contentLbl.text = content
}
</code>```

答:
Your are facing this issue because the content of your label comes from an async function.

The cell uses its content to work out its height dynamically. When your async request returns it has already done its work and will not recalculate and resize.

You need to make these requests, cache/store the results and reload the cells as needed. Usually in chat there would only be a couple of users to load usernames for anyway. You could also try pre-loading this data before the chat is displayed.

You can quickly confirm this by creating an array of random usernames and messages (sample data) and adding that to the cell straight away.

Body:
I'm having some height problems with my dynamic UITableViewCell (sew picture below). Some cells have the correct height and some not, and when I drag the tableView some of the cells become correct and some don't.

I'm using this code to get the cell's height to be dynamic and reloading it in viewDidAppear and viewDidLoad.

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableView.rowHeight

As mentioned the cells are sometimes correct and sometimes not. Is there another way to do it or am I doing something wrong? I have tried many different solutions, all mentioned here as well as other suggestions both here at StackOverflow and other sites.

I appreciate all help!

Edit!

TableView

extension ChatVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMessages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "groupFeedCell", for: indexPath) as? GroupFeedCell else { return UITableViewCell() }

        let message = groupMessages[indexPath.row]

            DataService.instance.getUsername(forUID: message.senderId, handler: { (name) in
                cell.configureCell(name: name, content: message.content)
            })

        cell.layoutSubviews()
        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}

Cell

@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var contentLbl: UILabel!

func configureCell(name: String, content: String) {
    self.nameLbl.text = name //email
    self.contentLbl.text = content
}


问:
Function that returns the closest number to B that's in an UNSORTED multidimensional array, A?
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

```<code>import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])
</code>```

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

```<code>def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer
</code>```

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.

答:
Your problem is the same as a find-min problem.  The only difference is that you're looking for min(abs(A[i]-B)) instead.  So, iterate over your array.  As you do so, record the smallest absolute delta and the index at which it occurred.  When you find a smaller delta, update the record and then keep searching.  When you've made it all the way through, return whatever value was at the recorded index.

Since you're working with numpy arrays, another approach is that you could create an array of identical size as A but filled only with value B.  Compute the difference between the arrays and then use argmin on each row.  Assemble an array of all minimum values for each row and then do argmin again to pull out the smallest of the values.

Body:
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.


问:
How to send from JAVA String(path of file) to C?
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

```<code>     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }
</code>```

Now with a thread i start to call the function that connect with C

```<code>      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}
</code>```

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

```<code>    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }
</code>```

The C code that will recieve the path will be look like that...

```<code>            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }
</code>```

I try with ProcessBuilder but i cant send the path every time with this way...

```<code>          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }
</code>```

答:
Use jni (Java native interfaces)  Make a c++ .dll file and you can easily pass information between both languages.

Good example/explanation for using jni:
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

Body:
i want to send from java some paths to C.

For example i have a folder that have 4 subfoldes... From java i read the length of them from the code below and it returns me 4.

     public static int GetLength(){File file = new File("C:\\Registrations");
           File[] files = file.listFiles(new FileFilter(){
             public boolean accept(File f) {
                 return f.isDirectory();   }});
                  return files.length;}     }

Now with a thread i start to call the function that connect with C

      public Start(){ Thread listeningThread = new Thread(new Runnable(){
        public void run(){
        new Match(GetDBNumber());  }  });
        listeningThread.start();}

So far all good. Now from MATCH(int x) class i want to call a C code and every time give the path of the Main folder each time

    *PSEUDOCODE*      public class Match {
                       public Match( int len){
                      System.out.println("subfolders  : "+len);
                      for (i=0; i<len; i++)
                      {     //Some way call C programm (like an exe)
                            //with the first,second,third,fourth path
                      }
                        ....      }

The C code that will recieve the path will be look like that...

            int main()     {
            FILE *fp = fopen(FilePATH, "r");
            ......
            ......
            return 0;                                 }

I try with ProcessBuilder but i cant send the path every time with this way...

          ProcessBuilder p = new ProcessBuilder();
           //receive.exe is the exe that Codeblocks create after built the C code
          p.command("C:\\Users\\PC\\Documents\\NetBeansProjects\\TEST\\C\\recieve.exe");
         try {
             p.start();
             } catch (Exception e) {System.out.println("Error");

            }


问:
Jackson JSon : Can not deserialize instance of java.lang.String out of START_OBJECT token
I'm using an API and I'm trying to deserialize  the results with Jackson but I always have the same mistake.

I guess my POJO is not right but I can't find what's wrong.

The mistake is on libs

I've tried to declare as String or as List without any success. Any idea ?

```<code>{
"libs": {},
"items": [
    {
        "id": "001",
        "cars": [
            "cd1042af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    },
    {

        "id": "002",
        "cars": [
            "cd1043af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    }]
</code>```

}

```<code>public class Page<Car> {

    private List<String> libs;

    private List<Car>items;

    public List<Car> getItems() {
        return items;
    }

    public void setItems(List<Car> items) {
        this.items = items;
    }

    public List<String> getLibs() {
        return libs;
    }

    public void setLibs(List<String> libs) {
        this.libs = libs;
    }

}
</code>```

答:
You are declaring libs as a list but using the maps/objects brackets.

Should be "libs": []

And you have extra commas after name attribute ends in each list element.

Body:
I'm using an API and I'm trying to deserialize  the results with Jackson but I always have the same mistake.

I guess my POJO is not right but I can't find what's wrong.

The mistake is on libs

I've tried to declare as String or as List without any success. Any idea ?

{
"libs": {},
"items": [
    {
        "id": "001",
        "cars": [
            "cd1042af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    },
    {

        "id": "002",
        "cars": [
            "cd1043af-856d-4649-a170-032d15a4119b",
            "00ed61a4-3aab-4722-90c2-7f4cca4cbded",
            "8fa3aa8b-3f22-4413-a41d-e78de9051de2"
        ],
        "name": "James"

    }]

}

public class Page<Car> {

    private List<String> libs;

    private List<Car>items;

    public List<Car> getItems() {
        return items;
    }

    public void setItems(List<Car> items) {
        this.items = items;
    }

    public List<String> getLibs() {
        return libs;
    }

    public void setLibs(List<String> libs) {
        this.libs = libs;
    }

}


问:
Priority/Cascading datetime without full table scan
```<code>SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';
</code>```

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

```<code>+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
</code>```

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

```<code>WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
</code>```

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

```<code>+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
</code>```

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

```<code>SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');
</code>```

And its explain plan:

```<code>+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
</code>```

答:
First you need a compound index on (priority_date, created_at), then you can use a query like this:

```<code>SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10' AND '2017-10-10 23:59:59'
  OR (priority_date IS NULL AND created_at BETWEEN '2017-10-10' AND '2017-10-10 23:59:59');
</code>```

Having priority_date first in the compound index makes a big difference.  No union is required.

Explain results on 400k rows with 2000 results:

```<code>Extra: Using where; Using index
key: priority_created_compound
rows: 2000
</code>```

Body:
SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');

And its explain plan:

+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+

Body:
First you need a compound index on (priority_date, created_at), then you can use a query like this:

SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10' AND '2017-10-10 23:59:59'
  OR (priority_date IS NULL AND created_at BETWEEN '2017-10-10' AND '2017-10-10 23:59:59');

Having priority_date first in the compound index makes a big difference.  No union is required.

Explain results on 400k rows with 2000 results:

Extra: Using where; Using index
key: priority_created_compound
rows: 2000


问:
Delete records from SQL Server backup file
It is an insane idea to delete records from backup since the notion of backup is to serve on disaster. But in our case, data deletion is a valid use-case.

Requirement: in brief, we are in need of a system which is capable of deleting a specific record from an active database instance and from all its backups.

We have a fully functional internal system which is capable of performing the mentioned requirement of deleting data from active database. But what we don't know is how to do the same agonist all these database backups.

Question:

Is it possible to find a specific record from a backup?

Is there any predefined schema or data allocation style within SQL Server backup file, which allow us to isolate a specific record?

Can you share any thoughts or experience you have on such style of deletion?

Note: we take 2 full backup daily and store a week worth (14 in total) at any point in time.

答: You can't modify the contents of a .bak file. You shouldn't want to do that either. If you want to restore to a specific point in time you should use the Full recovery model and take differential and log backups instead of just full backups. </p>


问:
Convert Android Java formatted string to Swift
```<code>private String result = String.format("$1#%1$s","myString")
</code>```

How do I get an equivalent result in Swift 4?

答:
You should use String(format:_:) and use %@ as a reference instead of %1$s.

```<code>let myString = "test"
let result = String(format: "$1#%@", myString) //$1#test
</code>```

Read more about String Format Specifiers in the Cocoa documentation.

Body:
private String result = String.format("$1#%1$s","myString")

How do I get an equivalent result in Swift 4?

Body:
You should use String(format:_:) and use %@ as a reference instead of %1$s.

let myString = "test"
let result = String(format: "$1#%@", myString) //$1#test

Read more about String Format Specifiers in the Cocoa documentation.


问:
codeblocks shows error: This file requires support for the ISO C++ 2011 standard
I want to use poisson_distribution template in my C++ code (included in random header), but cant find a way to compile it without error

My codeblocks shows an error

This file requires compiler and library support for the \
  ISO C++ 2011 standard. This support is currently experimental, and must be \
  enabled with the -std=c++11 or -std=gnu++11 compiler options.

I remember while installing codeblocks I installed only gnu c/c++ compiler. Can anyone explain me how to update my compiler to standard ISO C++ 2011 standard or suggest an alternative.

Thanks in advance...

答:
A simple option would be to write

```<code>-std=c++11
</code>```

As part of the other compiler options flags or directly in your Makefile.

Note that some projects may require -std=gnu++11 which is like C++11 but has some GNU extensions enabled.

Body:
A simple option would be to write

-std=c++11

As part of the other compiler options flags or directly in your Makefile.

Note that some projects may require -std=gnu++11 which is like C++11 but has some GNU extensions enabled.