问:
Update dynamodb item based on condition
I want to update an item in DynamoDB only if the new item has a more recent date than the existing item. Currently, I'm querying for the existing item, doing the comparison in my code, and then writing to db. I was wondering if there was a way to have DynamoDB do the checking and updating in single query.i have used conditionalexpression but it's not updating value even if condition satisfies.
I'm working with nodejs.</p>

答:
I have found solution by using

Expected

clause of dynamodb.
so below is my code.

```<code>var params;
  params = {
    Key: {
      "HashKey": {
        S: "Value"
      }
    },
    TableName: 'TableName',
    AttributeUpdates: {
      "Attr1": {
        Value: {
          S: "Value1"
        }
      }
    },
    Expected: {
      "Attr2": {
          "ComparisonOperator": "EQ",
          "AttributeValueList": [ {S: "Value2"} ]
      }
    }
  };
  dynamodb_client.updateItem(params, function(err, data) {
  if (err){
    console.log(err);
  } else {
    console.log(data);
  }
});
</code>```

so above code updates value of Attr1 to Value 1 if Attr2 is equal to Value2

Title: Update dynamodb item based on condition

Body:
I have found solution by using

Expected

clause of dynamodb.
so below is my code.

var params;
  params = {
    Key: {
      "HashKey": {
        S: "Value"
      }
    },
    TableName: 'TableName',
    AttributeUpdates: {
      "Attr1": {
        Value: {
          S: "Value1"
        }
      }
    },
    Expected: {
      "Attr2": {
          "ComparisonOperator": "EQ",
          "AttributeValueList": [ {S: "Value2"} ]
      }
    }
  };
  dynamodb_client.updateItem(params, function(err, data) {
  if (err){
    console.log(err);
  } else {
    console.log(data);
  }
});

so above code updates value of Attr1 to Value 1 if Attr2 is equal to Value2


来源: stackexchange

问:
How do I reverse each word in a sentence string like "I love computer science" using c++
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

```<code>#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}
</code>```

答:
After getting the sentence, get each word from the sentence into a new variable, then reverse and print it.

Tip: you need a for loop inside a for loop.

```<code>for word in sentence:
    for character in word:
        /* your code to reverse the word */
    /* print the word */
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}

Body:
After getting the sentence, get each word from the sentence into a new variable, then reverse and print it.

Tip: you need a for loop inside a for loop.

for word in sentence:
    for character in word:
        /* your code to reverse the word */
    /* print the word */


问:
How to transform new data using sklearn.pipeline
I have created a pipeline with TfIdfVectorizer transformer and OnevsRestClassifier estimator and trained it on training data as follows

```<code># Split data using train_test_split
print "Split data into train and test sets"
x_train, x_test, y_train, y_test = train_test_split(
    data_x, data_y, test_size=0.33)

# transform matrix of plots into lists to pass to a TfidfVectorizer
train_x = [x[0].strip() for x in x_train.tolist()]
test_x = [x[0].strip() for x in x_test.tolist()]

# Pipeline fit and transform
print "Learn the model using train data"
model = text_clf.fit(train_x, y_train)

# Predict the test data
print "Predict the recipients on test data"
predictions = model.predict(test_x)
</code>```

Now, I want to use the trained model to predict classes for new unlabeled data.
I tried this and got an error

```<code># Read text from input
text = raw_input()
print "Input : ", text
new_data = text_clf.transform([text])
predict = model.predict(new_data)
</code>```

This is the error. What Am I doing wrong?

```<code>AttributeError: 'OneVsRestClassifier' object has no attribute 'transform'
</code>```

答:
If text_clf and model are a pipeline as you have suggested, then no need to call transform and then predict. Only call

```<code>predictions = model.predict([text])
</code>```

The pipeline will internally automatically transform the data into usable format (using transform() on intermediate transformers).

When you explicitly call model.transform(), the pipeline assumes that all the estimators inside the pipeline are having a transform() which is not the case here.

Body:
I have created a pipeline with TfIdfVectorizer transformer and OnevsRestClassifier estimator and trained it on training data as follows

# Split data using train_test_split
print "Split data into train and test sets"
x_train, x_test, y_train, y_test = train_test_split(
    data_x, data_y, test_size=0.33)

# transform matrix of plots into lists to pass to a TfidfVectorizer
train_x = [x[0].strip() for x in x_train.tolist()]
test_x = [x[0].strip() for x in x_test.tolist()]

# Pipeline fit and transform
print "Learn the model using train data"
model = text_clf.fit(train_x, y_train)

# Predict the test data
print "Predict the recipients on test data"
predictions = model.predict(test_x)

Now, I want to use the trained model to predict classes for new unlabeled data.
I tried this and got an error

# Read text from input
text = raw_input()
print "Input : ", text
new_data = text_clf.transform([text])
predict = model.predict(new_data)

This is the error. What Am I doing wrong?

AttributeError: 'OneVsRestClassifier' object has no attribute 'transform'

Body:
If text_clf and model are a pipeline as you have suggested, then no need to call transform and then predict. Only call

predictions = model.predict([text])

The pipeline will internally automatically transform the data into usable format (using transform() on intermediate transformers).

When you explicitly call model.transform(), the pipeline assumes that all the estimators inside the pipeline are having a transform() which is not the case here.


问:
How to implement tool-tip on Stacked bar chart in Power BI
I have a Stacked bar chart that displays Tasks by UserName.
So each user can have:
Closed Tasks - black color
Overdue Tasks - red color
Open Tasks - green color

How can I use a tool-tip so when I drag my mouse on any of tasks I want to see how many of those task are particular type.

For example, if I am interested in user Alison Petrarca, if I point my mouse on a green color (where value is 24) I want to see that there is  8 of them are "Audits" type; 9 of them are "Follow-up" type; 6 of them are "Pending Cancellation" type etc.

Same if I point my mouse on a red color (where value is 6) I want to see what types of tasks contain those 6.

Is it possible to achieve that?

So far I created a couple of measures for Audit type for Open and Overdue tasks:

```<code>AuditsOpen = CALCULATE(SUM(TotalCounts[OpenTasks]), TotalCounts[Type]= "Audits")
AuditsOpen = CALCULATE(SUM(TotalCounts[OpenTasks]), TotalCounts[Type]= "Audits")
</code>```

But then, even if I point mouse only on green (Open Tasks) I still see Audits for open tasks and audits for Closed tasks.
But I only want to see for open tasks.

答:
Reshaping your data will make this fairly simple. Take your TotalCounts table and unpivot the ClosedTasks, OverdueTasks, and OpenTasks columns in the query editor so that it looks like this:

```<code>AssignedTo       | Type   | Status       | Tasks
-----------------|--------|--------------|-------
Allison Petrarca | Audits | ClosedTasks  | 6
Allison Petrarca | Audits | OverdueTasks | 3
Allison Petrarca | Audits | OpenTasks    | 8
Allison Petrarca | Claims | ClosedTasks  | 4
Allison Petrarca | Claims | OverdueTasks | 0
Allison Petrarca | Claims | OpenTasks    | 0
... (etc.) ...
</code>```

Then you can put AssignedTo on your Axis, Status as your Legend, and Tasks as your Value. Then you'll create a measure for each Type you want on the tooltip. I.e.

```<code>Audits = CALCULATE(SUM(TotalCounts[Tasks]), TotalCounts[Type]="Audits")
Claims = CALCULATE(SUM(TotalCounts[Tasks]), TotalCounts[Type]="Claim")
... (etc.) ...
</code>```

Body:
I have a Stacked bar chart that displays Tasks by UserName.
So each user can have:
Closed Tasks - black color
Overdue Tasks - red color
Open Tasks - green color

How can I use a tool-tip so when I drag my mouse on any of tasks I want to see how many of those task are particular type.

For example, if I am interested in user Alison Petrarca, if I point my mouse on a green color (where value is 24) I want to see that there is  8 of them are "Audits" type; 9 of them are "Follow-up" type; 6 of them are "Pending Cancellation" type etc.

Same if I point my mouse on a red color (where value is 6) I want to see what types of tasks contain those 6.

Is it possible to achieve that?

So far I created a couple of measures for Audit type for Open and Overdue tasks:

AuditsOpen = CALCULATE(SUM(TotalCounts[OpenTasks]), TotalCounts[Type]= "Audits")
AuditsOpen = CALCULATE(SUM(TotalCounts[OpenTasks]), TotalCounts[Type]= "Audits")

But then, even if I point mouse only on green (Open Tasks) I still see Audits for open tasks and audits for Closed tasks.
But I only want to see for open tasks.

Body:
Reshaping your data will make this fairly simple. Take your TotalCounts table and unpivot the ClosedTasks, OverdueTasks, and OpenTasks columns in the query editor so that it looks like this:

AssignedTo       | Type   | Status       | Tasks
-----------------|--------|--------------|-------
Allison Petrarca | Audits | ClosedTasks  | 6
Allison Petrarca | Audits | OverdueTasks | 3
Allison Petrarca | Audits | OpenTasks    | 8
Allison Petrarca | Claims | ClosedTasks  | 4
Allison Petrarca | Claims | OverdueTasks | 0
Allison Petrarca | Claims | OpenTasks    | 0
... (etc.) ...

Then you can put AssignedTo on your Axis, Status as your Legend, and Tasks as your Value. Then you'll create a measure for each Type you want on the tooltip. I.e.

Audits = CALCULATE(SUM(TotalCounts[Tasks]), TotalCounts[Type]="Audits")
Claims = CALCULATE(SUM(TotalCounts[Tasks]), TotalCounts[Type]="Claim")
... (etc.) ...


问:
How to display a stack panel after some delay on button hover in WPF?
I have one button, on hovering mouse on that button for two seconds, i want open the stack panel.

xaml code:

```<code><StackPanel x:Name="spPinDetailsPopup" Height="200" Width="240" Visibility="Hidden">
     <!--it contains label control which have text to display-->
</StackPanel>
<Button x:Name="btnDisplayPopUp" MouseEnter="DisplayPopUpOnMouseEnter"/>
</code>```

CS code :

```<code>void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    spPinDetailsPopup.Visibility = Visibility.Visible;
}
</code>```

I have used the stack panel as a pop up which displays the control information.

Current Result : Stack panel is displayed immediately.

Expected Result :
Stack panel should only be open when we put mouse cursor on button for more than 2 seconds.
Is there any solution ?

答:
Why not use ToolTip?

```<code>    <Button ToolTip="Some Text" ToolTipService.InitialShowDelay="2000"/>
</code>```

As ToolTip is an object, you can configure the layout to whatever you like, not just some text.

https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/tooltip-overview

Body:
I have one button, on hovering mouse on that button for two seconds, i want open the stack panel.

xaml code:

<StackPanel x:Name="spPinDetailsPopup" Height="200" Width="240" Visibility="Hidden">

</StackPanel>
<Button x:Name="btnDisplayPopUp" MouseEnter="DisplayPopUpOnMouseEnter"/>

CS code :

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    spPinDetailsPopup.Visibility = Visibility.Visible;
}

I have used the stack panel as a pop up which displays the control information.

Current Result : Stack panel is displayed immediately.

Expected Result :
Stack panel should only be open when we put mouse cursor on button for more than 2 seconds.
Is there any solution ?

Body:
Why not use ToolTip?

    <Button ToolTip="Some Text" ToolTipService.InitialShowDelay="2000"/>

As ToolTip is an object, you can configure the layout to whatever you like, not just some text.

https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/tooltip-overview


问:
how to remove both first and last line of csv file using sed
I can remove the first line of csv file's starting with myfile and merge them using:

```<code>sed 1d myfile*.csv > myfile_merged.csv
</code>```

I'd like to also remove the last line of the csv files.

I've tried:

```<code>sed 1d -i '$d' myfile*.csv > myfile_merged.csv
</code>```

But get the error:

```<code>sed: can't read $d: No such file or directory
</code>```

答:
Problem is this command:

```<code>sed 1d -i '$d' myfile*.csv > myfile_merged.csv
</code>```

You need not have an argument after -i (inline replacement) in sed otherwise it is treated as a SUFFIX to create a backup for inline replacement.

What you need is this gnu sed command:

```<code>sed -i '1d;$d' myfile*.csv
</code>```

This will remove 1st and last line in each of the matched file and save it in place.

Body:
I can remove the first line of csv file's starting with myfile and merge them using:

sed 1d myfile*.csv > myfile_merged.csv

I'd like to also remove the last line of the csv files.

I've tried:

sed 1d -i '$d' myfile*.csv > myfile_merged.csv

But get the error:

sed: can't read $d: No such file or directory

Body:
Problem is this command:

sed 1d -i '$d' myfile*.csv > myfile_merged.csv

You need not have an argument after -i (inline replacement) in sed otherwise it is treated as a SUFFIX to create a backup for inline replacement.

What you need is this gnu sed command:

sed -i '1d;$d' myfile*.csv

This will remove 1st and last line in each of the matched file and save it in place.


问:
Is there an analogue of this function in Python standard modules?
I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function:

```<code>def defaulted(func, defaultVal):
   try:
      result = func()
   except:
      result = defaultVal

   return result
</code>```

Thanks!

答:
No. Python's philosophy is that explicit is better than implicit. Most Python functions that are expected to throw exceptions regularly, like dict.__getitem__, provide equivalent versions that return a default value, like dict.get.

I've used the new with contexts for something like this before; the code looked like:

```<code>with ignoring(IOError, OSError):
    # some non-critical file operations
</code>```

But I didn't need to return anything either. Generally, the whole-function level is a bad place for this, and by using decorators you'd block any chance at actually getting the error should you want to handle it more gracefully elsewhere.

Also, except: is extremely dangerous; you probably mean (at least) except Exception:, and probably something even more tightly scoped, like IOError or KeyError. Otherwise you will also catch things like Ctrl-C, SystemExit, and misspelled variable names.

ContentLicense: CC BY-SA 2.5

Body:
I'm looking for a standard function (operator, decorator) that would be equivalent to the following hand-written function:

def defaulted(func, defaultVal):
   try:
      result = func()
   except:
      result = defaultVal

   return result

Thanks!

Body:
No. Python's philosophy is that explicit is better than implicit. Most Python functions that are expected to throw exceptions regularly, like dict.__getitem__, provide equivalent versions that return a default value, like dict.get.

I've used the new with contexts for something like this before; the code looked like:

with ignoring(IOError, OSError):
    # some non-critical file operations

But I didn't need to return anything either. Generally, the whole-function level is a bad place for this, and by using decorators you'd block any chance at actually getting the error should you want to handle it more gracefully elsewhere.

Also, except: is extremely dangerous; you probably mean (at least) except Exception:, and probably something even more tightly scoped, like IOError or KeyError. Otherwise you will also catch things like Ctrl-C, SystemExit, and misspelled variable names.


问:
How exactly are UDFs working in SparkR?
Let's say I defined a R function that takes two numerics as inputs :

```<code>effectifTouche <- function(audience, extrapolated){
TM = audience / 1000000
VE= extrapolated/100
TME = TM * VE
nbVis = TME / 1000000.1
return (nbVis)
}
</code>```

And it gives me back a score, so I would like to use it as an udf on two columns of SparkR DataFrame.

It was working in pyspark, and I was wondering how was SparkR working.

So I tried many things in both Sparklyr and SparkR but I can't get this UDF working.

Ideally, I would love to just do this :

```<code>df %>%
dapply(df_join,
    function(p) { effectifTouche(p$audience,p$extrapolated)
})
</code>```

effectifTouche being my R function and audience, extrapolated my two columns of the spark DataFrame.

I will gladly take answers for both libraries SparkR and Sparklyr, because I tried both, and checked every single github issues with no success.

Thanks a lot

Edit for another tricky use case

```<code>df %>%
   mutate(my_var = as.numeric(strptime(endHour,format="%H:%M:%S"),unit="secs"))
</code>```

答:
With simple arithmetic like this you're probably better off pushing the computation to Spark SQL, e.g.

```<code>df %>%
  mutate(TM = audience / 1000000,
         VE = extrapolated / 100,
         TME = TM * VE,
         nbVis = TME / 1000000.1)
</code>```

If you actually need to use external R packages, we can help you better if you provide an example of df.

Title: How exactly are UDFs working in SparkR?

Body:
Let's say I defined a R function that takes two numerics as inputs :

effectifTouche <- function(audience, extrapolated){
TM = audience / 1000000
VE= extrapolated/100
TME = TM * VE
nbVis = TME / 1000000.1
return (nbVis)
}

And it gives me back a score, so I would like to use it as an udf on two columns of SparkR DataFrame.

It was working in pyspark, and I was wondering how was SparkR working.

So I tried many things in both Sparklyr and SparkR but I can't get this UDF working.

Ideally, I would love to just do this :

df %>%
dapply(df_join,
    function(p) { effectifTouche(p$audience,p$extrapolated)
})

effectifTouche being my R function and audience, extrapolated my two columns of the spark DataFrame.

I will gladly take answers for both libraries SparkR and Sparklyr, because I tried both, and checked every single github issues with no success.

Thanks a lot

Edit for another tricky use case

df %>%
   mutate(my_var = as.numeric(strptime(endHour,format="%H:%M:%S"),unit="secs"))

Body:
With simple arithmetic like this you're probably better off pushing the computation to Spark SQL, e.g.

df %>%
  mutate(TM = audience / 1000000,
         VE = extrapolated / 100,
         TME = TM * VE,
         nbVis = TME / 1000000.1)

If you actually need to use external R packages, we can help you better if you provide an example of df.


问:
How to stub class property
I am trying to Stub class property using sinon.

```<code>function wrapper() {
  this.obj = {"message":"hello"};
  this.sendmessege = function() {
    console.log(this.obj.message);
    return "message is:" + this.obj.message;
  }
 }

// stub

var wrap = new wrapper();
stub = sinon.stub(wrap , 'sendmessege', function () {
    return 'hola';
 });
 stub1 = sinon.stub(wrap , {'obj':
   {'message':'hii'}
 });

console.log(stub1);
</code>```

its giving me

error : Attempted to wrap object property obj as function.

how i can stub obj ?

答:
If you want to stub the property of an object, use the value() method of the Stub.

```<code>stub1 = sinon.stub(wrap, 'obj').value({message: 'hii'});
</code>```

Documentation Reference: http://sinonjs.org/releases/v4.1.2/stubs/#stubvaluenewval

Title: How to stub class property

Body:
I am trying to Stub class property using sinon.

function wrapper() {
  this.obj = {"message":"hello"};
  this.sendmessege = function() {
    console.log(this.obj.message);
    return "message is:" + this.obj.message;
  }
 }

// stub

var wrap = new wrapper();
stub = sinon.stub(wrap , 'sendmessege', function () {
    return 'hola';
 });
 stub1 = sinon.stub(wrap , {'obj':
   {'message':'hii'}
 });

console.log(stub1);

its giving me

error : Attempted to wrap object property obj as function.

how i can stub obj ?

Body:
If you want to stub the property of an object, use the value() method of the Stub.

stub1 = sinon.stub(wrap, 'obj').value({message: 'hii'});

Documentation Reference: http://sinonjs.org/releases/v4.1.2/stubs/#stubvaluenewval


问:
What is a very efficient way to export data from a GridView to Excel?
I tested a few samples of VB code to export data from a GridView to Excel.  All were way too slow to be practical.  I'm dealing with 200k rows, or more, in the GridView.  Everything loads from SQL Server into the GridView very quickly, but to get it from the GridView to Excel is painfully slow.  I'd like to know if there is a fast way to move the data into Excel, like loading everything into an array, instead of looping through 200k rows of data.

Or, could I write to a CSV, and open that in Excel?  If that's pretty fast that could certainly be an option for me.

Thanks for sharing your wisdom experts.

答:
I think CSV is the fastest, but Excel.Range.Value2 allows you to send an array, rather than filling each cell one at a time:

```<code>Dim xl As New Excel.Application 'always use a variable to reference Excel, otherwise it may stay in memory, hidden.'
Dim b As Excel.Workbook = xl.Workbooks.Add 'do not use b = New Excel.Workbook, as this can cause a memory leak'
Dim s As Excel.Worksheet

xl.Visible = True
Dim sLast As Excel.Worksheet = b.Worksheets(b.Worksheets.Count)
b.Worksheets.Add(, sLast)
s = b.Worksheets(1) '1-based'
Dim o(199999, 1) As Object
For i As Integer = 0 To 199999
  o(i, 0) = i.ToString
  o(i, 1) = (200000 - i).ToString
Next i
s.Name = "ExcelDemo"
Dim r As Excel.Range = s.Range("A1", "B200000")
r.Value2 = o
s.Activate()
Dim strFilename As String = My.Computer.FileSystem.SpecialDirectories.Desktop & "\Junk" 'N.B. extension automatically added'
b.SaveAs(strFilename)
strFilename = b.FullName 'get full filename'
xl.Quit()
MsgBox(strFilename & " saved")
</code>```

Body:
I think CSV is the fastest, but Excel.Range.Value2 allows you to send an array, rather than filling each cell one at a time:

Dim xl As New Excel.Application 'always use a variable to reference Excel, otherwise it may stay in memory, hidden.'
Dim b As Excel.Workbook = xl.Workbooks.Add 'do not use b = New Excel.Workbook, as this can cause a memory leak'
Dim s As Excel.Worksheet

xl.Visible = True
Dim sLast As Excel.Worksheet = b.Worksheets(b.Worksheets.Count)
b.Worksheets.Add(, sLast)
s = b.Worksheets(1) '1-based'
Dim o(199999, 1) As Object
For i As Integer = 0 To 199999
  o(i, 0) = i.ToString
  o(i, 1) = (200000 - i).ToString
Next i
s.Name = "ExcelDemo"
Dim r As Excel.Range = s.Range("A1", "B200000")
r.Value2 = o
s.Activate()
Dim strFilename As String = My.Computer.FileSystem.SpecialDirectories.Desktop & "\Junk" 'N.B. extension automatically added'
b.SaveAs(strFilename)
strFilename = b.FullName 'get full filename'
xl.Quit()
MsgBox(strFilename & " saved")


问:
ORA-01791: oracle join
I want to know how to organize this code in a way where I'm only getting the data from customer. my problem is I'm getting repeated data from rental which is against what I need.

```<code> SELECT DISTINCT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
 FROM CUSTOMER C
   JOIN RENTAL R ON C.CUSTOMER_ID = R.CUSTOMER_ID
 ORDER BY C.LAST_NAME;
</code>```

exactly I should get 599 rows, when this is giving me 16044 rows.

答:
Fetch only distinct customers from rental to join with customer. I think the error you received - ORA-01791 is because of using ORDER BY C.LAST_NAME . either use ORDER BY "Customer Name"  or ORDER BY 2

```<code>SELECT
        C.CUSTOMER_ID ,
        (C.FIRST_NAME||
        ' '          ||
                C.LAST_NAME) "Customer Name"
FROM
        CUSTOMER C
JOIN
        ( SELECT DISTINCT CUSTOMER_ID FROM RENTAL
        ) R ON C.CUSTOMER_ID = R.CUSTOMER_ID
ORDER BY
        2;
</code>```

Title: ORA-01791: oracle join

Body:
I want to know how to organize this code in a way where I'm only getting the data from customer. my problem is I'm getting repeated data from rental which is against what I need.

 SELECT DISTINCT C.CUSTOMER_ID , (C.FIRST_NAME|| ' ' || C.LAST_NAME) "Customer Name"
 FROM CUSTOMER C
   JOIN RENTAL R ON C.CUSTOMER_ID = R.CUSTOMER_ID
 ORDER BY C.LAST_NAME;

exactly I should get 599 rows, when this is giving me 16044 rows.

Body:
Fetch only distinct customers from rental to join with customer. I think the error you received - ORA-01791 is because of using ORDER BY C.LAST_NAME . either use ORDER BY "Customer Name"  or ORDER BY 2

SELECT
        C.CUSTOMER_ID ,
        (C.FIRST_NAME||
        ' '          ||
                C.LAST_NAME) "Customer Name"
FROM
        CUSTOMER C
JOIN
        ( SELECT DISTINCT CUSTOMER_ID FROM RENTAL
        ) R ON C.CUSTOMER_ID = R.CUSTOMER_ID
ORDER BY
        2;


问:
How to remove border right form last child div?

How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="job-posting">
  <div class="row">
    <div class="col-md-4">
      <div class="process">
        <header>STEP 1</header>
        <div class="process-content">
          <i class="fa fa-user-plus icon" aria-hidden="true"></i>
          <h1>Signup</h1>
          <p>Sign Up as a Company or an Individual</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 2</header>
        <div class="process-content">
          <i class="fa fa-upload icon" aria-hidden="true"></i>
          <h1>Upload Resume</h1>
          <p>Upload your resume and provide us with details of you experience and skills</p>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <div class="process">
        <header>STEP 3</header>
        <div class="process-content">
          <i class="fa fa-smile-o icon" aria-hidden="true"></i>
          <h1>Get Hired</h1>
          <p>Browse the available job postings and get hired according to your skills</p>
        </div>
      </div>
    </div>
  </div>
</div></code>```

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

答:
Start by selecting the containing parent element for specificity (.job-posting), then apply the pseudo-selector :last-child to the containing element of the .process class you intend to target:

```<code>.job-posting .col-md-4:last-child .process {
    border-right: 0px;
}
</code>```

Since you are using framework classes that are most likely going to be used elsewhere you should use some sort of unique selector, like .job-posting, to avoid any conflicting styles you may experience on other pages or elements utilizing the same classes or similar nesting or DOM structures.

Body:
How do i remove border right form the last div?

.process {
  border-right: 1px solid #e0e0e0;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        STEP 1

Signup

Sign Up as a Company or an Individual

        STEP 2

Upload Resume

Upload your resume and provide us with details of you experience and skills

        STEP 3

Get Hired

Browse the available job postings and get hired according to your skills

I'm having trouble removing the right border form the last div I tried using the :last-child:border:remove;

Body:
Start by selecting the containing parent element for specificity (.job-posting), then apply the pseudo-selector :last-child to the containing element of the .process class you intend to target:

.job-posting .col-md-4:last-child .process {
    border-right: 0px;
}

Since you are using framework classes that are most likely going to be used elsewhere you should use some sort of unique selector, like .job-posting, to avoid any conflicting styles you may experience on other pages or elements utilizing the same classes or similar nesting or DOM structures.


问:
Instagram API Subscription endpoint asks for access token even though it is provided
I am sending a POST request to the Instagram API subscriptions endpoint to add a user subscription, but am getting the error:

error: StatusCodeError: 400 -
{"meta":
{"code":400,
"error_type":"OAuthParameterException",
"error_message":"Missing client_id or access_token URL parameter."}}

I have provided both the client_id and the access_token in my request.

Here is the request code.

```<code>let access_token = user[0].access_token
let options = {
        method: 'POST',
        uri: `https://api.instagram.com/v1/subscriptions/`,
        body: {
          access_token: access_token,
          client_id: instaConfig.client_id,
          client_secret: instaConfig.client_secret,
          object: 'user',
          aspect: 'media',
          verify_token: 'myVerifyToken',
          callback_url: `${callback_url}`
        },
        headers: {
          'User-Agent': 'Request-Promise'
        },
        // Automatically parses the JSON string in the response
        json: true
      }
// rp = require('request-promise')
      rp(options)
        .then((response) => {
          console.log('subscriptions response: ' + util.inspect(response, { showHidden: true, depth: null }))
        })
        .catch((err) => {
          console.log('error: ' + err)
        })
</code>```

答: It wouldn't read from body. It needs to be passed from query param or headers.</p>

Body:
I am sending a POST request to the Instagram API subscriptions endpoint to add a user subscription, but am getting the error:

error: StatusCodeError: 400 -
{"meta":
{"code":400,
"error_type":"OAuthParameterException",
"error_message":"Missing client_id or access_token URL parameter."}}

I have provided both the client_id and the access_token in my request.

Here is the request code.

let access_token = user[0].access_token
let options = {
        method: 'POST',
        uri: `https://api.instagram.com/v1/subscriptions/`,
        body: {
          access_token: access_token,
          client_id: instaConfig.client_id,
          client_secret: instaConfig.client_secret,
          object: 'user',
          aspect: 'media',
          verify_token: 'myVerifyToken',
          callback_url: `${callback_url}`
        },
        headers: {
          'User-Agent': 'Request-Promise'
        },
        // Automatically parses the JSON string in the response
        json: true
      }
// rp = require('request-promise')
      rp(options)
        .then((response) => {
          console.log('subscriptions response: ' + util.inspect(response, { showHidden: true, depth: null }))
        })
        .catch((err) => {
          console.log('error: ' + err)
        })


问:
Erratic timings in Julia
I am beginning to learn Julia after using Matlab for several years. I started by implementing a simple polynomial multiplication (without FFT) to try and understand the role of type stability. A big part of this project is the requirement for a fast polynomial multiplier. However, I have the following timings which I can't understand at all.

```<code>function cauchyproduct(L::Array{Float64},R::Array{Float64})
    # good one for floats
    N = length(L)
    prodterm = zeros(1,2N-1)
    for n=1:N
        Lterm = view(L,1:n)
        Rterm = view(R,n:-1:1)
        prodterm[n] = dot(Lterm,Rterm)
    end

    for n = 1:N-1
        Lterm = view(L,n+1:N)
        Rterm = view(R,N:-1:n+1)
        prodterm[N+n] = dot(Lterm,Rterm)
    end
    prodterm
end

testLength = 10000
goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j in 1:10
    @time cauchyproduct(goodL,goodR)
end
@which cauchyproduct(goodL,goodR)
</code>```

I get the following timings from 2 sequential runs of this code. These timings from one run to another are completely erratic. In general, the timing I get per test can range between .05s to 2s. Typically, the timings for a single run through the for loop will all have similar timings (as in the example below), but even this isn't always the case. Occasionally, I have it alternate such as
.05s
.05s
1.9s
.04s
.05s
2.1s
etc etc.

Any idea why this is happening?

```<code>  0.544795 seconds (131.08 k allocations: 5.812 MiB)
  0.510395 seconds (120.00 k allocations: 5.340 MiB)
  0.528362 seconds (120.00 k allocations: 5.340 MiB, 0.94% gc time)
  0.507156 seconds (120.00 k allocations: 5.340 MiB)
  0.507566 seconds (120.00 k allocations: 5.340 MiB)
  0.507932 seconds (120.00 k allocations: 5.340 MiB)
  0.527383 seconds (120.00 k allocations: 5.340 MiB)
  0.513301 seconds (120.00 k allocations: 5.340 MiB, 0.83% gc time)
  0.509347 seconds (120.00 k allocations: 5.340 MiB)
  0.509177 seconds (120.00 k allocations: 5.340 MiB)
  0.052247 seconds (120.00 k allocations: 5.340 MiB, 7.95% gc time)
  0.049644 seconds (120.00 k allocations: 5.340 MiB)
  0.047275 seconds (120.00 k allocations: 5.340 MiB)
  0.049163 seconds (120.00 k allocations: 5.340 MiB)
  0.049029 seconds (120.00 k allocations: 5.340 MiB)
  0.054050 seconds (120.00 k allocations: 5.340 MiB, 8.36% gc time)
  0.047010 seconds (120.00 k allocations: 5.340 MiB)
  0.051240 seconds (120.00 k allocations: 5.340 MiB)
  0.050961 seconds (120.00 k allocations: 5.340 MiB)
  0.049841 seconds (120.00 k allocations: 5.340 MiB, 4.90% gc time)
</code>```

Edit: The timings shown are obtained by executing the code beneath the defined functions twice in a row. Specifically, the code block

```<code>goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j in 1:10
    @time cauchyproduct(goodL,goodR)
end
</code>```

gives vastly different timings on different runs (without recompiling the functions above it). In all of the timings, the same method of cauchyproduct (the top version) is being called. Hopefully this clarifies the problem.

Edit 2: I changed the code block at the end to the following

```<code>testLength = 10000
goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j = 1:3
    @time cauchyproduct(goodL,goodR)
end

for j = 1:3
    goodL = rand(1,testLength)
    goodR = rand(1,testLength)
    @time cauchyproduct(goodL,goodR)
end

@time cauchyproduct(goodL,goodR)
@time cauchyproduct(goodL,goodR)
@time cauchyproduct(goodL,goodR)
</code>```

and got the following timings on 2 repeated executions of the new block.

Timing 1:

```<code>  0.045936 seconds (120.00 k allocations: 5.340 MiB)
  0.045740 seconds (120.00 k allocations: 5.340 MiB)
  0.045768 seconds (120.00 k allocations: 5.340 MiB)
  1.549157 seconds (120.00 k allocations: 5.340 MiB, 0.14% gc time)
  0.046797 seconds (120.00 k allocations: 5.340 MiB)
  0.046637 seconds (120.00 k allocations: 5.340 MiB)
  0.047143 seconds (120.00 k allocations: 5.341 MiB)
  0.049088 seconds (120.00 k allocations: 5.341 MiB, 3.88% gc time)
  0.049246 seconds (120.00 k allocations: 5.341 MiB)
</code>```

Timing 2:

```<code>  2.250852 seconds (120.00 k allocations: 5.340 MiB)
  2.370882 seconds (120.00 k allocations: 5.340 MiB)
  2.247676 seconds (120.00 k allocations: 5.340 MiB, 0.14% gc time)
  1.550661 seconds (120.00 k allocations: 5.340 MiB)
  0.047258 seconds (120.00 k allocations: 5.340 MiB)
  0.047169 seconds (120.00 k allocations: 5.340 MiB)
  0.048625 seconds (120.00 k allocations: 5.341 MiB, 4.02% gc time)
  0.045489 seconds (120.00 k allocations: 5.341 MiB)
  0.049457 seconds (120.00 k allocations: 5.341 MiB)
</code>```

So confused.

答:
Short answer: Your code is a bit odd, and so probably triggering garbage collection in unexpected ways, resulting in varied timings.

Long answer: I agree that the timings you are getting are a bit strange. I'm not completely sure I can nail down exactly what is causing the problem, but I'm 99% certain it is something to do with garbage collection.

So, your code is a bit odd, because you allow input arrays of any dimension, even though you then call the dot function (a BLAS routine for taking the dot product of two vectors). In case you didn't realise, if you want a vector, use Array{Float64,1}, and for a matrix Array{Float64,2} and so on. Or you could also uses the aliases Vector{Float64} and Matrix{Float64}.

The second odd thing I noticed is that in your test, you generate rand(1, N). This returns an Array{Float64,2}, i.e. a matrix. To get an Array{Float64, 1}, i.e. a vector, you would use rand(N). Then within your function you take views into your matrix, which are of size 1xN. Now, Julia uses column-major ordering, so using a 1xN object for a vector is going to be really inefficient, and is probably the source of your strange timings. Under the hood, I suspect the call to dot is going to involve converting these things into regular vectors of floats, since dot eventually feeds through to the underlying BLAS routine which will need this input type. All these conversions will mean plenty of temporary storage, which needs to be garbage collected at some point, and this will probably be the source of the varying timings (90% of the time, varied timings on the same code are the result of the garbage collector being triggered - and sometimes in quite unexpected ways).

So, there is probably several ways to improve the following, but my quick-and-dirty version of your function looks like this:

```<code>function cauchyproduct(L::AbstractVector{<:Number}, R::AbstractVector{<:Number})
    length(L) != length(R) && error("Length mismatch in inputs")
    N = length(L)
    prodterm = zeros(1,2*N-1)
    R = flipdim(R, 1)
    for n=1:N
        prodterm[n] = dot(view(L, 1:n), view(R, N-n+1:N))
    end
    for n = 1:N-1
        prodterm[N+n] = dot(view(L, n+1:N), view(R, 1:N-n))
    end
    return prodterm
end
</code>```

Note, I flip R before the loop so the memory doesn't need to be re-ordered over and over within the loop. This was no doubt contributing to your strange garbage collection issues. Then, applying your test (I think it is a better idea to move array generation inside the loop in case some clever caching issue throws off timings):

```<code>testLength = 10000
for j = 1:20
    goodL = rand(testLength);
    goodR = rand(testLength);
    @time cauchyproduct(goodL,goodR);
end
</code>```

we get something like this:

```<code>  0.105550 seconds (78.19 k allocations: 3.935 MiB, 2.91% gc time)
  0.022421 seconds (40.00 k allocations: 2.060 MiB)
  0.022527 seconds (40.00 k allocations: 2.060 MiB)
  0.022333 seconds (40.00 k allocations: 2.060 MiB)
  0.021568 seconds (40.00 k allocations: 2.060 MiB)
  0.021837 seconds (40.00 k allocations: 2.060 MiB)
  0.022155 seconds (40.00 k allocations: 2.060 MiB)
  0.022071 seconds (40.00 k allocations: 2.060 MiB)
  0.021720 seconds (40.00 k allocations: 2.060 MiB)
  0.024774 seconds (40.00 k allocations: 2.060 MiB, 9.13% gc time)
  0.021714 seconds (40.00 k allocations: 2.060 MiB)
  0.022066 seconds (40.00 k allocations: 2.060 MiB)
  0.021815 seconds (40.00 k allocations: 2.060 MiB)
  0.021819 seconds (40.00 k allocations: 2.060 MiB)
  0.021928 seconds (40.00 k allocations: 2.060 MiB)
  0.021795 seconds (40.00 k allocations: 2.060 MiB)
  0.021837 seconds (40.00 k allocations: 2.060 MiB)
  0.022285 seconds (40.00 k allocations: 2.060 MiB)
  0.021380 seconds (40.00 k allocations: 2.060 MiB)
  0.023828 seconds (40.00 k allocations: 2.060 MiB, 6.91% gc time)
</code>```

The first iteration is measuring compile time, rather than runtime, and so should be ignored (if you don't know what I mean by this then check the performance tips section of the official docs). As you can see, the remaining iterations are much faster, and quite stable.

Title: Erratic timings in Julia

Body:
I am beginning to learn Julia after using Matlab for several years. I started by implementing a simple polynomial multiplication (without FFT) to try and understand the role of type stability. A big part of this project is the requirement for a fast polynomial multiplier. However, I have the following timings which I can't understand at all.

function cauchyproduct(L::Array{Float64},R::Array{Float64})
    # good one for floats
    N = length(L)
    prodterm = zeros(1,2N-1)
    for n=1:N
        Lterm = view(L,1:n)
        Rterm = view(R,n:-1:1)
        prodterm[n] = dot(Lterm,Rterm)
    end

    for n = 1:N-1
        Lterm = view(L,n+1:N)
        Rterm = view(R,N:-1:n+1)
        prodterm[N+n] = dot(Lterm,Rterm)
    end
    prodterm
end

testLength = 10000
goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j in 1:10
    @time cauchyproduct(goodL,goodR)
end
@which cauchyproduct(goodL,goodR)

I get the following timings from 2 sequential runs of this code. These timings from one run to another are completely erratic. In general, the timing I get per test can range between .05s to 2s. Typically, the timings for a single run through the for loop will all have similar timings (as in the example below), but even this isn't always the case. Occasionally, I have it alternate such as
.05s
.05s
1.9s
.04s
.05s
2.1s
etc etc.

Any idea why this is happening?

  0.544795 seconds (131.08 k allocations: 5.812 MiB)
  0.510395 seconds (120.00 k allocations: 5.340 MiB)
  0.528362 seconds (120.00 k allocations: 5.340 MiB, 0.94% gc time)
  0.507156 seconds (120.00 k allocations: 5.340 MiB)
  0.507566 seconds (120.00 k allocations: 5.340 MiB)
  0.507932 seconds (120.00 k allocations: 5.340 MiB)
  0.527383 seconds (120.00 k allocations: 5.340 MiB)
  0.513301 seconds (120.00 k allocations: 5.340 MiB, 0.83% gc time)
  0.509347 seconds (120.00 k allocations: 5.340 MiB)
  0.509177 seconds (120.00 k allocations: 5.340 MiB)
  0.052247 seconds (120.00 k allocations: 5.340 MiB, 7.95% gc time)
  0.049644 seconds (120.00 k allocations: 5.340 MiB)
  0.047275 seconds (120.00 k allocations: 5.340 MiB)
  0.049163 seconds (120.00 k allocations: 5.340 MiB)
  0.049029 seconds (120.00 k allocations: 5.340 MiB)
  0.054050 seconds (120.00 k allocations: 5.340 MiB, 8.36% gc time)
  0.047010 seconds (120.00 k allocations: 5.340 MiB)
  0.051240 seconds (120.00 k allocations: 5.340 MiB)
  0.050961 seconds (120.00 k allocations: 5.340 MiB)
  0.049841 seconds (120.00 k allocations: 5.340 MiB, 4.90% gc time)

Edit: The timings shown are obtained by executing the code beneath the defined functions twice in a row. Specifically, the code block

goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j in 1:10
    @time cauchyproduct(goodL,goodR)
end

gives vastly different timings on different runs (without recompiling the functions above it). In all of the timings, the same method of cauchyproduct (the top version) is being called. Hopefully this clarifies the problem.

Edit 2: I changed the code block at the end to the following

testLength = 10000
goodL = rand(1,testLength)
goodR = rand(1,testLength)
for j = 1:3
    @time cauchyproduct(goodL,goodR)
end

for j = 1:3
    goodL = rand(1,testLength)
    goodR = rand(1,testLength)
    @time cauchyproduct(goodL,goodR)
end

@time cauchyproduct(goodL,goodR)
@time cauchyproduct(goodL,goodR)
@time cauchyproduct(goodL,goodR)

and got the following timings on 2 repeated executions of the new block.

Timing 1:

  0.045936 seconds (120.00 k allocations: 5.340 MiB)
  0.045740 seconds (120.00 k allocations: 5.340 MiB)
  0.045768 seconds (120.00 k allocations: 5.340 MiB)
  1.549157 seconds (120.00 k allocations: 5.340 MiB, 0.14% gc time)
  0.046797 seconds (120.00 k allocations: 5.340 MiB)
  0.046637 seconds (120.00 k allocations: 5.340 MiB)
  0.047143 seconds (120.00 k allocations: 5.341 MiB)
  0.049088 seconds (120.00 k allocations: 5.341 MiB, 3.88% gc time)
  0.049246 seconds (120.00 k allocations: 5.341 MiB)

Timing 2:

  2.250852 seconds (120.00 k allocations: 5.340 MiB)
  2.370882 seconds (120.00 k allocations: 5.340 MiB)
  2.247676 seconds (120.00 k allocations: 5.340 MiB, 0.14% gc time)
  1.550661 seconds (120.00 k allocations: 5.340 MiB)
  0.047258 seconds (120.00 k allocations: 5.340 MiB)
  0.047169 seconds (120.00 k allocations: 5.340 MiB)
  0.048625 seconds (120.00 k allocations: 5.341 MiB, 4.02% gc time)
  0.045489 seconds (120.00 k allocations: 5.341 MiB)
  0.049457 seconds (120.00 k allocations: 5.341 MiB)

So confused.

Body:
Short answer: Your code is a bit odd, and so probably triggering garbage collection in unexpected ways, resulting in varied timings.

Long answer: I agree that the timings you are getting are a bit strange. I'm not completely sure I can nail down exactly what is causing the problem, but I'm 99% certain it is something to do with garbage collection.

So, your code is a bit odd, because you allow input arrays of any dimension, even though you then call the dot function (a BLAS routine for taking the dot product of two vectors). In case you didn't realise, if you want a vector, use Array{Float64,1}, and for a matrix Array{Float64,2} and so on. Or you could also uses the aliases Vector{Float64} and Matrix{Float64}.

The second odd thing I noticed is that in your test, you generate rand(1, N). This returns an Array{Float64,2}, i.e. a matrix. To get an Array{Float64, 1}, i.e. a vector, you would use rand(N). Then within your function you take views into your matrix, which are of size 1xN. Now, Julia uses column-major ordering, so using a 1xN object for a vector is going to be really inefficient, and is probably the source of your strange timings. Under the hood, I suspect the call to dot is going to involve converting these things into regular vectors of floats, since dot eventually feeds through to the underlying BLAS routine which will need this input type. All these conversions will mean plenty of temporary storage, which needs to be garbage collected at some point, and this will probably be the source of the varying timings (90% of the time, varied timings on the same code are the result of the garbage collector being triggered - and sometimes in quite unexpected ways).

So, there is probably several ways to improve the following, but my quick-and-dirty version of your function looks like this:

function cauchyproduct(L::AbstractVector{<:Number}, R::AbstractVector{<:Number})
    length(L) != length(R) && error("Length mismatch in inputs")
    N = length(L)
    prodterm = zeros(1,2*N-1)
    R = flipdim(R, 1)
    for n=1:N
        prodterm[n] = dot(view(L, 1:n), view(R, N-n+1:N))
    end
    for n = 1:N-1
        prodterm[N+n] = dot(view(L, n+1:N), view(R, 1:N-n))
    end
    return prodterm
end

Note, I flip R before the loop so the memory doesn't need to be re-ordered over and over within the loop. This was no doubt contributing to your strange garbage collection issues. Then, applying your test (I think it is a better idea to move array generation inside the loop in case some clever caching issue throws off timings):

testLength = 10000
for j = 1:20
    goodL = rand(testLength);
    goodR = rand(testLength);
    @time cauchyproduct(goodL,goodR);
end

we get something like this:

  0.105550 seconds (78.19 k allocations: 3.935 MiB, 2.91% gc time)
  0.022421 seconds (40.00 k allocations: 2.060 MiB)
  0.022527 seconds (40.00 k allocations: 2.060 MiB)
  0.022333 seconds (40.00 k allocations: 2.060 MiB)
  0.021568 seconds (40.00 k allocations: 2.060 MiB)
  0.021837 seconds (40.00 k allocations: 2.060 MiB)
  0.022155 seconds (40.00 k allocations: 2.060 MiB)
  0.022071 seconds (40.00 k allocations: 2.060 MiB)
  0.021720 seconds (40.00 k allocations: 2.060 MiB)
  0.024774 seconds (40.00 k allocations: 2.060 MiB, 9.13% gc time)
  0.021714 seconds (40.00 k allocations: 2.060 MiB)
  0.022066 seconds (40.00 k allocations: 2.060 MiB)
  0.021815 seconds (40.00 k allocations: 2.060 MiB)
  0.021819 seconds (40.00 k allocations: 2.060 MiB)
  0.021928 seconds (40.00 k allocations: 2.060 MiB)
  0.021795 seconds (40.00 k allocations: 2.060 MiB)
  0.021837 seconds (40.00 k allocations: 2.060 MiB)
  0.022285 seconds (40.00 k allocations: 2.060 MiB)
  0.021380 seconds (40.00 k allocations: 2.060 MiB)
  0.023828 seconds (40.00 k allocations: 2.060 MiB, 6.91% gc time)

The first iteration is measuring compile time, rather than runtime, and so should be ignored (if you don't know what I mean by this then check the performance tips section of the official docs). As you can see, the remaining iterations are much faster, and quite stable.


问:
SQL where condition in Codeigniter
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?</p>

```<code>$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();
</code>```

答:
Try this:</p>

```<code>$array = "('$checkindate' BETWEEN `checkin_date` AND `checkout_date`) OR  ('$checkoutdate' BETWEEN `checkin_date` AND `checkout_date`) OR (`checkin_date` > '$checkindate' AND `checkout_date` < '$checkoutdate')";
    $this->db->select('*');
    $this->db->from('igc_room_booking');
    $this->db->where('delete_status', 0);
    $this->db->where('cancel_status', 0);
    $this->db->where('room_id', $val->room_id);
    $this->db->where($array);
    $bookingss = $this->db->get()->result();
</code>```

Title: SQL where condition in Codeigniter

Body:
I want to check if booking exists or not.  I have checkin date, checkout date, and room number. I tried below query but it gives all the data which is not of that room id also. What am I doing wrong?

$array = array('checkin_date' => $checkin, 'checkout_date' => $checkin);
$array1 = array('checkin_date >' => $checkin, 'checkout_date <' => $checkin);
$array2 = array('checkin_date <' => $checkin, 'checkout_date >' => $checkin);
$array3 = array('checkin_date <' => $checkin, 'checkout_date <' => $checkin);
$array4 = array('checkin_date >=' => $checkin, 'checkout_date <=' => $checkin);
$array5 = array('checkin_date >=' => $checkout, 'checkout_date <=' => $checkout);

$this->db->select('*');
$this->db->from('igc_room_booking');
$this->db->where('delete_status', 0);
$this->db->where('cancel_status', 0);
$this->db->where('room_id', $val->room_id);
$this->db->where($array);
$this->db->or_where($array2);
$this->db->or_where($array3);
$this->db->or_where($array);
$this->db->or_where($array4);
$this->db->or_where($array5);
$bookingss = $this->db->get()->result();

Body:
Try this:

$array = "('$checkindate' BETWEEN `checkin_date` AND `checkout_date`) OR  ('$checkoutdate' BETWEEN `checkin_date` AND `checkout_date`) OR (`checkin_date` > '$checkindate' AND `checkout_date` < '$checkoutdate')";
    $this->db->select('*');
    $this->db->from('igc_room_booking');
    $this->db->where('delete_status', 0);
    $this->db->where('cancel_status', 0);
    $this->db->where('room_id', $val->room_id);
    $this->db->where($array);
    $bookingss = $this->db->get()->result();


问:
Locating resource for OpenMP + MPI application
I'm currently developing a hybrid program using c++. I'm using both openMP and MPI. However, I don't know how to specify the number of processors and threads for my job. Let's say that I want to use 5 nodes and I want one MPI processor on each node and I want 24 threads per node.

This is how I submit my_job right now:

```<code>qsub -l select=5:ncpus=24:mpiprocs=5 -l place=scatter:exclhost my_job
</code>```

and on my_job script, I'm doing this

```<code>#PBS -l select=5:ncpus=24:mpiprocs=5
export OMP_NUM_THREADS=24
mpic++ -O3 myprogram.cpp -o out -fopenmp -lquadmath -std=gnu++11
mpirun -n 5 ./out
</code>```

However, the performance is very slow, which make me think that there might be a problem with how I'm locating my resources.

Any suggestion?

答:
Per https://www2.cisl.ucar.edu/resources/computational-systems/cheyenne/running-jobs/pbs-pro-job-script-examples that would be</p>

```<code>#PBS -l select=5:ncpus=24:mpiprocs=1:ompthreads=24
</code>```

Body:
I'm currently developing a hybrid program using c++. I'm using both openMP and MPI. However, I don't know how to specify the number of processors and threads for my job. Let's say that I want to use 5 nodes and I want one MPI processor on each node and I want 24 threads per node.

This is how I submit my_job right now:

qsub -l select=5:ncpus=24:mpiprocs=5 -l place=scatter:exclhost my_job

and on my_job script, I'm doing this

#PBS -l select=5:ncpus=24:mpiprocs=5
export OMP_NUM_THREADS=24
mpic++ -O3 myprogram.cpp -o out -fopenmp -lquadmath -std=gnu++11
mpirun -n 5 ./out

However, the performance is very slow, which make me think that there might be a problem with how I'm locating my resources.

Any suggestion?

Body:
Per https://www2.cisl.ucar.edu/resources/computational-systems/cheyenne/running-jobs/pbs-pro-job-script-examples that would be

#PBS -l select=5:ncpus=24:mpiprocs=1:ompthreads=24


问:
Is this is the correct way to create a user in postgresql?
Since I'm testing the sql script I first drop the instance and users with:

```<code>REVOKE CONNECT ON DATABASE online_dev FROM dbIdsManager;
DROP USER dbIdsManager;
</code>```

Then I create the database online_dev and the tables.
After this I create the user like this:

```<code>CREATE USER dbIdsManager WITH PASSWORD 'abc123' VALID UNTIL 'infinity';
ALTER ROLE dbIdsManager IN DATABASE online_dev SET search_path TO map_id_db;
GRANT CONNECT ON DATABASE online_dev TO dbIdsManager;
GRANT USAGE ON SCHEMA map_id_db TO dbIdsManager;
GRANT SELECT ON ALL TABLES IN SCHEMA map_id_db TO dbIdsManager;
</code>```

And everytime I try to login with that user it's says that the password is not correct.

```<code>FATAL: password authentication failed for user "dbIdsManager"
FATAL: password authentication failed for user "dbIdsManager"

Please enter the password for the user 'dbIdsManager' to connect the server - "dbtest"
</code>```

There are posts that it might be an error with the 'valid until' but I already add the 'infinity' validation.

Any ideas of what it might be the problem?

The server is an instance of aws rdbms.

答:
The permission setting is not right.

My solution is following,

```<code>CREATE USER dbIdsManager WITH PASSWORD 'abc123' VALID UNTIL 'infinity' LOGIN;
</code>```

If not specified LOGIN or NOLOGIN, NOLOGIN is default.

Body:
Since I'm testing the sql script I first drop the instance and users with:

REVOKE CONNECT ON DATABASE online_dev FROM dbIdsManager;
DROP USER dbIdsManager;

Then I create the database online_dev and the tables.
After this I create the user like this:

CREATE USER dbIdsManager WITH PASSWORD 'abc123' VALID UNTIL 'infinity';
ALTER ROLE dbIdsManager IN DATABASE online_dev SET search_path TO map_id_db;
GRANT CONNECT ON DATABASE online_dev TO dbIdsManager;
GRANT USAGE ON SCHEMA map_id_db TO dbIdsManager;
GRANT SELECT ON ALL TABLES IN SCHEMA map_id_db TO dbIdsManager;

And everytime I try to login with that user it's says that the password is not correct.

FATAL: password authentication failed for user "dbIdsManager"
FATAL: password authentication failed for user "dbIdsManager"

Please enter the password for the user 'dbIdsManager' to connect the server - "dbtest"

There are posts that it might be an error with the 'valid until' but I already add the 'infinity' validation.

Any ideas of what it might be the problem?

The server is an instance of aws rdbms.

Body:
The permission setting is not right.

My solution is following,

CREATE USER dbIdsManager WITH PASSWORD 'abc123' VALID UNTIL 'infinity' LOGIN;

If not specified LOGIN or NOLOGIN, NOLOGIN is default.


问:
android - Notification not playing custom sound
I'm trying to show an notification with custom sound. I used firebase console to throw an notification.

Here is my code:

```<code>    Notification notification = builder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(pendingIntent)
            .setSound(notificationSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeInMilliSec(timeStamp))
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), icon))
            .setContentText(message).build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID_SMALL_IMAGE, notification);

Here notificationSound = Uri.parse(SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/raw/notification");

I placed my notification.mp3 file here: res/raw/notification.
</code>```

I got the notification as expected but I didn't get any notification sound.

Here are the logs when I get notification:

```<code>11-14 10:08:31.200 16509-16509/com.hago.ntr D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
11-14 10:08:31.220 16509-16509/com.hago.ntr D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
11-14 10:08:31.272 16509-16509/com.hago.ntr I/FA: App measurement is starting up, version: 9683
11-14 10:08:31.272 16509-16509/com.hago.ntr I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
11-14 10:08:31.272 16509-16509/com.hago.ntr D/FA: Debug-level message logging enabled
11-14 10:08:31.272 16509-16509/com.hago.ntr D/FA: AppMeasurement singleton hash: 266608187
11-14 10:08:31.299 16509-16509/com.hago.ntr V/FA: Collection enabled
11-14 10:08:31.299 16509-16509/com.hago.ntr V/FA: App package, google app id: com.hago.ntr, 1:317122300577:android:6c0b483c0a4e3f40
11-14 10:08:31.299 16509-16509/com.hago.ntr I/FA: To enable faster debug mode event logging run:
                                                adb shell setprop firebase.analytics.debug-mode com.hago.ntr
11-14 10:08:31.343 16509-16509/com.hago.ntr V/FA: Registered activity lifecycle callback
11-14 10:08:31.345 16509-16509/com.hago.ntr I/FirebaseInitProvider: FirebaseApp initialization successful
11-14 10:08:31.347 16509-16509/com.hago.ntr I/InstantRun: starting instant run server: is main process
11-14 10:08:31.354 16509-16552/com.hago.ntr V/FA: Using measurement service
11-14 10:08:31.368 16509-16552/com.hago.ntr V/FA: Connecting to remote service
11-14 10:08:31.459 16509-16552/com.hago.ntr I/FA: Tag Manager is not found and thus will not be used
11-14 10:08:31.465 16509-16552/com.hago.ntr D/FA: Logging event (FE): _nr, Bundle[{_o=fcm, _ndt=0, _nmt=1510634308, _nmid=7758633434821297510}]
11-14 10:08:31.468 16509-16552/com.hago.ntr V/FA: Using measurement service
11-14 10:08:31.468 16509-16552/com.hago.ntr V/FA: Connection attempt already in progress
11-14 10:08:31.473 16509-16552/com.hago.ntr D/FA: Connected to remote service
11-14 10:08:31.473 16509-16552/com.hago.ntr V/FA: Processing queued up service tasks: 2
11-14 10:08:36.494 16509-16552/com.hago.ntr V/FA: Inactivity, disconnecting from the service
</code>```

What might be the issue ?

答:
Try to add this code below Pending intent

```<code>     try {
            Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.fileName);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), defaultSoundUri);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

For more please follow below links

https://github.com/firebase/quickstart-android/tree/master/messaging

https://firebase.google.com/docs/cloud-messaging/android/client

Also if you want to manage or customize notifications bar please follow below link

https://developer.android.com/guide/topics/ui/notifiers/notifications.html

Body:
I'm trying to show an notification with custom sound. I used firebase console to throw an notification.

Here is my code:

    Notification notification = builder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(pendingIntent)
            .setSound(notificationSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeInMilliSec(timeStamp))
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), icon))
            .setContentText(message).build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID_SMALL_IMAGE, notification);

Here notificationSound = Uri.parse(SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/raw/notification");

I placed my notification.mp3 file here: res/raw/notification.

I got the notification as expected but I didn't get any notification sound.

Here are the logs when I get notification:

11-14 10:08:31.200 16509-16509/com.hago.ntr D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
11-14 10:08:31.220 16509-16509/com.hago.ntr D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
11-14 10:08:31.272 16509-16509/com.hago.ntr I/FA: App measurement is starting up, version: 9683
11-14 10:08:31.272 16509-16509/com.hago.ntr I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
11-14 10:08:31.272 16509-16509/com.hago.ntr D/FA: Debug-level message logging enabled
11-14 10:08:31.272 16509-16509/com.hago.ntr D/FA: AppMeasurement singleton hash: 266608187
11-14 10:08:31.299 16509-16509/com.hago.ntr V/FA: Collection enabled
11-14 10:08:31.299 16509-16509/com.hago.ntr V/FA: App package, google app id: com.hago.ntr, 1:317122300577:android:6c0b483c0a4e3f40
11-14 10:08:31.299 16509-16509/com.hago.ntr I/FA: To enable faster debug mode event logging run:
                                                adb shell setprop firebase.analytics.debug-mode com.hago.ntr
11-14 10:08:31.343 16509-16509/com.hago.ntr V/FA: Registered activity lifecycle callback
11-14 10:08:31.345 16509-16509/com.hago.ntr I/FirebaseInitProvider: FirebaseApp initialization successful
11-14 10:08:31.347 16509-16509/com.hago.ntr I/InstantRun: starting instant run server: is main process
11-14 10:08:31.354 16509-16552/com.hago.ntr V/FA: Using measurement service
11-14 10:08:31.368 16509-16552/com.hago.ntr V/FA: Connecting to remote service
11-14 10:08:31.459 16509-16552/com.hago.ntr I/FA: Tag Manager is not found and thus will not be used
11-14 10:08:31.465 16509-16552/com.hago.ntr D/FA: Logging event (FE): _nr, Bundle[{_o=fcm, _ndt=0, _nmt=1510634308, _nmid=7758633434821297510}]
11-14 10:08:31.468 16509-16552/com.hago.ntr V/FA: Using measurement service
11-14 10:08:31.468 16509-16552/com.hago.ntr V/FA: Connection attempt already in progress
11-14 10:08:31.473 16509-16552/com.hago.ntr D/FA: Connected to remote service
11-14 10:08:31.473 16509-16552/com.hago.ntr V/FA: Processing queued up service tasks: 2
11-14 10:08:36.494 16509-16552/com.hago.ntr V/FA: Inactivity, disconnecting from the service

What might be the issue ?

Body:
Try to add this code below Pending intent

     try {
            Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.fileName);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), defaultSoundUri);
            r.play();
        } catch (Exception e) {
            e.printStackTrace();
        }

For more please follow below links

https://github.com/firebase/quickstart-android/tree/master/messaging

https://firebase.google.com/docs/cloud-messaging/android/client

Also if you want to manage or customize notifications bar please follow below link

https://developer.android.com/guide/topics/ui/notifiers/notifications.html


问:
How can I check whether an array is null / empty?
I have an int array which has no elements and I'm trying to check whether it's empty.

For example, why is the condition of the if-statement in the code below never true?

```<code>int[] k = new int[3];

if (k == null) {
    System.out.println(k.length);
}
</code>```

答:
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null. </p>

```<code>int[] k = new int[3];
if(k.length == 0)
{
//do something
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an int array which has no elements and I'm trying to check whether it's empty.

For example, why is the condition of the if-statement in the code below never true?

int[] k = new int[3];

if (k == null) {
    System.out.println(k.length);
}

Body:
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.

int[] k = new int[3];
if(k.length == 0)
{
//do something
}


问:
Uploading image in ASP.NET Boilerplate
When posting an image, HttpContext.Current.Request is null.

Is there any simple way to achieve this? I am using dropzone.js on client side.

Project is Angular with Web API (ASP.NET Core 2.0) template.

```<code>[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
    HttpResponseMessage response = new HttpResponseMessage();
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
    }
    return response;
}
</code>```

答:
You cannot use app service for uploading image.

Just create a new controller and upload your file.

Return to client the unique filename that you generated in server.

When user saves the whole entity, send the unique filename to server again.

You can derive your controller from AbpController.

https://aspnetboilerplate.com/Pages/Documents/AspNet-Core?searchKey=AbpController

https://aspnetboilerplate.com/Pages/Documents/MVC-Controllers?searchKey=AbpController

Title: Uploading image in ASP.NET Boilerplate

Body:
When posting an image, HttpContext.Current.Request is null.

Is there any simple way to achieve this? I am using dropzone.js on client side.

Project is Angular with Web API (ASP.NET Core 2.0) template.

[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
    HttpResponseMessage response = new HttpResponseMessage();
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
    }
    return response;
}


问:
How to return a single FirebaseObjectObservable from a FirebaseListObservable query
I'm building a game using Angular 4 and Firebase Realtime DB.  I have a Firebase DB layout like this:

```<code>FB -> player_list-> -KyagqWEM-cqUoppGe_x
                        id:33061
                        name:Joe
                   -KyadrWSD-aqUeedBv_w
                        id:22037
                        name:Cara
</code>```

In my app I'd like to create a FirebaseObjectObservable on a specific player, Joe in this example.  In my Ng Database Service I've created a method that looks like this:

```<code>getPlayerFromId(playerId: number): FirebaseListObservable<Player[]> {
  this.player = this.database.list(this.playerBasePath, {
    query: {
      orderByChild: 'id',
      equalTo: playerId,
      limitToFirst: 1
    }
  })
  return this.player;
}
</code>```

A query seems to be the best way to find a specific node in my Firebase database, unfortunately queries seem to only return a list, even if that list is only one item in length.  In my component It's fairly easy to get the one player object, with code like this:

```<code>  getPlayer(playerId: number){
    this.studentService.getPlayerFromId(playerId)
    .subscribe(data => {
      this.player = data[0];
    })
  }
</code>```

Is there a more elegant way to return one FirebaseObjectObservable from a list query?  I've tried map and filter, but apparently those are not supported by FirebaseListObservable.

答:
```<code>    Try with forEach but as this.player will get its data asynchronously from firebase

this.player= this.af.database.list(this.playerBasePath);
        this.player.forEach(element => {
            console.log(element);
        });

    Above code you will be iterating before the data actually there. So for this
    you can add the option

     preserveSnapshot: true

        this.studentService.getPlayerFromId(playerId, { preserveSnapshot: true})
            .subscribe(snapshots=>{
                snapshots.forEach(snapshot => {
                  console.log(snapshot.key, snapshot.val());
                });
            })
</code>```

Body:
I'm building a game using Angular 4 and Firebase Realtime DB.  I have a Firebase DB layout like this:

FB -> player_list-> -KyagqWEM-cqUoppGe_x
                        id:33061
                        name:Joe
                   -KyadrWSD-aqUeedBv_w
                        id:22037
                        name:Cara

In my app I'd like to create a FirebaseObjectObservable on a specific player, Joe in this example.  In my Ng Database Service I've created a method that looks like this:

getPlayerFromId(playerId: number): FirebaseListObservable<Player[]> {
  this.player = this.database.list(this.playerBasePath, {
    query: {
      orderByChild: 'id',
      equalTo: playerId,
      limitToFirst: 1
    }
  })
  return this.player;
}

A query seems to be the best way to find a specific node in my Firebase database, unfortunately queries seem to only return a list, even if that list is only one item in length.  In my component It's fairly easy to get the one player object, with code like this:

  getPlayer(playerId: number){
    this.studentService.getPlayerFromId(playerId)
    .subscribe(data => {
      this.player = data[0];
    })
  }

Is there a more elegant way to return one FirebaseObjectObservable from a list query?  I've tried map and filter, but apparently those are not supported by FirebaseListObservable.


问:
Laravel store session to redis
I want to store the session to redis in Laravel.

I was do :
- Change the session driver into 'redis'
- Set my redis server
- and then use this code to store $req->session()->put($email, json_encode($user));

The code was run successfully. And it was store to redis.
But, I just simply add the code to 1 function.

Why the other function like example testing()/check(), also setex to redis? I don't even put the code into that function.

答:
You can store data in Redis this way :-</p>

```<code>use Illuminate\Support\Facades\Redis; // add in top of controler before class
      or
use Redis;
//put this in function
$redis = new Redis();
$redis->set('boo','Have beer and relax!')
$redis->get('boo');
</code>```

Title: Laravel store session to redis

Body:
You can store data in Redis this way :-

use Illuminate\Support\Facades\Redis; // add in top of controler before class
      or
use Redis;
//put this in function
$redis = new Redis();
$redis->set('boo','Have beer and relax!')
$redis->get('boo');


问:
Is It Possible to Create a Vertical Meter With HTML5?
Normally, if I create:

```<code><meter value="30" max="100">Low</meter>
</code>```

I'll end up with a horizontal meter/bar if viewed on a browser that supports the html5 meter element.

Is it possible to create a vertical meter with html5?

The only solution I've been able to come up with so far is using CSS3 rotation (transform).

答: Transform is the answer. The whole point of meter is that it's a semantic, not a presentational element and you should be able to style it however you want with CSS></p>

Body:
Normally, if I create:

<meter value="30" max="100">Low</meter>

I'll end up with a horizontal meter/bar if viewed on a browser that supports the html5 meter element.

Is it possible to create a vertical meter with html5?

The only solution I've been able to come up with so far is using CSS3 rotation (transform).


问:
Java connection to a SQL Server Database: Login failed for user 'sa'
I am trying to connect to a database that I created using SQL Server 2012, but I keep getting an error. This is the code for the connection:

```<code>Driver d = (Driver)Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=Tema6;user=sa;password=123456";
        java.sql.Connection con = DriverManager.getConnection(DB_URL);
</code>```

And this is the error that I am getting:

```<code>Login failed for user 'sa'. ClientConnectionId:e6335e64-ca68-4d72-8939-5b7ded951424
</code>```

I have enabled TCP/IP protocol from SQL Server Config, I am sure that the 'sa' account is enabled and that the password is correct. Can anyone help me, please?

EDIT: This is the entire stacktrace.

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. ClientConnectionId:e6335e64-ca68-4d72-8939-5b7ded951424
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Connection.main(Connection.java:12)
</code>```

EDIT2: After replacing the driver with jTDS:

```<code>java.sql.SQLException: Login failed for user 'sa'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2893)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2335)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:609)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:369)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:183)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Connection.main(Connection.java:19)
</code>```

答: Go to sql server, select user properties and change server roles to sysadmin solved the issue.</p>

Body:
I am trying to connect to a database that I created using SQL Server 2012, but I keep getting an error. This is the code for the connection:

Driver d = (Driver)Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String DB_URL = "jdbc:sqlserver://localhost:1433;databaseName=Tema6;user=sa;password=123456";
        java.sql.Connection con = DriverManager.getConnection(DB_URL);

And this is the error that I am getting:

Login failed for user 'sa'. ClientConnectionId:e6335e64-ca68-4d72-8939-5b7ded951424

I have enabled TCP/IP protocol from SQL Server Config, I am sure that the 'sa' account is enabled and that the password is correct. Can anyone help me, please?

EDIT: This is the entire stacktrace.

com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. ClientConnectionId:e6335e64-ca68-4d72-8939-5b7ded951424
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:254)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:84)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2908)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2220)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1326)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Connection.main(Connection.java:12)

EDIT2: After replacing the driver with jTDS:

java.sql.SQLException: Login failed for user 'sa'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2893)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2335)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:609)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:369)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:183)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Connection.main(Connection.java:19)


问:
Duration (Year Conversion)
I am new in Redshift. How do I convert to years/months.

Year(Varchar): 1 year 6 months.

Expected Result(Integer): 1.5

答:
As far as my understanding this is similar to the one which I answered in a different SO question here:
https://stackoverflow.com/a/47277430/3259044</p>

Title: Duration (Year Conversion)


问:
VBA to input formula in code
I am trying to convert the below excel formula into a vba code for macro but not sure what is the syntax to input the same in code
How to write a VBA code for the below formula

```<code>=CONCATENATE(A12,REPT(" ",(10-LEN(A12))),B12,REPT(" ",215))
</code>```

答:
You can execute the worksheet formula in VBA:

```<code>Sub qwerty()
    x = Evaluate("CONCATENATE(A12,REPT("" "",(10-LEN(A12))),B12,REPT("" "",215))")
    MsgBox x
End Sub
</code>```

Title: VBA to input formula in code

Body:
I am trying to convert the below excel formula into a vba code for macro but not sure what is the syntax to input the same in code
How to write a VBA code for the below formula

=CONCATENATE(A12,REPT(" ",(10-LEN(A12))),B12,REPT(" ",215))

Body:
You can execute the worksheet formula in VBA:

Sub qwerty()
    x = Evaluate("CONCATENATE(A12,REPT("" "",(10-LEN(A12))),B12,REPT("" "",215))")
    MsgBox x
End Sub


问:
How do I fetch my own Instagram media feed
I have a use case that Instagram does not seem to acknowledge. I am hoping that someone else has an idea for what I can do.

The website that I am maintaining has been using the API endpoint:
https://www.instagram.com/anyUser/media/

And I am aware that Instagram has recently stopped supporting this endpoint. So I am looking for a replacement.

My use case is that I do not want to allow the users of my website to authenticate and browse their own photos. Instead I want to show only the latest 20 images that "I" (aka my employer) have posted, one at a time in a loop.

Instagram's API documentation seems to be entirely focused on the use case of allowing users to authenticate and share their photos.

Is there an API call that will return the last 20 images that I have posted?

From its specs, the Sandbox will work fine for me, I cannot find a way to register with Instagram that does not require me to build a user authentication work flow that will NEVER be used.

答:
You would want to use self feed endpoint.

https://www.instagram.com/developer/endpoints/users/#get_users_self

https://api.instagram.com/v1/users/self/?access_token=ACCESS-TOKEN


问:
Oracle 12c - which index should be used for a table with partitions and sub-partitions
I have a table of 500M records in Oracle 12c.
Table is partitioned per 1 varchar column and sub-partitioned per other varchar column.

What indexes should be used with queries that use these 2 columns in Where clause?

I am assuming local partitioned indexes are the best choice but wanted to get more insight on when is this a case and how is the best to create them?

答:
Oracle is capable of partition pruning, meaning that if your query has the partition key column(s) in the where clause, Oracle is smart enough to only query those partitions that are relevant. In such case a local partitioned index is more beneficial because it is "local to the partition", i.e. the index is also partitioned the same way and Oracle will only read the relevant index entries for those partition that are relevant.

If however you have a query that doesn't have the partition key column(s) in the where clause Oracle can't apply partition pruning and will have no other choice but to scan all local partitioned indexes or, worst case, the entire table for the data. This is where a global partitioned index will come in handy on those columns that are in the where clause. In that case Oracle creates an index over those columns across partitions and knows exactly which records to read from which partitions that qualify for the where clause of the statement.


问:
Finding a particular expression in R
```<code>afn(a)
1       pwr_p08_mgr1
2       pwr_p08_asd
3       pwr_p11_mgr1
4       pwr_p11_mgr4
5       pwr_p10_asd
6       scribbles
7       abc_de_p11_wer
8       red-p08
</code>```

<p>I have a function which will return a list of elements like what I labeled above. I want to repeat this for all possible values of a. There are 150 different values. For each of the values I want it to return 3 things. They can be 3 separate functions or all in 1 function. I want to get the periods present and count for each value of a. For the example shown, the period 08 appears 3 times, 10 once, and 11 3 times.  The other thing I need is the fraction of values of a (there are 150) for which each of the periods(01-50) are present. </p>

答:
This will work, if your character vector has this pattern: "XXX_p[0-9]XXX"
For example: The pattern for this string 'pwr_p08_mgr1' is 'XXX_X08_XXX1'. Numbers may appear before or after the first underscore, and the first numbered value will be taken as the return value.</p>

```<code>afn_a <-  c( 'pwr_p08_mgr1', 'pwr_p08_asd', 'pwr_p11_mgr1',
             'pwr_p11_mgr4', 'pwr_p10_asd', 'scribbles',
             'abc_de_p11_wer', 'red-p08')

mytab <- table( na.omit( unlist( lapply( strsplit( gsub( "[^0-9_]", "", afn_a), split = "_"),
        function( x ){
          x[ x != "" ][1]
        }) ) ) )
mytab
# 08 10 11
# 3  1  3
mytab/150
# 08          10          11
# 0.020000000 0.006666667 0.020000000
</code>```

Title: Finding a particular expression in R

Body:
afn(a)
1       pwr_p08_mgr1
2       pwr_p08_asd
3       pwr_p11_mgr1
4       pwr_p11_mgr4
5       pwr_p10_asd
6       scribbles
7       abc_de_p11_wer
8       red-p08

I have a function which will return a list of elements like what I labeled above. I want to repeat this for all possible values of a. There are 150 different values. For each of the values I want it to return 3 things. They can be 3 separate functions or all in 1 function. I want to get the periods present and count for each value of a. For the example shown, the period 08 appears 3 times, 10 once, and 11 3 times.  The other thing I need is the fraction of values of a (there are 150) for which each of the periods(01-50) are present.

Body:
This will work, if your character vector has this pattern: "XXX_p[0-9]XXX"
For example: The pattern for this string 'pwr_p08_mgr1' is 'XXX_X08_XXX1'. Numbers may appear before or after the first underscore, and the first numbered value will be taken as the return value.

afn_a <-  c( 'pwr_p08_mgr1', 'pwr_p08_asd', 'pwr_p11_mgr1',
             'pwr_p11_mgr4', 'pwr_p10_asd', 'scribbles',
             'abc_de_p11_wer', 'red-p08')

mytab <- table( na.omit( unlist( lapply( strsplit( gsub( "[^0-9_]", "", afn_a), split = "_"),
        function( x ){
          x[ x != "" ][1]
        }) ) ) )
mytab
# 08 10 11
# 3  1  3
mytab/150
# 08          10          11
# 0.020000000 0.006666667 0.020000000


问:
How to convert binary file into readable format on linux server
I am trying to convert binary file into readable format but unable to do so, please suggest how it could be achieved.</p>

```<code>$ file test.docx
test.docx: Microsoft Word 2007+
$ file -i test.docx
test.docx: application/msword; charset=binary
$

>>> raw = codecs.open('test.docx', encoding='ascii').readlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 694, in readlines
    return self.reader.readlines(sizehint)
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 603, in readlines
    data = self.read()
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 492, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 18: ordinal not in range(128)
</code>```

答:
you'll have to read it in binary mode :</p>

```<code>import binascii
with open('test.docx', 'rb') as f: # 'rb' stands for read binary
    hexdata = binascii.hexlify(f.read()) # convert to hex
    print(hexdata)
</code>```

Body:
I am trying to convert binary file into readable format but unable to do so, please suggest how it could be achieved.

$ file test.docx
test.docx: Microsoft Word 2007+
$ file -i test.docx
test.docx: application/msword; charset=binary
$

>>> raw = codecs.open('test.docx', encoding='ascii').readlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 694, in readlines
    return self.reader.readlines(sizehint)
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 603, in readlines
    data = self.read()
  File "/home/Python/installPath/lib/python2.7/codecs.py", line 492, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 18: ordinal not in range(128)

Body:
you'll have to read it in binary mode :

import binascii
with open('test.docx', 'rb') as f: # 'rb' stands for read binary
    hexdata = binascii.hexlify(f.read()) # convert to hex
    print(hexdata)


问:
Sparse array in CUDA or OpenCL
I have a large array (say 512K elements), GPU resident, where only a small fraction of elements (say 5K randomly distributed elements - set S) needs to be processed. The algorithm to find out which elements belong to S is very efficient, so I can easily create an array A of pointers or indexes to elements from set S.

What is the most efficient way to run a CUDA or OpenCL kernel only over elements from S? Can I run a kernel over array A? All examples I've seen so far deal with contiguous 1D, 2D, or 3D arrays. Is there any problem with introducing one layer of indirection?

答:
No problem at all with the one level of indirection.  I use that a fair amount in my own CUDA code.  Is the set S likely to remain static over time?  If so, it may very well be worth generating the lookup A like you said.

Also, texture memory will be your friend in providing cache locality.  The type of texture you use (1D, 2D, or 3D) will depend on your problem.

Title: Sparse array in CUDA or OpenCL


问:
Upgrade/install php7 on google compute cloud instance
I'm trying to upgrade my google cloud compute instance with the latest version of php.

It is currently is running debian9/php5/apache2/mysql14 and I want to get it to php7.

I've tried all the simple apt-get update upgrade install php7 etc and no packages are found.

E: Unable to locate package php7.0

E: Couldn't find any package by regex 'php7.0'

E: Unable to locate package libapache2-mod-php7.0

E: Couldn't find any package by regex 'libapache2-mod-php7.0'

E: Unable to locate package php7.0-mysql

E: Couldn't find any package by regex 'php7.0-mysql'

E: Unable to locate package php-common

E: Unable to locate package php7.0-cli

E: Couldn't find any package by regex 'php7.0-cli'

E: Unable to locate package php7.0-common

E: Couldn't find any package by regex 'php7.0-common'

E: Unable to locate package php7.0-json

E: Couldn't find any package by regex 'php7.0-json'

E: Unable to locate package php7.0-opcache

E: Couldn't find any package by regex 'php7.0-opcache'

E: Unable to locate package php7.0-readline

E: Couldn't find any package by regex 'php7.0-readline'

I've also tried 7.1 and 7.2 and same thing. Ideally the latest version of php but I'll take anything at this point.

Thanks for any help!

p.s. this will primarily run WordPress sites.

答:
Here's how to do it is anyone else needs to get this done. I'm on Debian 8 I mistakenly said 9 in my post.

Instructions: https://shiji.info/uncategorized/install-php7-on-debian-8-jessie-with-apache_99/

Before the final step of the instructions, I had to add these two steps:

sudo a2enmod proxy_fcgi setenvif

sudo a2enconf php7.0-fpm

Here are the instructions from the link above:

```<code>Install PHP7:
Since PHP7 is not included in any Debian official source list, we gonna use         the version compiled by Dotdeb.org, which is pretty widely used.

Add source:

sudo nano /etc/apt/sources.list
Add the following two lines to the end of the file:

deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all
If you server is far from US, try find the nearest mirror:         https://www.dotdeb.org/mirrors/

Get and Install GnuPG key:

wget https://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
Update packages again

sudo apt-get update
Install PHP7:

here is a list of available packages currently: (By the way, Swoole also     work with php7, use ‘pecl install swoole to install’)

php7.0-apcu       php7.0-dbg        php7.0-imagick    php7.0-memcached      php7.0-phpdbg     php7.0-sybase
php7.0-apcu-bc    php7.0-dev        php7.0-imap       php7.0-mongodb        php7.0-pspell     php7.0-tidy
php7.0-bz2        php7.0-enchant    php7.0-interbase  php7.0-msgpack    php7.0-readline   php7.0-xdebug
php7.0-cgi        php7.0-fpm        php7.0-intl       php7.0-mysql          php7.0-recode     php7.0-xmlrpc
php7.0-cli        php7.0-gd         php7.0-json       php7.0-odbc       php7.0-redis      php7.0-xsl
php7.0-common     php7.0-gmp        php7.0-ldap       php7.0-opcache    php7.0-snmp
php7.0-curl       php7.0-igbinary   php7.0-mcrypt     php7.0-pgsql      php7.0-sqlite3
Choose your list of mod, install with php

sudo apt-get install php7.0 php7.0-common php-pear #add your list of mods here
Install mod_php7 for Apache 2.4 and restart apache:

sudo apt-get install libapache2-mod-php7.0
sudo service apache2 restart
That’s it! Done!
</code>```

Body:
Here's how to do it is anyone else needs to get this done. I'm on Debian 8 I mistakenly said 9 in my post.

Instructions: https://shiji.info/uncategorized/install-php7-on-debian-8-jessie-with-apache_99/

Before the final step of the instructions, I had to add these two steps:

sudo a2enmod proxy_fcgi setenvif

sudo a2enconf php7.0-fpm

Here are the instructions from the link above:

Install PHP7:
Since PHP7 is not included in any Debian official source list, we gonna use         the version compiled by Dotdeb.org, which is pretty widely used.

Add source:

sudo nano /etc/apt/sources.list
Add the following two lines to the end of the file:

deb http://packages.dotdeb.org jessie all
deb-src http://packages.dotdeb.org jessie all
If you server is far from US, try find the nearest mirror:         https://www.dotdeb.org/mirrors/

Get and Install GnuPG key:

wget https://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg
Update packages again

sudo apt-get update
Install PHP7:

here is a list of available packages currently: (By the way, Swoole also     work with php7, use ‘pecl install swoole to install’)

php7.0-apcu       php7.0-dbg        php7.0-imagick    php7.0-memcached      php7.0-phpdbg     php7.0-sybase
php7.0-apcu-bc    php7.0-dev        php7.0-imap       php7.0-mongodb        php7.0-pspell     php7.0-tidy
php7.0-bz2        php7.0-enchant    php7.0-interbase  php7.0-msgpack    php7.0-readline   php7.0-xdebug
php7.0-cgi        php7.0-fpm        php7.0-intl       php7.0-mysql          php7.0-recode     php7.0-xmlrpc
php7.0-cli        php7.0-gd         php7.0-json       php7.0-odbc       php7.0-redis      php7.0-xsl
php7.0-common     php7.0-gmp        php7.0-ldap       php7.0-opcache    php7.0-snmp
php7.0-curl       php7.0-igbinary   php7.0-mcrypt     php7.0-pgsql      php7.0-sqlite3
Choose your list of mod, install with php

sudo apt-get install php7.0 php7.0-common php-pear #add your list of mods here
Install mod_php7 for Apache 2.4 and restart apache:

sudo apt-get install libapache2-mod-php7.0
sudo service apache2 restart
That’s it! Done!


问:
JavaScript: How we can call Document.evaluate method for getting result
I'm using below code for getting result value, but while executing it shows me an error message. (Failed to read the 'numberValue' property from 'XPathResult': The result type is not a number.)

Please take a look to get the value.

```<code>IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
                    var confirmationtext = "return document.evaluate( \"//*[@id='main-content']/div/div/div/h2/strong\",  document,  null,  XPathResult.STRING_TYPE,  null)";
                    var returnvalue = js.ExecuteScript(confirmationtext);
</code>```

答: You are using STRING_TYPE. Try NUMBER_TYPE if you are sure that it is always a number or ANY_TYPE but I would not recommend this.

Body:
I'm using below code for getting result value, but while executing it shows me an error message. (Failed to read the 'numberValue' property from 'XPathResult': The result type is not a number.)

Please take a look to get the value.

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
                    var confirmationtext = "return document.evaluate( \"//*[@id='main-content']/div/div/div/h2/strong\",  document,  null,  XPathResult.STRING_TYPE,  null)";
                    var returnvalue = js.ExecuteScript(confirmationtext);