id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527000
|
const arr = [
{
item1: 1,
item2: 2
},
{
item1: 3
}
]
In this example it would be an error, because in the second object item2 isn't set though it is present in the first object.
A: Yes, You can specify the schema of an object inside an array. Sample code
const Joi = require('joi');
const objectSchema = Joi.object({
item1: Joi.number().required(),
item2: Joi.number().required()
})
const arraySchema = Joi.array().items(objectSchema);
const invalidInput = [{
item1: 1,
item2: 2
}, {
item1: 1,
}];
const result = Joi.validate(invalidInput, arraySchema);
console.log(result);
The output will show an error
{ ValidationError: "value" at position 1 fails because [child "item2" fails because ["item2" is required]]
| |
doc_23527001
|
"bitcoin:address?label=mylabel&amount=12"
Then return value of bitcoin address, amount, label.
A: String bitcoinUrl = "bitcoin:address?label=mylabel&amount=12";
String address = bitcoinUrl.replaceAll("bitcoin:(.*)\\?.*", "$1");
String label = bitcoinUrl.replaceAll(".*label=(.*)&.*", "$1");
String amount = bitcoinUrl.replaceAll(".*amount=(.*)(&.*)?", "$1");
Log.d("bitcoin", address);
Log.d("bitcoin", label);
Log.d("bitcoin", amount);
Result
D/bitcoin﹕ address
D/bitcoin﹕ mylabel
D/bitcoin﹕ 12
| |
doc_23527002
|
Now i installed xampp with php 7.2.9
But C:\xampp>php -v shows PHP 5.6.25.
I want xampp with php 7.2 how can i achieve this.
my httpd.xampp.conf file has the following:
<IfModule env_module>
SetEnv MIBDIRS "C:/xampp/php/extras/mibs"
SetEnv MYSQL_HOME "\\xampp\\mysql\\bin"
SetEnv OPENSSL_CONF "C:/xampp/apache/bin/openssl.cnf"
SetEnv PHP_PEAR_SYSCONF_DIR "C:\\xampp\\php"
SetEnv PHPRC "C:\\xampp\\php"
SetEnv TMP "\\xampp\\tmp"
</IfModule>
| |
doc_23527003
|
file_1 = set()
file_2 = set()
with open('output.txt', 'r') as f:
for line in f:
file_1.add(line.strip())
with open('words_alpha.txt', 'r') as f:
for line in f:
file_2.add(line.strip())
same=(file_1 - file_2)
samelist=list(same)
with open('some_output_file.txt', 'w') as f:
for item in samelist:
f.write("%s\n" % item)
A: If you did use intersections at some point, your code should generally have worked. You can shorten it here and there:
with open('output.txt', 'r') as f1, open('words_alpha.txt', 'r') as f2:
file_1 = set(map(str.strip, f1))
file_2 = set(map(str.strip, f2))
same = file_1 & file_2
| |
doc_23527004
|
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState: Started");
String text = txtNumOfSplits.getText().toString();
int no = Integer.parseInt(text);
outState.putInt("count", no);
String num_of_splits = txtNumOfSplits.getText().toString();
//Convert String to Integer
int no2 = Integer.parseInt(num_of_splits);
outState.putInt("count", no2);
money = Double.parseDouble(edtBillAmount.getText().toString());
outState.putString("bill", String.valueOf(money));
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState: Started");
String text = txtNumOfSplits.getText().toString();
int no = savedInstanceState.getInt("count");
txtNumOfSplits.setText(no + "");
money = Double.parseDouble(edtBillAmount.getText().toString());
String money = savedInstanceState.getString("bill");
txtTotalBill.setText("Total Bill\n$" + finalAmount.toString());
}
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_20 = findViewById(R.id.btn_20);
btn_15 = findViewById(R.id.btn_15);
btn_10 =findViewById(R.id.btn_10);
btn_calculate = findViewById(R.id.btn_calculate);
btn_reset = findViewById(R.id.btn_reset);
txtBill = findViewById(R.id.txtBill);
txtTip = findViewById(R.id.txtTip);
txtSplit = findViewById(R.id.txtSplit);
txtRoundUp = findViewById(R.id.txtRoundUp);
txtNumOfSplits = findViewById(R.id.txtNumOfSplits);
txtTotalHeading = findViewById(R.id.txtTotalHeading);
txtTotalPerPerson = findViewById(R.id.txtTotalPerPerson);
txtTotalBill = findViewById(R.id.txtTotalBill);
txtTotalTip = findViewById(R.id.txtTotalTip);
txt_switch_error = findViewById(R.id.txt_switch_error);
switchRoundUp = (Switch) findViewById(R.id.switchRoundUp);
switchRoundDown = (Switch) findViewById(R.id.switchRoundDown);
edtBillAmount = findViewById(R.id.edtBillAmount);
horizontalLine = findViewById(R.id.horizontalLine);
A: Is that what you need? You can add double values parsing if necessary.
private static final String NUM_OF_SPLITS_KEY = "num_of_splits_key";
private static final String SELECTED_BUTTON_KEY = "selected_button_key";
private static final String TOTAL_PER_PERSON_KEY = "total_per_person_key";
private static final String TOTAL_BILL_KEY = "total_bill_key";
private static final String TOTAL_TIP_KEY = "total_tip_key";
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState: Started");
String textNumOfSplits = txtNumOfSplits.getText().toString();
int numOfSplits = Integer.parseInt(textNumOfSplits);
outState.putInt(NUM_OF_SPLITS_KEY, numOfSplits);
int selectedButtonId = 0;
if (btn_10.isSelected()) selectedButtonId = R.id.btn_10;
else if (btn_15.isSelected()) selectedButtonId = R.id.btn_15;
else if (btn_20.isSelected()) selectedButtonId = R.id.btn_20;
outState.putInt(SELECTED_BUTTON_KEY, selectedButtonId);
outState.putString(TOTAL_PER_PERSON_KEY, txtTotalPerPerson.getText().toString());
outState.putString(TOTAL_BILL_KEY, txtTotalBill.getText().toString());
outState.putString(TOTAL_TIP_KEY, txtTotalTip.getText().toString());
}
@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState: Started");
int numOfSplits = savedInstanceState.getInt(NUM_OF_SPLITS_KEY);
txtNumOfSplits.setText(numOfSplits + "");
String selectedButtonId = savedInstanceState.getInt(SELECTED_BUTTON_KEY);
if (selectedButtonId == btn_10.getId()) selectButton(btn_10);
else if (selectedButtonId == btn_15.getId()) selectButton(btn_15);
else if (selectedButtonId == btn_20.getId()) selectButton(btn_20);
String totalPerPerson = savedInstanceState.getString(TOTAL_PER_PERSON_KEY);
txtTotalPerPerson.setText(totalPerPerson);
String totalBill = savedInstanceState.getString(TOTAL_BILL_KEY);
txtTotalBill.setText(totalBill);
String totalTip = savedInstanceState.getString(TOTAL_TIP_KEY);
txtTotalTip.setText(totalTip);
}
private void selectButton(@NonNull Button button) {
button.setSelected(true);
}
| |
doc_23527005
|
What is the most elegant & performant way to define DAX formula calculating the values of a confusion matrix (TP, FP, FN, TN) so that another measure (e.g. Precision, Recall, F1) can make use of them?
Background
We are serving a classification model to users. Users have expressed desire to see how model evaluation metrics for a given subset of historical predictions.
My approach of one measure for each of the four values strikes me as inefficient...
Originally, I had a "What-If?" parameter for threshold so the "predicted" column was a measure and calculated columns/tables were ruled out.
I'm thinking there's a potential use case for SUMMARIZE()...
Current approach
True Positive := CALCULATE ( DISTINCTCOUNT ( Eval[id] ), Eval[actual] = 1, Eval[predicted] = 0 )
False Negative := CALCULATE ( DISTINCTCOUNT ( Eval[id] ), Eval[actual] = 1, Eval[predicted] = 0 )
False Negative := CALCULATE ( DISTINCTCOUNT ( Eval[id] ), Eval[actual] = 1, Eval[predicted] = 0 )
False Negative := CALCULATE ( DISTINCTCOUNT ( Eval[id] ), Eval[actual] = 1, Eval[predicted] = 0 )
Precision := DIVIDE([True Positive],[True Positive]+[False Positive])
Recall := DIVIDE([True Positive],[True Positive]+[False Negative])
F1 Score := 2*DIVIDE([Precision]*[Recall],[Precision]+[Recall])
Example source data
| id | predicted | actual |
|----|-----------|--------|
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 1 |
| 4 | 1 | 1 |
| 5 | 1 | 1 |
| 6 | 1 | 0 |
| 7 | 1 | 0 |
Source query
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSUTIA41idaCUjFJ4xlGcI5pmAWTCeKQrPDMqD6DNH8GIB", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [id = _t, predicted = _t, actual = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"id", Int64.Type}, {"predicted", Int64.Type}, {"actual", Int64.Type}})
in
#"Changed Type"
A: In general the most elegant and performing way is not a simple line of DAX, instead it is the general approach you used to design your data model.
The general rule for optimization is: move to back-end as much as possible.
Having said this, you will always find yourself in a trade-off between query performance and total memory of your data model. If total memory is not a problem, the best practice defined by Microsoft is to perform sum of individual columns.
Here is my approach:
1. Modify M-query to add 4 new columns we will use as field to aggregate. In general, do prefer modifying the data source instead of creating Calculated Columns. The resulting data source should be the following:
+----+-----------+--------+-------+-------+-------+-------+
| id | predicted | actual | TP_fl | TN_fl | FP_fl | FN_fl |
+----+-----------+--------+-------+-------+-------+-------+
| 1 | 0 | 0 | 0 | 1 | 0 | 0 |
| 2 | 0 | 0 | 0 | 1 | 0 | 0 |
| 3 | 0 | 1 | 0 | 0 | 0 | 1 |
| 4 | 1 | 1 | 1 | 0 | 0 | 0 |
| 5 | 1 | 1 | 1 | 0 | 0 | 0 |
| 6 | 1 | 0 | 0 | 0 | 1 | 0 |
| 7 | 1 | 0 | 0 | 0 | 1 | 0 |
+----+-----------+--------+-------+-------+-------+-------+
*Next, let's define the base measures:
[TP] := SUM('Eval'[TP_fl])
[TN] := SUM('Eval'[TN_fl])
[FP] := SUM('Eval'[FP_fl])
[FN] := SUM('Eval'[FN_fl])
Please note the following measures are based on the assumption Eval[Id] is the Primary Key of Eval table, as in your example.
*Finally, let's define complex measures which are calculated using above base measures:
[Precision] := VAR _TP = [TP] RETURN DIVIDE(_TP,_TP +[FP])
[Recall] := VAR _TP = [TP] RETURN DIVIDE(_TP,_TP + [FN])
[F1 Score] := VAR _TP = [TP] VAR _FP = [_FP] VAR FN_ = [_FN] VAR _PRECISION = DIVIDE(_TP,_TP +[FP]) VAR _RECALL = DIVIDE(_TP,_TP + [FN]) RETURN 2*DIVIDE(_PRECISION * _RECALL, _PRECISION + _RECALL)
Two important remarks:
*
*In complex measures, the use of variables is key to avoid wasting computing time.
*This optimal answer is against software engineering principle of redundant code. As explained there is always a trade-off. In this scenario, mathematical formulas won't change.
A: DISTINCTCOUNT is a bad performing operation. There is a chance to get performance by swapping it with an iterator such as SUMX, for example:
True Positive = SUMX ( Eval, IF ( Eval[predicted] && Eval[actual], 1 ) )
False Positive = SUMX ( Eval, IF ( Eval[predicted] && NOT Eval[actual], 1 ) )
True Negative = SUMX ( Eval, IF ( NOT Eval[predicted] && NOT Eval[actual], 1 ) )
False Negative = SUMX ( Eval, IF ( NOT Eval[predicted] && Eval[actual], 1 ) )
Edit: If you don't need the actual measure definition for the numbers in each confusion matrix quadrant, you may calculate the F1 score directly. Using variables is helpful for both readability and performance.
F1 Score =
VAR TruePositive = SUMX ( Eval, IF ( Eval[predicted] && Eval[actual], 1 ) )
VAR Selected = SUMX ( Eval, IF ( Eval[predicted], 1 ) )
VAR Relevant = SUMX ( Eval, IF ( Eval[actual], 1 ) )
VAR Precision = DIVIDE ( TruePositive, Selected )
VAR Recall = DIVIDE ( TruePositive, Relevant )
RETURN 2 * DIVIDE ( Precision * Recall, Precision + Recall )
| |
doc_23527006
|
Code:
import json
with open('data.json', encoding='utf-8') as meu_json:
aux = json.loads(meu_json.read())
# var = input('write the name: ')
# print('value in var: ' + var)
print(next(item for item in aux if item["name"] == "name to search or 'var' " ))
If I pass it directly (a name that I know exists in .json):
print(next(item for item in aux if item["name"] == "Charles Cote" ))
I get the desired output:
{'name': 'Charles Cote', 'parcel_id': '1303852', 'civic': 1216, 'street': 'Boulevard René-Lévesque Ouest', 'city': 'Québec'}
But I need to pass the name of the variable that holds what comes from the form ('var'):
print(next(item for item in aux if item["name"] == var ))
But my attempts only return to me:
NameError: name 'var' is not defined
Eu consegui fazer a pesquisa que eu precisava usando um for:
for sub in aux:
if sub["name"] == var:
saida = sub
print(saida)
Input:
write the name: Marie Fournier
Print confirming what you entered:
value in var: Marie Fournier
Output (Which is exactly what I needed):
{'name': 'Marie Fournier', 'parcel_id': '1532723', 'civic': 707, 'street': "Rue de l'Alsace", 'city': 'Québec'}
| |
doc_23527007
|
A simple example is (bear with me):
If I have a 5 column table (X,O,#,T,P) with X amount of rows and the csv format needs to be
X,,,,O,,,,T,P,,,,,,#,,,
Thanks!
A: you can export table data to csv file directly using mysql query
"SELECT column1, column2, column3 INTO OUTFILE '<filename>' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\' LINES TERMINATED BY '\r\n' FROM table1;"
A: One approach is you can place dummy columns in select query itself and then just create a CSV from the output:
select X,'','','',O,'','','',T,P,'','','','','',#,'','' from table_name; // this will by default give you your CSV structured output.
$fp = fopen('file_name', 'w');
fputcsv($fp, $values);
A: You can create lots of empty fields in the SELECT clause
SELECT X, '' AS col2, '' AS col3, '', O, '', '', '', '', T, P, '', '', '', '', '', '', `#`, '', ''
INTO OUTFILE 'filename.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM yourTable;
When reading the file back into the table, you can specify which fields of the file go into the table like this:
LOAD DATA INFILE 'filename.csv'
INTO TABLE yourTable
(X, @dummy, @dummy, @dummy, O, @dummy, @dummy, @dummy, @dummy, T, P, @dummy, @dummy, @dummy, @dummy, @dummy, @dummy, `#`, @dummy, @dummy);
The @dummy variables receive the values of those file fields, while the column names receive those file fields.
| |
doc_23527008
|
For example I'd like to be able to require certain libraries and enable them for every session in IRB.
A: The file is called ~/.irbrc. Here is an example of one (found while googling "irbrc").
| |
doc_23527009
|
In the next step, i'm creating a new VSTS Build Definition with the existing SonarQube build steps.
When I trigger this build, it fails in the last step, after the report has been uploaded to my SonarQube server:
VSTS build log
SonarQube server log
I don't know why this happens, because the sonar-scanner is working just fine. I'm using the same parameters in my MS Build step.
A: Looks like your VSTS task is pending completion of the Background Task on SonarQube server side, as per this log in your first screenshot:
Waiting on the sonarqube server to finish processing in order to determine the quality gate status
(note: this is a log from the VSTS task itself, not from the SonarQube Scanner which did finish successfully)
The problem is that the Background Task actually fails with an error as per your second screenshot. The failure corresponds to bug SONAR-8013 (fix to be released in upcoming SonarQube 6.1).
| |
doc_23527010
|
Could anyone help me understand why this is?
class Foo
def self.fuga
pp Foo.public_instance_methods(false)
end
end
class Bar < Foo
fuga
def hoge
p "fuga"
end
end
Bar.fuga
=> []
A: You get an empty array because at Foo.public_instance_methods you call public_instance_methods on Foo and Foo doesn't have any public instance methods (only Bar does).
If you change that line to self.public_instance_methods it would work as expected.
class Foo
def self.fuga
pp self.public_instance_methods(false)
end
end
class Bar < Foo
fuga
def hoge
p "fuga"
end
end
Bar.fuga
#=> [:hoge]
| |
doc_23527011
|
if(!preg_match('/^[~a-zA-Z0-9{},:_\/-]+$/i', $str))
{
exit('Disallowed Key Characters: '.$str);
}
This triggers Disallowed Key Characters: when $str contains:
{"education_level":"1","job_experience":"1","occupation":"41-3011","onet_code"
:"41-3011_00","region":"22220","relevance":"0","school":"0","schoolstate":"0","state":"4","gpa":"0","major"
:"0"}
A: You should allow also a quote character (") and whitespaces (\s). Your regex should be:
/^[~a-zA-Z0-9{},:_\/"\s-]+$/i
Regex101 demo.
| |
doc_23527012
|
Example 1 (script1.sh):
a="google.analytics.account.id=`read a`"
echo $a
Example 2 (script2.sh):
cat script2.sh
a=`head -1 input.txt`
echo $a
Sample input.txt
google.analytics.account.id=`read a`
If I run script1.sh the read command is working fine, but when I am running script2.sh, the read command is not executed, but is printed as part of the output.
So I want script2.sh to have the same output as script1.sh.
A: Your input.txt contents are effectively executed as a script here; only do this if you entirely trust those contents to run arbitrary commands on your machine. That said:
#!/usr/bin/env bash
# ^^^^- not /bin/sh; needed for $'' and $(<...) syntax.
# generate a random sigil that's unlikely to exist inside your script.txt
# maybe even sigil="EOF-$(uuidgen)" if you're guaranteed to have it.
sigil="EOF-025CAF93-9479-4EDE-97D9-483A3D5472F3"
# generate a shell script which includes your input file as a heredoc
script="cat <<$sigil"$'\n'"$(<input.txt)"$'\n'"$sigil"
# run that script
eval "$script"
A: In script1.sh the first line is evaluated, therefore the read a is executed and replaced in the string.
In script 2.sh the first line is evaluated, therefore the resulting string from execution of head is put into the variable a.
There is no re-evaluation done on the resulting string. If you add the evaluation with eval $a and the first line in input.txt is exactly as the first line of script1.sh (actually the a="..." is missing) then you might get the same result. The heredoc, as CharlesDuffy suggested, seems more accurate.
| |
doc_23527013
|
When using it, the floor casting is working well for east and west side, but for north and south it just does weird things (just look image).
double pixelsToBottom;
double pixelsToMid;
double directDistFloor;
double realDistance;
double y;
t_point f_p;
pixelsToBottom = (double)data->s_height - wall[1].y;
pixelsToMid = (double)data->s_height / 2 - pixelsToBottom;
for (int i = pixelsToMid; i < data->s_height / 2; i += 1)
{
directDistFloor = (data->dist_proj * (double)(data->s_height / 2)) / i;
realDistance = directDistFloor / fabs(cos(angle));
f_p.x = data->player.pos.x + cos(angle) * (realDistance) / (data->dist_proj / (64.0));
f_p.y = data->player.pos.y + sin(angle) * (realDistance) / (data->dist_proj / (64.0));
y = (wall->x + (i + data->s_height / 2) * data->s_width) / data->s_width;
pixel_put(&data->obj, wall->x, y, f_pixel(data, f_p));
}
But i'm facing an issu, when i'm facing north and south side it's all ok, but when the ray is going into east or west side, the texture just do a weird thing like that :
I know that it refer to : realDistance = directDistFloor / fabs(cos(angle));
if i replace the cos(angle) by sin(angle) in this line, it just invert things. I didn't find a way to change the calcule in right moment. I you have any idea I will take it ! Thank you !!
A: It's okay I found the answer, for the people who are interest, in the line realDistance = directDistFloor / fabs(cos(angle)); I was using the angle of the ray in the world, I changed it by the angle relative to my player dir (so 0° if it's the player dir ray) and it work properly ! Thank's @ZwergofPhoenix for the time you took !
| |
doc_23527014
|
Fatal Exception: com.facebook.react.bridge.NoSuchKeyException: backgroundColor
at com.facebook.react.bridge.ReadableNativeMap.getValue + 109(ReadableNativeMap.java:109)
at com.facebook.react.bridge.ReadableNativeMap.getValue + 113(ReadableNativeMap.java:113)
at com.facebook.react.bridge.ReadableNativeMap.getInt + 156(ReadableNativeMap.java:156)
at com.facebook.react.uimanager.ViewProps.isLayoutOnly + 252(ViewProps.java:252)
at com.facebook.react.uimanager.NativeViewHierarchyOptimizer.isLayoutOnlyAndCollapsable + 445(NativeViewHierarchyOptimizer.java:445)
at com.facebook.react.uimanager.NativeViewHierarchyOptimizer.handleCreateView + 94(NativeViewHierarchyOptimizer.java:94)
at com.facebook.react.uimanager.UIImplementation.handleCreateView + 259(UIImplementation.java:259)
at com.facebook.react.uimanager.UIImplementation.createView + 252(UIImplementation.java:252)
at com.facebook.react.uimanager.UIManagerModule.createView + 465(UIManagerModule.java:465)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke + 515(Method.java:515)
at com.facebook.react.bridge.JavaMethodWrapper.invoke + 371(JavaMethodWrapper.java:371)
at com.facebook.react.bridge.JavaModuleWrapper.invoke + 150(JavaModuleWrapper.java:150)
at com.facebook.react.bridge.queue.NativeRunnable.run(NativeRunnable.java)
at android.os.Handler.handleCallback + 733(Handler.java:733)
at android.os.Handler.dispatchMessage + 95(Handler.java:95)
at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage + 26(MessageQueueThreadHandler.java:26)
at android.os.Looper.loop + 136(Looper.java:136)
at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run + 225(MessageQueueThreadImpl.java:225)
at java.lang.Thread.run + 841(Thread.java:841)
A: I resolved issue as in one of my css file I'd:
backgroundColor: null
and converted to
backgroundColor: 'transparent'
You can also check if backgroundColor is not undefined
| |
doc_23527015
|
#include<stdio.h>
void main()
{
printf("%d"+1);
}
is d but the output of
#include<stdio.h>
void main()
{
printf("%%%d"+1);
}
is %d and not %%d ??
A: "%d"+1 by pointer arithmetic takes you to the second char in the char array which is d.
In the string literal "%%%d"+1 leaves you with "%%d" which is interpreted as %d by printf. Since %% is escaped to %.
A: You are doing pointer arithmetic. "%d"+1 is "d" and "%%%d"+1 is "%%d" (it's like you are skipping the first character of the string).
But, as the documentation of printf() explains, the percent sign (%) is a special character in the string format argument of printf(). It introduces a "conversion specifications".
Because it is a special character it needs a special sequence (a conversion specification, in fact) in order to be able to print a literal %. And the conversion specification designated to print a literal % is exactly %%, as you can see from the first row of the conversion specifications table in the docs.
A: You are using +1 in printf which will in turn skip the one character i.e. % in your case. after skipping %character you will be left with %%d, since %% is used to print % character. Output will be %d.
| |
doc_23527016
|
|Date | Time |
|--------|--------|
|1/1/2019|1200hrs |
|1/1/2019|1300hrs |
|1/1/2019|1400hrs |
|1/2/2019|1200hrs |
|1/2/2019|1300hrs |
|1/2/2019|1400hrs |
|1/2/2019|1700hrs |
I want to generate another column that shows the difference between each time like the dataframe shown below,
|Date | Time |Time difference(mins)|
|--------|--------|---------------------|
|1/1/2019|1200hrs |- |
|1/1/2019|1300hrs |60 |
|1/1/2019|1400hrs |60 |
|1/2/2019|1200hrs |- |
|1/2/2019|1300hrs |60 |
|1/2/2019|1400hrs |60 |
|1/2/2019|1700hrs |180 |
The time difference should be calculated on the same date.
Can anyone give me some idea of how to do it?
Thank you!
A: Use DataFrameGroupBy.diff with convert to datetimes, last convert timedeltas to seconds by Series.dt.total_seconds and last to minutes by division of 60:
df['Time'] = pd.to_datetime(df['Date'] + df['Time'], format='%m/%d/%Y%H%Mhrs')
df['Time difference(mins)'] = df.groupby('Date')['Time'].diff().dt.total_seconds().div(60)
print (df)
Date Time Time difference(mins)
0 1/1/2019 2019-01-01 12:00:00 NaN
1 1/1/2019 2019-01-01 13:00:00 60.0
2 1/1/2019 2019-01-01 14:00:00 60.0
3 1/2/2019 2019-01-02 12:00:00 NaN
4 1/2/2019 2019-01-02 13:00:00 60.0
5 1/2/2019 2019-01-02 14:00:00 60.0
6 1/2/2019 2019-01-02 17:00:00 180.0
| |
doc_23527017
|
def fetch_num():
x = np.random.randint(low=0, high=1000000) # choose a number
for i in range(5000000): # do some calculations
j = i ** 2
return x # return a result
This function picks a random number, then does some calculations, and returns it.
I would like to create a large list, containing all of these results. The catch is, that I don't want to process the same number twice, and I want to use multiprocessing to make that quicker.
I've tried the following code:
import multiprocessing as mp
from tqdm import tqdm
from parallelizing_defs import fetch_num
import os
os.system("taskset -p 0xff %d" % os.getpid())
if __name__ == '__main__':
n = 10 # number of numbers that I want to gather
def collect_result(result): # a callback function - only append if it is not in the results list
if result not in results:
results.append(result)
pbar.update(1) # this is just for the fancy progress bar
def error_callback(e):
raise e
pool = mp.Pool(6) # create 6 workers
global results # initialize results list
results = []
pbar = tqdm(total=n) # initialize a progress bar
while len(results) < n: # work until enough results have been accumulated
pool.apply_async(fetch_num, args=(), callback=collect_result, error_callback=error_callback)
pool.close()
pool.join()
Notes:
*
*the function fetch_num is imported from a different python file since I understand that it doesn't work within the same file from this issue Multiprocessing example giving AttributeError
*the weird os line, I added after reading this issue: Why does multiprocessing use only a single core after I import numpy?
My problem is:
*
*The loop doesn't stop, it goes on forever.
*The iterations are not faster, it doesn't seem to be using more than one core.
I've tried a bunch of other configurations, but it doesn't seem to work. This sounds like a very common situation but I haven't been able to find an example of that particular problem.
Any ideas as to why these behaviours take place would be much appreciated.
A: You have several issues. First, you need to include numpy. But your big problem is:
while len(results) < n: # work until enough results have been accumulated
pool.apply_async(fetch_num, args=(), callback=collect_result, error_callback=error_callback)
You can be submitting these jobs with calls to apply_async faster than the results are returned and end up submitting way too many jobs. You need to submit exactly n jobs and take care of ensuring that duplicate results are not returned in fetch_num. The way to do that is to use a sharable set that holds all previously generated numbers. Unfortunately, sharable sets do not exist. But we do have sharable dictionaries that can serve the purpose. We therefore initialize each process in the pool with a proxy pointer to the sharable dictionary and a lock to serialize access to the dictionary.
It is true that process pools functions sucg as fetch_num must be imported for but only if you are running under something like jupyter notebook. If you are running the program "normally" from the command line, this is not required. I have therefore included the source inline so you might see it. I have also added a print statement so that you can see that all 6 processes are running in parallel.
import multiprocessing as mp
import numpy as np
from tqdm import tqdm
def pool_init(the_dict, l):
global num_set, the_lock
num_set = the_dict
the_lock = l
def fetch_num():
the_lock.acquire()
print('fetch_num')
while True:
# get
x = np.random.randint(low=0, high=1000000) # choose a number
if x not in num_set:
num_set[x] = True
break
the_lock.release()
for i in range(5000000): # do some calculations
j = i ** 2
return x # return a result
if __name__ == '__main__':
with mp.Manager() as manager:
the_dict = manager.dict()
the_lock = mp.Lock()
n = 10 # number of numbers that I want to gather
results = []
def collect_result(result):
results.append(result)
pbar.update(1) # this is just for the fancy progress bar
pool = mp.Pool(6, initializer=pool_init, initargs=(the_dict, the_lock)) # create 6 workers
pbar = tqdm(total=n) # initialize a progress bar
for _ in range(n):
pool.apply_async(fetch_num, args=(), callback=collect_result)
pool.close()
pool.join()
print()
print(results)
A: Is there a particular reason you need to generate the number in the function doing the processing? Both Python and NumPy have ways to sample without replacement so as to feed a bunch of unique random integers to your process pool without them needing to worry about acquiring and releasing locks.
>>> import numpy as np
>>> from concurrent.futures import ProcessPoolExecutor
>>> rng = np.random.default_rng()
>>> randoms = rng.choice(1000000, size=(10,), replace=False)
>>> randoms
array([908648, 947502, 510774, 272587, 362679, 529124, 42039, 912716,
921618, 581853])
>>> with ProcessPoolExecutor() as p:
... results = p.map(process_num, randoms)
A: You should add an error_callback to display the error from the subprocess and either decrements the expected results (so you don't loop forever) or pushes the error up to crash the script.
| |
doc_23527018
|
The problem is in entities of each bundle. Exists some way, how to assign entities into its bundle? I mean User entity into User bundle, Products and Categories entities into Products bundle and so on.
Edit:
I generate entities using doctrine console. But I didnt find any parameter to generate few entity/ies from my DB. Is this way right? Or I have to write entities manually?
I need somethink like this for reusabling of bundles.
Thank`s for any hints ;)
A: I think you are waay overcomplicating things. Something simple as managing an entity should not have a full bundle just for that. It is perfectly fine to have one bundle to house 40+ entities.
What you could use another bundle is like this example:
form bundle that will be used for fancy-looking forms, autocomplete fields, image uploader, image resiser etc. Than from your main application form, you could do something like this:
$builder->add("Users", "my_fancy_autocomplete_collection", [
"type"=>new UserType(),
"autocomplete_route_name"=>"suggest_users" // controller route
]) ;
And for display, it could be something like: http://welldonethings.com/tags/manager (the first one I found)
That fancy type must have some DataTransformer that would convert display data into real users fetched from database. It is kinda tricky to learn all these things at once but once you do that, you would be able to use that same bundle in other applications as well.
A: When I start a symfony 2 project, here is my logic about bundles :
*
*Create one bundle for my app (with the CLI of course)
*Create other bundles if I can reuse them in other projects
So, as @Zeljko said, think twice about your project's scope to define bundles.
After that it's simple, create your entities inside bundle with correct namespaces (for example : Company\Nomdubundle\Entity).
A: I found the soultion here (there is a parameter --filter)
Generating a single Entity from existing database using symfony2 and doctrine
Thanks for hints.
| |
doc_23527019
|
Here is my code, any tips for how I can achieve this?
componentDidMount() {
this.myInterval = setInterval(() => {
this.setState(({ seconds, minutes }) => ({
seconds: seconds + 1,
minutes: Math.floor(seconds / 60)
}))
}, 1000)
}
| |
doc_23527020
|
class FanClub_Banner
{
public $img = 'http://www.example.com/museum/images/logo_ver_250.png';
public static function banner_me(array $widget, $positionCode, array $params, XenForo_Template_Abstract $renderTemplateObject)
{
return '<img src="'. $this->$img . '" width="250" height="250" alt="Museum">';
}
}
and i get the error:
Fatal error: Using $this when not in object context in C:\public_html\comunidad\library\FanClub\Banner.php on line 8
How to fix it?
Thanks
A: Your static method cannot access your Class property, a simple fix would be to remove the static from public static function and where you want to use this method you'd do FanClub_Banner fcBanner = new FanClub_Banner();
fcBanner->banner_me(....);
Another fix would be to make the property static as well so you'd have public static $img...
| |
doc_23527021
|
Surname | Name | Company
---------------------------------------
Sidorov | Sasha | DataGridBind.Company
Petrov | Misha | DataGridBind.Company
MainWindow.xaml.cs:
namespace DataGridBind
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Person person = new Person("Sasha", "Sidorov", new Company("Teremok") );
Person person1 = new Person("Misha", "Petrov",new Company("SubWay"));
ObservableCollection<Person> persons = new ObservableCollection<Person> { person, person1 };
personDataGrid.ItemsSource = persons;
}
}
}
Person.cs :
namespace DataGridBind
{
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public Company Company { get; set; }
public Person() { }
public Person(string _name, string _surname, Company _company)
{
Name = _name;
Surname = _surname;
Company = _company;
}
}
public class Company
{
public string Name {get;set;}
public Company() { }
public Company(string _name)
{
Name = _name;
}
}
}
Xaml:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DataGridBind" x:Class="DataGridBind.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid >
<DataGrid x:Name="personDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" Margin="10,10,138,177" RowDetailsVisibilityMode="Visible">
<DataGrid.Columns>
<DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
<DataGridTextColumn x:Name="surnameColumn" Binding="{Binding Surname}" Header="Surname" Width="SizeToHeader"/>
<DataGridTextColumn x:Name="companyColumn" Binding="{Binding Company}" Header="Company" Width="200"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
A: Because Company is a class you need to specify which property of Company you want to bind to
<DataGridTextColumn Binding="{Binding Company.Name}" Header="Company" ... />
otherwise ToString() will be called on bound object
A: To avoid this we usually implement ToString() on all of our domain objects.
| |
doc_23527022
|
jQuery: Get height of hidden element in jQuery
Here is my code:
function tabload() {
$('.tab li:first-child').addClass('selected');
$(".tab ul").css({ 'position': 'absolute', 'visibility': 'hidden', 'display': 'block'});
var h = $(".tab ul").outerHeight(true);
$(".tab ul").css("height", h);
$(".tab ul").css({'position': 'relative', 'visibility': 'visible', 'display': 'none' });
};
Am i doing something wrong?
A: I have blogged about this issue before since there are a few other similar questions here on stackoverflow. Take a look at the code in this blog post
I initially developed it just for the width method, but based on comments the code has evolved to include inner/outer dimensions.
A: You may not get the height/widith of hidden(display:none;) elements in all the browsers. Try to show the element and hide it after you get the height.
function tabload() {
$('.tab li:first-child').addClass('selected');
$(".tab ul").show();
var h = $(".tab ul").outerHeight(true);
$(".tab ul").css("height", h);
$(".tab ul").css({'position': 'relative', 'visibility': 'visible', 'display': 'none' });
};
A: If you are using display: none you may consider to use position absolute with some huge margin. eg position:absolute;left:-999999px; instead.
A: I think you're confusing visibility and display. visibility shows the space for the element on the page, but doesn't actually render it. display: none won't show the element or the space it fills.
So when you set
$(".tab ul").css({'position': 'relative', 'visibility': 'visible', 'display': 'none' });
You're actually completely hiding the element
| |
doc_23527023
|
It means if I have a product which is in cat1>cat2>cat3, I should get "cat1".
Is it possible ?
I tried $product->id_category_default, but I only get the current category.
A: You have to create new smarty variable in ProductController and use getParentsCategories() function for your product category.
| |
doc_23527024
|
The task: To repeat json data in a table. (list of products, last cell is a button).
The problem: On clicking the button, another repeated list of rows appears under the product (second data-repeat, accessories of the products) but must match the product.
Now i can get the first part. I can even ng-repeat the second part, and the ng-click. However, every button repeats the same thing. I know that $index probably can be used here, i just dont understand how.
So how do i get the accessories for each individual product, to only show when the product button is clicked?
Example: Product 1 has 5 accessories. Product 2 has 1 accessory. If i click the product 1's button, 5 accessories show underneath it. If i click the product 2's button, 1 accessory shows below it.
Code:
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12" style="padding:0px;">
<table class="table table-bordered" ng-controller="tableCtrl_1" ng-switch="test">
<tr style="height:70px;background-color:#0C4791;">
<th style="text-align:center;color:white;vertical-align:middle;">Flexi Floor/Low Wall</th>
<th style="text-align:center;color:white;vertical-align:middle;">Cooling</th>
<th style="text-align:center;color:white;vertical-align:middle;">Heating</th>
<th style="text-align:center;color:white;vertical-align:middle;">Nominal Capacities(cooling/heating)</th>
<th style="text-align:center;color:white;vertical-align:middle;">Pipe Length</th>
<th style="text-align:center;color:white;vertical-align:middle;">List Price</th>
<th style="text-align:center;color:white;vertical-align:middle;">Quantity</th>
</tr>
<tr ng-repeat-start = "getdata in getdata | filter:'Flexi Floor/Low Wall':true">
<td style="vertical-align:middle;text-align:center;">{{getdata.model_no_from}} + {{getdata.model_no_to}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata.cooling}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata.heating}}</td>
<td style="vertical-align:middle;text-align:center;"><span style="color:blue">{{getdata.nominal_cooling}}</span><span style="color:red;">{{getdata.nominal_heating}}</span></td>
<td style="vertical-align:middle;text-align:center;">{{getdata.pipe_length}}</td>
<td style="vertical-align:middle;text-align:center;"><span style="font-weight:bold;">{{getdata.system_listPrice | currency: "£"}}</span></td>
<td style="vertical-align:middle;text-align:center;"><button class="btn btn-default btn-large btn-block" ng-click="showDetails = ! showDetails">Select</button></td>
</tr>
<tr ng-repeat-end ng-class="{ 'hidden': ! showDetails }" >
<!--<td style="vertical-align:middle;text-align:center;">{{getdata_2.sales_description}}</td>
<td style="vertical-align:middle;text-align:center;">{{getdata_2.list_price}}</td> -->
<td colspan="7" style="text-align:center;vertical-align:middle;">test 1</td>
</tr>
</table>
</div>
</div>
</div>
</body>
And the controller:
testApp.controller('tableCtrl_1', function($scope, $http, ajaxServices, secondaryServices){
getdata();
function getdata(){
$http.post("angular_data.php").success(function(data){
$scope.getdata = data;
});
};
ajaxServices.getProducts().success(function(data){
$scope.getdata = data
});
secondaryServices.getProducts_2().success(function(data){
$scope.getdata_2 = data
});
});
Services:
testApp.factory('ajaxServices', function($http){
return {
getProducts: function(){
return $http.get('angular_data.php', {data: {}})
}
}
});
testApp.factory('secondaryServices', function($http){
return {
getProducts_2: function(){
return $http.get('angular_data_2.php', {data: {}})
}
}
});
Pardon the inline-styling, just easier for me while testing.
| |
doc_23527025
|
createAction returns a PayloadActionCreator which has a generic of <ReturnType<PA>['payload'], T, PA>. However, what does it mean by ReturnType<PA>['payload']?
export declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>
A: ReturnType<PA>['payload'] means the payload property of the object returned by the prepare function - as this is the signature for the prepare notation.
However, this should not concern you. The usual usage is const actionCreator = createAction<PayloadType>('some/action/type').
The alternative notation would be the prepare notation, in the form createAction('some/action/type', (payload: string) => ({ payload, meta: {something: "foo"}}).
In general, please refer to the API documentation that has almost all usage examples in TypeScript.
You really should not write more types than are present there. (And yes, that's not a lot of types, that's pretty much the point ;) )
| |
doc_23527026
|
var Person = sequelize.define("Person", {
no: {type: DataTypes.STRING, unique: true, allowNull: false}
}, {
classMethods: {
associate: function(models){
Person.hasMany(models.Task);
Person.hasMany(models.Job);
}
}
});
Task has field: description, and Job has field: title.
Now I try to use transaction to insert record, but I am stuck:
return sequalize.transaction(function (t) {
return models.Person.create({
no: '1221212'
}, {transaction: t}).then(function (person){
// I am stuck here, to insert multiple task and job
}, {transaction: t});
}).then(function(result){
}).catch(function(err){
});
How can I insert multiple task and job after create a person?
A: Option 1
You can create child objects like this:
return sequelize.transaction(function (t) {
return Person.create({
no: '1221212',
Tasks: [
{ taskName: 'task1' },
{ taskName: 'task2' }
]}, {
transaction: t,
include: [ { model: Task } ]
}
);
});
We use "include" option here.
Here is SQL generated:
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): START TRANSACTION;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): SET autocommit = 1;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "People" ("id","no") VALUES (DEFAULT,'1221212') RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'task1',3) RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'task2',3) RETURNING *;
Executing (61834d07-de9e-4b6e-aa53-9cead8157595): COMMIT;
Option 2
You can also create a Person and then add Tasks to it in a bulk. This will work good if number of tasks is big, because it use only one INSERT operation for all tasks.
return sequelize.transaction(function (t) {
return Person.create({
no: '00000'
}, {
transaction: t,
})
.then(function(person) {
return Task.bulkCreate( [
{ taskName: 't1', PersonId: person.id },
{ taskName: 't2', PersonId: person.id }
], {
transaction: t
});
});
});
We use bulkCreate function and manually set id for the foreign key field.
This will generate the following SQL:
Executing (c9802841-6a22-4633-a006-41a78a9623b2): START TRANSACTION;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): SET autocommit = 1;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): INSERT INTO "People" ("id","no") VALUES (DEFAULT,'00000') RETURNING *;
Executing (c9802841-6a22-4633-a006-41a78a9623b2): INSERT INTO "Tasks" ("id","taskName","PersonId") VALUES (DEFAULT,'t1',4),(DEFAULT, 't2', 4)
Executing (c9802841-6a22-4633-a006-41a78a9623b2): COMMIT;
| |
doc_23527027
|
How to perform the same operation using azure python SDK, instead of deleting the vm's one by one.
A: The batch endpoint is Portal only and is not supported by SDKs. This issue for discussion: https://github.com/Azure/msrestazure-for-python/issues/74
(I work at MS in the Python team)
| |
doc_23527028
|
A: Try to put a redirection rule to your download.php file like this using .htaccess file
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/download.php$
RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$
RewriteRule .* /download.php [L,R=302]
| |
doc_23527029
|
I have the image-data in an Array{Array{Float64, 2}, 1} already normalized.
The following code shows only the last, smallest image. The array is sorted from the largest to the smallest picture.
for i = 1:size(P, 1)
imshow(P[i], "gray", interpolation = "none")
end
I want to achieve the following effect:
A: Here's a solution with Plots:
using Plots, TestImages
img = testimage("cameraman")
p = plot(
axis = nothing,
layout = @layout([a [b [c [d;_]; _]; _]]),
size = (800,400)
)
for i=1:4
plot!(p[i], img, ratio=1)
end
p
A: Here's two methods.
1. The quick but inflexible subplot one:
# create test image
using PyPlot, TestImages
img = testimage("cameraman");
img = [convert(Float64, i.val) for i in img[:,:]]';
# plot in desired positions
subplot(1,2,1); imshow(img); axis("off");
subplot(2,4,3); imshow(img); axis("off");
subplot(4,8,7); imshow(img); axis("off");
subplot(8,16,15); imshow(img); axis("off");
subplot(16,32,31); imshow(img); axis("off"); # ... etc
2. Manually specifying axes positioning:
# using same image as above
figure();
axes(position=[0,0,0.5,1]); imshow(img); axis("off");
axes(position=[0.5,0.5,0.25,0.5]); imshow(img); axis("off");
axes(position=[0.75,0.75,0.125,0.25]); imshow(img); axis("off");
axes(position=[0.875,0.875,0.0625,0.125]); imshow(img); axis("off"); # ... etc
A: What I would do is create a single array by concatenating the arrays for all the other images and filling in where you would like the empty space to be with zeros (or any other number)?
*
*Make a new array of arrays where all inner arrays have the same height by padding bottom with zeros
*fullimage = cat(1, arrayofarrays...)
*imshow(fullimage)
(Sorry I'm on my phone so can't provide a working example for you!)
| |
doc_23527030
|
So the architecture I want to follow is kind of like
public CustomButtonBarView extends ViewGroup
{
public CustomButtonBarView( Context context )
{
//initialize variables
}
public void onMeasure()
{
// inflate all the buttons more than 3
// measure each button width, then see if it can be fitted in one
// line and then move forward
}
}
So my question is where should I inflate those 3+ buttons? I cannot put them in the XML as the exact number is different
<CustomButtonBarView>
<Button/>
<Button/> <!-- NO idea how many -->
</CustomButtonBarView>
Thanks, any help or direction or even if you feel my direction is incorrect feel free to let me know. I am open to changes.
A: Putting the buttons in a grid view might help. There you can force the buttons to follow a grid. The OS will handle the width of the button so you might need to measure them.
| |
doc_23527031
|
Data in Elasticsearch after replication:
{
"_index": "streams",
"_type": "couchbaseDocument",
"_id": "e8c7999c-67c8-47a4-b235-726d89102f83",
"_score": 1,
"_source": {
"meta": {
"id": "e8c7999c-67c8-47a4-b235-726d89102f83",
"rev": "3-000007c43e1293830000000000000000",
"expiration": 0,
"flags": 0
},
"doc": {
"createdOn": "20141201183646786",
"activityId": "c3c0dc11-16b5-479b-80c5-93d2ce34d77d",
"_class": "com.netspective.streams.model.Activity",
"documentType": "Activity",
"objectId": "UserAgent_1",
"subjectId": "{"actionId":"111"}",
"actionId": "2",
"updatedOn": "20141201183646786",
"deleteStatus": false
}
}
}
Data in Elasticsearch that is inserted directly:
{
"_index": "streams",
"_type": "couchbaseDocument",
"_id": "45ebb326-a33e-43f2-9fd7-60953cb14772",
"_score": 1,
"_source": {
"id": "45ebb326-a33e-43f2-9fd7-60953cb14772",
"activityId": "56d291bc-eacd-4942-b26d-08025eec0ab1",
"subjectId": "{"actionId":"123"}",
"objectId": "UserAgent_1",
"documentType": "Activity",
"createdOn": "20141202113523979",
"updatedOn": "20141202113523979",
"deleteStstus": false,
"action": "2"
}
}
A: You probably need to update the Elasticsearch mappings if you have changed the structure of your data.
Take a look at the Indexing Issues section of the Elasticsearch plugin documentation, which describes how to address this.
| |
doc_23527032
|
-(void) CreateElasticRope {
//=======Params
// Position and size
b2Vec2 lastPos = b2Vec2(4,4); //set position first body
float widthBody = 0.35;
float heightBody = 0.1;
// Body params
float density = 0.05;
float restitution = 0.5;
float friction = 0.5;
// Distance joint
float dampingRatio = 0.85;
float frequencyHz = 10;
// Rope joint
float kMaxWidth = 1.1;
// Bodies
int countBodyInChain = 10;
b2Body* prevBody;
//========Create bodies and joints
for (int k = 0; k < countBodyInChain; k++) {
b2BodyDef bodyDef;
if(k==0 || k==countBodyInChain-1) bodyDef.type = b2_staticBody; //first and last bodies are static
else bodyDef.type = b2_dynamicBody;
bodyDef.position = lastPos;
lastPos += b2Vec2(2*widthBody, 0); //modify b2Vect for next body
bodyDef.fixedRotation = YES;
b2Body* body = world->CreateBody(&bodyDef);
b2PolygonShape distBodyBox;
distBodyBox.SetAsBox(widthBody, heightBody);
b2FixtureDef fixDef;
fixDef.density = density;
fixDef.restitution = restitution;
fixDef.friction = friction;
fixDef.shape = &distBodyBox;
body->CreateFixture(&fixDef);
if(k>0) {
//Create distance joint
b2DistanceJointDef distJDef;
b2Vec2 anchor1 = prevBody->GetWorldCenter();
b2Vec2 anchor2 = body->GetWorldCenter();
distJDef.Initialize(prevBody, body, anchor1, anchor2);
distJDef.collideConnected = false;
distJDef.dampingRatio = dampingRatio;
distJDef.frequencyHz = frequencyHz;
world->CreateJoint(&distJDef);
//Create rope joint
b2RopeJointDef rDef;
rDef.maxLength = (body->GetPosition() - prevBody->GetPosition()).Length() * kMaxWidth;
rDef.localAnchorA = rDef.localAnchorB = b2Vec2_zero;
rDef.bodyA = prevBody;
rDef.bodyB = body;
world->CreateJoint(&rDef);
} //if k>0
prevBody = body;
} //for -loop
}
I use distance and rope Joints, set different values of parameters dampingRatio and frequencyHz, but the effect is far from being an example (my thread for a long time coming to original state, and not so elastic.).
A: You can simulate springs by applying forces. At each timestep update the forces on the connected bodies (wake the bodies up if necessary too). If one of the bodies is the ground (or a static body) then you don't need to apply any force to the ground just the dynamic body.
A regular spring would apply both tension and compression forces (pull and push) depending on the deflection. In your case you have a bungee so there would be no compression force just tension (pull).
This is the formula you need:
F = K * x
Where F is the force, K is the spring stiffness (force/deflection), and x is the deflection. Deflection is computed as the difference between the initial length and the current length (the distance between connection points). The sign of the F determines if it is pulling or pushing. Once you compute F then you need to apply it along the line connecting two spring connection points. To satisfy force balance you need to apply this force in opposing directions (one of the bodies gets positive the other one gets negative force). This is because Sir Newton says so.
Here is an example (works with pyBox2D but you can easily convert this to C++)
You need spring objects with some properties. Your spring objects need to know their initial lengths, stiffness, body1, body2, connection coordinates (b1x, b1y, b2x, b2y (in local coordinates))
In your case you need to check if length < spr.initialLength, if this is True then you don't apply any force.
body1 = spr.box2DBody1
body2 = spr.box2DBody2
pA = body1.GetWorldPoint(b2Vec2(spr.box2Db1x, spr.box2Db1y))
pB = body2.GetWorldPoint(b2Vec2(spr.box2Db2x, spr.box2Db2y))
lenVector = pB - pA
length = lenVector.Length()
deltaL = length - spr.initialLength
force = spr.K * deltaL
#normalize the lenVector
if length == 0:
lenVector = b2Vec2(0.70710678118654757, 0.70710678118654757)
else:
lenVector = b2Vec2(lenVector.x / length, lenVector.y / length)
sprForce = b2Vec2(lenVector.x * force, lenVector.y * force)
body1.ApplyForce(sprForce, pA)
body2.ApplyForce(-sprForce, pB)
A: I very much doubt they are using any joints there. They are probably just taking the distance between the current position of the ninja guy, and the middle of the two posts, to calculate a direction and starting impulse... and just drawing two lines between the posts and the ninja guy.
A: The best physics implementation added to games I have seen was done by a guy with an engineering degree. He used the calculations you would do in physics / engineering translated into C++. Everything from simple gravity, recoil, thrust, to rotational velocities caused by incidental explosions. All the math was separated into a module that was distinct from the animation.
I would suggest looking up formulas for properties of elastics, and also consider that you have three situations for the elastic band:
1) A shaped force is being applied to stretch it back
2) The shape is now driven by the elastic properties of the band
3) The shape is no longer touching the band, and the band is loosely oscillating by its own weight and inertia
The closer you get to using the true physics calculations, the more realistic it will appear. I'm sure you can fudge it to make it easier on yourself, but humans are inherently good at seeing fakeness.
| |
doc_23527033
|
I have three different <div>s. when user click the first link, first <div> data should be display. when click the second link, display second <div>data at the position of first <div>.
code:
<div id="firstdiv" >
//first div data
</div>
<div id="seconddiv">
//second div data
</div>
<div id="lastdiv">
//last div data
</div>
<ul class="footer_links">
<li><a href="#" id="firstlink"></li>
<li><a href="#" id="secondlink"></li>
<li><a href="#" id="lastlink"></li>
</ul>
Here when user click the firstlink need to display the fistdiv data and when user click the secondlink need to display seconddiv data at position of firstdiv.
for this i have done jQuery, but it is not proper way.
$(document).ready(function () {
$("#firstdiv").replaceWith($('#seconddiv'));
$('#seconddiv').attr('id', 'firstdiv');
});
Here i have done firstdiv replacing with seconddiv and changing the id to firstdiv.
It displaying data at position of first <div>. But display forward only. Not as backward. Because here I am replacing firstdiv with seconddiv. So its not proper way. Can any one tell this. How can I do this forward and backward.
A: if you change your html to the following:
<div id="firstdiv" class="datadiv">
//first div data
</div>
<div id="seconddiv" class="datadiv">
//second div data
</div>
<div id="lastdiv" class="datadiv">
//last div data
</div>
<ul class="footer_links">
<li><a href="#firstdiv" id="firstlink" class="link">first</a></li>
<li><a href="#seconddiv" id="secondlink" class="link">second</a></li>
<li><a href="#lastdiv" id="lastlink" class="link">third</a></li>
</ul>
you can use the following jquery:
var divs = $('.datadiv');
$('.link').click(function(e) {
e.preventDefault();
divs.hide();
$($(this).attr('href')).show();
});
http://jsfiddle.net/uJ3yy/
A: <div id="firstdiv" class="myDiv" style="display:none;" >
//first div data
</div>
<div id="seconddiv" class="myDiv" style="display:none;" >
//first div data
</div>
<div id="lastdiv" class="myDiv" style="display:none;" >
//last div data
</div>
<ul class="footer_links">
<li><a href="#" id="firstlink" data-div="firtstdiv"></li>
<li><a href="#" id="secondlink" data-div="seconddiv"></li>
<li><a href="#" id="lastlink" data-div="lastdiv"></li>
</ul>
in javascript:
$(function () {
$(".footer_link a")click(function(e){
$(".myDiv").hide();
$("#" + $(this).data("div")).show();
e.preventDefault();
return false;
});
});
| |
doc_23527034
|
import pandas as pd
dat = {'ID': [1,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6],
't': [0,1,2,3,0,1,2,0,1,2,3,0,1,2,0,1,0,1,2],
'x1' : [3.5,3.5,3.5,3.5,2.01,2.01,2.01,3.9,3.9,3.9,3.9,2.2,2.2,2.2,1.8,1.8,2.1,2.1,2.1],
'x2': [4,4,4,4,3,3,3,4,4,4,4,3,3,3,2,2,3,3,3]
}
df = pd.DataFrame(dat, columns = ['ID', 't', 'x1','x2'])
print (df)
I need to create a new column y and group_by ID such that
if t!=max(t) then y=1,
if t==max(t) then y = x1-x2+1.
The output would look like:
Please not that I have million of records, so the faster the solution the better.
A: We can combine transform max with np.where
df['y'] = np.where(df.t != df.groupby('ID').t.transform('max'), 1, df.x1-df.x2+1)
df
Out[221]:
ID t x1 x2 y
0 1 0 3.50 4 1.00
1 1 1 3.50 4 1.00
2 1 2 3.50 4 1.00
3 1 3 3.50 4 0.50
4 2 0 2.01 3 1.00
5 2 1 2.01 3 1.00
6 2 2 2.01 3 0.01
7 3 0 3.90 4 1.00
8 3 1 3.90 4 1.00
9 3 2 3.90 4 1.00
10 3 3 3.90 4 0.90
11 4 0 2.20 3 1.00
12 4 1 2.20 3 1.00
13 4 2 2.20 3 0.20
14 5 0 1.80 2 1.00
15 5 1 1.80 2 0.80
16 6 0 2.10 3 1.00
17 6 1 2.10 3 1.00
18 6 2 2.10 3 0.10
| |
doc_23527035
|
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require select2
//= require datatables // This
//= require turbolinks
//= require_tree .
and application.css.scss
*= require_self
*= require select2
*= require datatables // This
*= require_tree .
*/
To test that DataTables I just enter to one my forms and with the Chrome console, I set a bootstrap class to a table, and converted to a DataTable with this:
$('table').DataTable( {
dom: 'B<"clear">lfrtip',
buttons: {
name: 'primary',
buttons: [ 'copy', 'csv', 'excel' ]
}
} );
Apparently it works, but there's something missing, those tiny icons in the sort headers.
Note: I included a customized download from the DataTables website.
Update:
Apparently I have a problem with the glyphicons, some font is missing or something. I'm currently using the gem 'bootstrap-sass', '~> 3.3.5'
A: *
*Did you copy over the images into the asset folder? You will need to copy over the "vendor/assets/images/dataTables/{sort_asc.png|sort_both.png|sort_desc.png" files
*You should try avoiding adding dataTable to all tables $('table'), does that, either bind it to a class (".dt") or id ("#dt")
*The correct API is $('table').dataTable({}). Note the small case. "DataTable" returns the api object and not the DataTable object. But then obviously, It still works!
Ensure the application.js files has
//= require dataTables/bootstrap/{3 OR 2}/jquery.dataTables.bootstrap
And these files should be also placed within vendor/assets folder
Btw, did you try using the jquery-datatables-rails gem?
Add the following to your Gemfile
gem 'jquery-datatables-rails', '~> 3.3.0'
Run the following command in your project folder
rails generate jquery:datatables:install bootstrap2
or if you prefer bootstrap3
Ensure you add your Extra's in the application.js and css files, for e.g.
//= require dataTables/extras/dataTables.tableTools
Should be present in your application.js file and similarly your application.css should have the following:
*= require dataTables/extras/dataTables.tableTools
A: The only way that fixed was downloading a bootstrap package and copy the fonts into a fonts folder in vendor directory, and add the following described on this answer:
https://stackoverflow.com/a/20297523/598070
A: I simply copied the images to app/assets/images and created a workaround route for these specific image files like this:
get '/assets/plugins/datatables/images/:name.:ext', to: redirect('/assets/%{name}.%{ext}'), constraints: { name: /.+/, ext: /(jpg|png|gif)/ }
Works fine with jquery-datatables-rails (3.4.0) and rails 5.0.0
A: The reason why the icon is not shown is due to fonts. Glyphicons is not loaded.
I resolved with following code.
diff --git a/app/assets/stylesheets/bootstrap_and_overrides.scss b/app/assets/stylesheets/bootstrap_and_overrides.scss
index 2f5a9f9..0bbbcc8 100644
--- a/app/assets/stylesheets/bootstrap_and_overrides.scss
+++ b/app/assets/stylesheets/bootstrap_and_overrides.scss
@@ -4,6 +4,7 @@
Use Font Awesome icons (default)
To use Glyphicons sprites instead of Font Awesome, replace with "require twitter-bootstrap-static/sprites"
=require twitter-bootstrap-static/fontawesome
+ =require twitter-bootstrap-static/sprites
*/
.alert-notice {
color: #3c763d;
| |
doc_23527036
|
class ABC {
protected:
X1& _x1;
X2& _x2;
Logger& _logger;
ABC(X1& x1, X2& x2, Logger& l):_x1(x1), _x2(x2),_logger(l) {}
ABC(X1& x1, Logger& l):_x1(x1),_logger(l) {} //getting error uninitialized reference member ‘ABC::_x2’
~ABC(){this->clear();}
void clear(){}
};
error uninitialized reference member ‘ABC::_x2'
A: The compiler is telling you the truth - you need to initialize the second reference in your class, i.e. _x2.
You cannot have uninitialized references so either don't use them or you need to initialize them in every constructor that you declare.
A: Well, thecompiler tells you what the problem is (and it is inrelated to having multiple constructors): your class has a reference member which is not initialized in the constructor: _x2. All reference members need to be initialized in the constructor.
A: C++ requires you to initialize all reference members. If there are situations when a reference to an object is optional, it's best to replace a reference variable with a pointer:
X2* _x2;
If you must have a reference with a default, make a private static variable for it, and use that variable to initialize your reference variable:
class ABC {
private:
static X2 _x2_default; // Declare it in a CPP file
protected:
...
ABC(X1& x1, Logger& l):_x1(x1),_logger(l), _x2(_x2_default) {}
...
};
A: A reference must be initialised. For class members, this means initialisation in the member initializer list of the constructor.
If the member may be remain uninitialized, make it a pointer and ensure that it is default initialized (ie :m2_() //null, where m2_ is M2* m2_;), or wrap it with a smart pointer that at least ensures default initialization
| |
doc_23527037
|
{{_.last([1,2,3,4])}}
... right in the HTML of the page.
I am able to see the correct answer (4) only if I do this in my controller:
$scope._ = _;
I tried to inject _ as a factory into my main application module and then inject that into my controller, but it doen't seem to inject it into the $scope.
Can anyone see the mistake I am making? Or is there a mechanism there that would prevent the underscore library from getting into the $scope? I am using angular v.1.0.7 and a recent version of underscore (not sure of the exact version number, but it is within the last 3 weeks).
A: Angular expressions ({{expression}}) are evaluated against the local $scope, which, in case you have defined a controller, is a $scope object as in function MyCtrl($scope){}.
So, when you use _ in your expressions, the _is evaluated against the $scope, and since $scope.doesn't have a _ member, you expression fails.
So, the only to use _in your views is to make it available on $scope object with: $scope._ = _;.
Btw, when used in browser context, underscore adds _as global object, so it's available throughout your JS. This means that there's no need to "inject _as a factory".
| |
doc_23527038
|
*
*I am under the assumption that many organization might have office 365 subscription but it is not mandatory that they should have Azure subscription as well. Is this right?
*Under the Office 365 account for an organization, there can be many users(not AD).
*If my organization needs to export existing AD users into Office 365, is that the point I should be thinking of Azure subscription or can existing users from AD be directly exported to Office 365
A: *
*You can use Office 365 (O365) without an Azure Subscription,
however, the directory service used for access to O365 is actually
Azure Active Directory (Azure AD). The default directory namespace
is {subscriptionname}.onmicrosoft.com.
*All O365 users will be registered in an Azure AD instance tied to
the O365 subscription.
*Existing on-premise users held in Windows Active Directory can be syncronised to Azure AD using the Azure Active Directory Sync Services which is a free tool and which can be used without an Azure Subscription.
If at some later point you wish to use the same Azure AD instance as part of an Azure Subscription it is possible to.
A: Chris, your first assumption is correct. Customers that have an Office 365 subscription do not necessarily have an Azure subscription too. However this doesn't prohibit them from signing up for applications like yours using their Office 365 Azure AD and using single sign-on with their Office 365 accounts. During sign-up customers will consent to granting your application the required delegated permissions - this experience doesn't require an Azure subscription.
All Office365 accounts live in the Azure Active Directory to which that Office365 subscription is associated. That Azure AD can contain user accounts mastered in the cloud and/or user accounts mastered in an on-premises directory that have been syncronized to the cloud. Many of our customers are small businesses with accounts only in the cloud, whereas our enterprise customers syncronize accounts from on-premises and also create cloud only accounts.
Synchronizing on-premises directory to Office 365 Azure AD also doesn't require an Azure subscription. The Azure AD Sync tool is available outside of an Azure subscription.
Finally, Azure AD administration via the Azure management portal (requires Azure subscription) provides many identity management features that aren't available in the Office365 management portal: Azure AD premium reports including anomalous sign-ins, managing access to third party applications like the one you're building (simple users and groups assignment as well as assigning users and groups to application roles), managing security groups in the cloud and many more.
Read more about Azure AD and most importantly try out both the experiences (without and with Azure subscription).
Hope this helps.
| |
doc_23527039
|
$dateCurrent = strtotime(date('Y-m-d h:i:s'));
$this->transactions = \Stripe\BalanceTransaction::all([
'available_on' => [
'lte' => "{$dateCurrent}",
],
'currency' => 'USD'
]);
foreach ($this->transactions->data as $key => $value) {
if ($key == 0) {
$time = date('d', $value->available_on);
}
if ($time == date('d', $value->available_on)) {
$this->trans[] = $value;
$transactionCount = $key;
}
}
and then I am trying to add all amounts for every transactions like this,
$total = 0;
foreach ($this->trans as $key => $value) {
if ($key == 0) {
$total = $value->amount;
} elseif ($value->status == 'available') {
$total = bcadd($value->amount, $total);
}
}
dump($total);
Upon writing this code, I got a result of -94769.
Am I doing it right?
How do I represent -94769 to actual money value e.g 99.18 USD?
My references on this is base on stripe API at the following links
https://stripe.com/docs/api?&lang=php#charge_object
https://stripe.com/docs/currencies#zero-decimal
This is the first time I will integrate payment method on web application. So I need deeper understanding about money.
A: "Amount" in the Stripe API always represents the smallest unit of your default currency. So, it is cents for USD, or Yen for JPY.
Assuming your currency is USD, you can convert any Amount to dollars simply by dividing by 100.
| |
doc_23527040
|
proc reg data=datain.aswells alpha=0.01;
model arsenic = latitude longitude depth_ft / clb;
run;
I wish to make a 95% prediction interval with latitude=23.75467, longitude=90.66169, and depth_ft=25. This data point does not exist in the data set, but it is in the range of values used to compute the model. Is there an easy way of accomplishing this in SAS? Shouldn't there be a way to compute this prediction interval in SAS easily?
A: The easiest thing to do is to add it to your input data set with a missing value for ARSENIC. Then use the OUTPUT statement to output the prediction intervals.
Here is an example:
data test;
do i=1 to 100;
x1 = rannor(123);
x2 = rannor(123)*2 + 1;
y = 1*x1 + 2*x2 + 4*rannor(123);
output;
end;
run;
data test;
set test end=last;
output;
if last then do;
y = .;
x1 = 1.5;
x2 = -1;
output;
end;
run;
proc reg data=test alpha=.01;
model y = x1 x2;
output out=test_out(where=(y=.)) p=predicted ucl=UCL_Pred lcl=LCL_Pred;
run;
quit;
The WHERE clause on the output filters the resulting set to just the missing value to be predicted. You can remove it and get all predicted values and prediction intervals.
| |
doc_23527041
|
cv_results_ provides a dataframe for the score, but the tuple output was way easier to handle.
Please guide me towards handling parameter and score values in this new version of scikit. I plan to run a GridSearchCV for different ranges of parameters which I would latter consolidate into a single dictionary.
A: Use the for loop to print the results from cv_results_ as they were in grid_scores_.
From the documentation example:
clf = GridSearchCV(init params...)
clf.fit(train data...)
print("Best parameters set found on development set:")
print(clf.best_params_)
print("Grid scores on development set:")
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
#THIS IS WHAT YOU WANT
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r"
% (mean, std * 2, params))
| |
doc_23527042
|
Is it possible to define functions which have multiple statements defined within?
Context
I want to automate some of the calculations involved in creating stacked plots by defining functions. In particular, I was hoping to have something like
mp_setup(bottom_margin, top_margin) = \
set tmargin 0; \
set bmargin 0; \
mp_available_height = 1.0 - top_margin - bottom_margin; \
mp_current_height = bottom_margin;
mp_plot(plot_height) = \
mp_plot_size = plot_height * mp_available_height; \
set origin 0,mp_current_height; \
set size 1,mp_plot_size; \
mp_current_height = mp_current_height + mp_plot_size;
with the intended usage being:
...
set multiplot
mp_setup(0.05, 0.05)
mp_plot(1.0/3.0)
plot ...
mp_plot(2.0/3.0)
plot ...
and this should automatically result in the plots being nicely stacked without me having to calculate the origin and size for each graph.
Problem
The way of defining the functions above doesn't work because it seems like the parsing of the function definition ends at the first occurrence of ;; but these semicolons are necessary in order to separate each statement (otherwise, we have set tmargin 0 set bmargin 0... which is invalid).
It also seems like Gnuplot doesn't support any way of grouping statement (like {...} in C/C++); or at least, I have never come across it.
Possible Solution
The only method I know to store multiple functions and evaluate them is using macros:
mp_setup = "<as above>"
mp_plot = "<as above>"
But the issue here is that macros do not allow for arguments to be passed in and instead each variable would have to be declared beforehand as follows:
...
set multiplot
top_margin = 0.05
bottom_margin = 0.05
@mp_setup
plot_height = 1.0/3.0
@mp_plot
plot ...
plot_height = 2.0/3.0
@mp_plot
plot ...
This solution, although it should work, is not quite as elegant.
Is there no other way of doing this?
A: No, it isn't possible to define such functions. In gnuplot user-defined functions cannot contain set, unset or other commands. Only those kind of expressions are allowed, which return numerical or string variables. Here, you can have several expressions, separated by comma:
a = 0
f(x) = (a = a + 1, a + x)
print f(1)
print f(1)
Besides your solution to use macros (@var), I prefer constructing strings inside the function and calling eval:
set_margin(s, v) = sprintf('set %smargin at screen %f;', s, v)
set_margins(l, r, b, t) = set_margin('l', l).set_margin('r', r).set_margin('b', b).set_margin('t', t)
eval(set_margins(0.1, 0.95, 0.15, 0.98))
For your specific case of a multiplot layout you can also see Removing blank gap in gnuplot multiplot.
A: You can do like that
mp_setup(bottom_margin, top_margin)=(tmargin=0,bmargin=0,mp_available_height=1.0 -top_margin-bottom_margin,mp_current_height=bottom_margin)
test:
print mp_setup(0.05,0.05)
==> 0.05
As you mentioned, the grouping statement in the function is not supporting yet.
| |
doc_23527043
|
bundles.Add(new ScriptBundle("~/bundles/ui-scripts").Include(
"~/Scripts/ui-scripts.js"));
On my locale machine (http://localhost:57210/) this renders out as
<script src="/Scripts/ui-scripts.js"></script>
Locally all works fine.
The problem is, we have testing server that runs on Team City where the project is run under subfolder
(http://testserver.com/myApp/), but the rendered output is the same
<script src="/Scripts/ui-scripts.js"></script>
which causes ui-scripts.js fail to load (404) because it tries to load the script from http://testserver.com/Scripts/ui-scripts.js which of course is not there, because the script is in http://testserver.com/myApp/Scripts/ui-scripts.js
I expected the framework to realize that ~ points to the root of the project which in my case is http://testserver.com/myApp/
If I enable optimizations
BundleTable.EnableOptimizations = true;
The output is rendered optimized, but still from the wrong location, again, missing the myApp subfolder
<script src="/bundles/ui-scripts?v=mRQZjAGbYccSwhcFn4iouztfiK3Xjwik5TtdvD58fHM1"></script>
Additionally ,
if I don't use bundles but instead in the _Layout.cshtml where I want the script to appear, write in the code like this
<script src="~/Scripts/ui-scripts.js"></script>
Then the paths are recognised correctly on the server to
<script src="/myApp/Scripts/ui-scripts.js"></script>
Additionally,
If I create subdirectory on my localhost and store application there, the paths are resolved correctly.
The same problem goes for StyleBundle. Any idea what I could try?
A: I found the problem. There was problem with configuration for IIS on the testing server.
The project actually had it's own subdomain assigned to it, and was not supposed to be run from subdirectory.
Fiddling with IIS settings solved the issue.
| |
doc_23527044
|
So next(iter(train_ds.take(1))) returns the first Training-Data as expected, but next(iter(val_ds.take(1))) loads indefinitely.
My Dataset Contains multiple Image-Path-Triplets (<ZipDataset shapes: ((), (), ()), types: (tf.string, tf.string, tf.string)>).
My-Preprocessing looks something like this:
buffer_size = 1024
batch_size = 32
def prep_image(filename, img_shape=(144,144), channels=3, dtype=tf.float32):
image_string = tf.io.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=channels)
image = tf.image.convert_image_dtype(image, dtype)
image = tf.image.resize(image, img_shape)
return image
def preprocess_triplet(a, p, n):
return prep_image(a), prep_image(p), prep_image(n)
dataset = dataset.shuffle(buffer_size)
dataset = dataset.map(preprocess_triplet)
# splitting the ds
split = .8
n_train_items = round(len(dataset) * split) #r(514551 * 0.8) = 411641
train_dataset = dataset.take(n_train_items)
val_dataset = dataset.skip(n_train_items)
train_dataset = train_dataset.batch(batch_size, drop_remainder=False)
train_dataset = train_dataset.prefetch(tf.data.AUTOTUNE) #.prefetch(tf.data.AUTOTUNE)
val_dataset = val_dataset.batch(batch_size, drop_remainder=False)
val_dataset = val_dataset.prefetch(tf.data.AUTOTUNE)
When i run next(iter(train_dataset.take(1))) im getting my Image-Triplets as Tuple of Arrays (as expected). When i try to do the same on the Validation-Dataset it runs forever type(next(iter(val_dataset.take(1)))).
Verbose Version - Containing sanity Checks
python next(iter(dataset))
(<tf.Tensor: shape=(), dtype=string, numpy=b'F:\\workspace\\datasets\\own_256\\hm\\pics\\bf\\67\\bf67f3922e8245954943f1479961d932d56ef0ad.jpg'>,
<tf.Tensor: shape=(), dtype=string, numpy=b'F:\\workspace\\datasets\\own_256\\hm\\pics\\4b\\03\\4b03c337d013500930b71f9999766656f5893946.jpg'>,
<tf.Tensor: shape=(), dtype=string, numpy=b'F:\\workspace\\datasets\\own_256\\asos\\pics\\products\\asos-design-petite-halter-midi-beach-dress-in-double-gauze-in-sage-green\\24233155-2.jpg'>)
After Loading the Dataset and Shuffling
dataset = dataset.shuffle(buffer_size)
dataset = dataset.map(preprocess_triplet)
i just tried to "load" each entry, to check if the Images can be read:
for img in dataset:
a, b, c = img
assert a.shape == (144, 144, 3) and b.shape == (144, 144, 3) and c.shape == (144, 144, 3)
This run without any problems.
Afterwards i tried to Split the Dataset into Validation and Test
split = .8
n_train_items = round(len(dataset) * split) #r(514551 * 0.8) = 411641
train_dataset = dataset.take(n_train_items)
val_dataset = dataset.skip(n_train_items)
To test if i can access the Items i just called the first item of the batch per Val/Train DS:
next(iter(train_dataset))
$(<tf.Tensor: shape=(144, 144, 3), dtype=float32, numpy=
array(..., dtype=float32)>,
<tf.Tensor: shape=(144, 144, 3), dtype=float32, numpy=
array(..., dtype=float32)>,
<tf.Tensor: shape=(144, 144, 3), dtype=float32, numpy=
array(..., dtype=float32)>)
Also tried to iterate over all Train Data and it worked
print("t_items")
test_n_items = sum([sum([1 for item in a])for a, p, n in train_dataset])
print(test_n_items == n_train_items)
$True
But i cant even get the first item of Validation Dataset
next(iter(val_dataset))
Sadly the Second next(iter(val_dataset)) runs indefinitely.
Some Info
len(dataset)
$ 514551
len(train_dataset)
$411641
len(val_dataset)
$len(val_dataset)
len(dataset) == len(train_dataset) + len(val_dataset)
$True
Edit 1:
The Problem is withingprep_image, when i just return the Filename without opening the Data everything works as expected:
def prep_image(filename, img_shape=(144,144), channels=3, dtype=tf.float32):
return filename
# image_string = tf.io.read_file(filename)
# image = tf.image.decode_jpeg(image_string, channels=channels)
# image = tf.image.convert_image_dtype(image, dtype)
# image = tf.image.resize(image, img_shape)
# return image
Just reading the File:
def prep_image(filename, img_shape=(144,144), channels=3, dtype=tf.float32):
return tf.io.read_file(filename)
already produces the error of waiting for ever on Val-Dataset (Train still works).
Edit 2:
Simple Code to Reproduce the Issue:
https://colab.research.google.com/drive/1w5RQDp6W3Zyu4p1kEBRlHT2Vl9zvxVOk?usp=sharing
Edit 3:
Loading the first Item within the Training-Dataset (from the example of ´Edit 2takes 0.6 msand loading the first item of the Validation Dataset takes31.09 Minutes`
| |
doc_23527045
|
How to fetch a id from the database after record inserted in db?
Kindly help me out for displaying an id like "registration is suss-your id is ........."
package controller;
import java.io.IOException;
import java.io.PrintWriter;
javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2945154063362413961L;
/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
/*String fname=request.getParameter("firstname");
String lname=request.getParameter("lastname");*/
//pw.println("Firstname is" +fname);
//pw.println("Firstname is" +lname);
/*System.out.println("first=="+fname);
System.out.println("last==="+lname);
*/
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="Registrationform";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
try{
String Fname = request.getParameter("firstname");
String Lname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String email= request.getParameter("email");
Class.forName(driver).newInstance();
System.out.println("welcome");
conn = DriverManager.getConnection(url+dbName,dbUserName, dbPassword);
System.out.println("Connection created");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into event (firstname,lastname,dob,email) values(?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Lname);
pst.setString(3,dob);
pst.setString(4,email);
int i = pst.executeUpdate();
System.out.println("Query updated");
PreparedStatement pstr =(PreparedStatement) conn.prepareStatement("select * from event(id);");//try2 is the name of the table
//conn.commit();
String msg=" ";
if(i!=0){
msg="You Are Succesfully Register For The Event Meet";
//alert("You Are Succesfully Register For The E;vent Meet")
// response.sendRedirect("reg.jsp");
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
else{
msg="Failed to insert the data";
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
java script code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="reg.css">
<title>Event Registration From</title>
</head>
<body class= "main">
<script type="text/javascript">
function register(registerform)
{
if(registerform.firstname.value == "") {
alert("Please enter your Firstname");
registerform.firstname.focus();
return false;
}
if(registerform.lastname.value == "") {
alert("Please enter your Lastname");
registerform.lastname.focus();
return false;
}
if(registerform.dob.value == "") {
alert("Please select your DOB");
registerform.dob.focus();
return false;
}
if(registerform.email.value == "") {
alert("Please enter your Email-id");
registerform.email.focus();
return false;
}
/* var x=document.forms["form"]["email_id"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
} */
return true;
}
</script>
<form name="registerform" action ="Register" method = "post">
<div>
<h3> Event Registration Form </h3>
<div>
<label for ="first" class ="label" > First Name </label>
<input type="text" id="first" name="firstname" class="text" />
</div>
<div>
<label for ="last" class ="label">Last Name</label>
<input type="text" id="last" name="lastname" class="text">
</div>
<div>
<label for ="dob" class ="label">Date Of Birth </label>
<input type="text" id="dob" name="dob" class="text">
</div>
<div>
<label for ="email" class ="label">Email_Id</label>
<input type="text" id="email" name="email" class="text">
</div>
<div><input type="submit" value ="submit" class="button" onclick="register(registerform)"></div>
</div></form>
</body>
</html>
A: You can try something like this with MySQL:
PreparedStatement ps = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
// Get generated key.
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
int key = rs.getInt(1);
}
Where ps is the PreparedStatement and you retrieve the key from the ResultSet object.
A: To get the last generated auto-increment id you can use the MySql function LAST_INSERT_ID().
Another option would be to use the MAX aggregation function to return the maximum value for the id field. Since the last inserted id is always the max MAX(id).
Because this is a standard way, this has been added to a constant, so doing:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, Statement.RETURN_GENERATED_KEYS);
For some JDBC drivers like Oracle you have to specify the columns explicitly:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, new String[]{"USER_ID"});
| |
doc_23527046
|
I want to have a percentage progress bar displayed solely at the bottom of the terminal output, below all of the continuous output of the file processing activities. How could I do this?
Note that I do not have access to ncurses.
Using guidance from a previous question, I have a basic attempt here:
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
void print_progress_bar(int percentage){
string progress = "[" + string(percentage, '*') + string(100 - percentage, ' ') + "]";
cout << progress << "\r\033[F\033[F\033[F" << flush;
}
void print_stuff(){
int number_of_lines = (rand() % 9) + 1;
for (int i=0; i <= number_of_lines; ++i){
cout << "some junk output of " << number_of_lines << " lines\n";
}
}
int main(){
cout << endl;
for (int i=0; i <= 100; ++i){
std::cout << "processing file number " << i << "\n";
print_stuff();
print_progress_bar(i);
usleep(10000);
}
cout << endl;
cout << endl;
cout << endl;
cout << endl;
}
| |
doc_23527047
|
Code is below - I've omitted portions that didn't seem relevant:
app/controllers/worker/csr_activities_controller.rb
class Worker::CustomerSupportActivitiesController < Worker::BaseController
def index
PaperTrail::Version.search_versions(resource_params)
end
...
private
def resource_params
params.fetch(:query).permit(:whodunnit, :event, :item_type, :term, :start_date, :end_date)
end
end
app/controllers/concerns/search_versions.rb
module SearchVersions
extend ActiveSupport::Concern
def search_versions(params)
...
end
end
config/initializers/paper_trail.rb
PaperTrail.config.track_associations = false
PaperTrail.config.version_limit = 100
require Rails.root.join('./app/controllers/concerns/search_versions.rb')
module PaperTrail
class Version < ActiveRecord::Base
include SearchVersions
end
end
terminal
...
[51e4ee33-6308-4861-bf3a-e1c51ecdfac0] NoMethodError (undefined method `search_versions' for #<Class:0x007f94e5ed2a70>):
...
A: Classic - figured it out shortly after posting here. The issue can be fixed by changing:
include SearchVersions to extend SearchVersions inside config/initializers/paper_trail.rb.
Essentially, I need to use extend since I'm invoking the method on the Class Version which has been extended by the Module SearchVersions.
Edit: changed terminology based on engineersmnky's comment to prevent confusion.
| |
doc_23527048
|
Now I want to use those fields in another model. So, How can I give name to that field?
e.g.
I have table named as Config with fields(id,key).
Data can be
1, Blog url
2, Site url
Now, I have 1 form where admin will add those value to database.
In Yii2 we create input field like
<?= $form->field($model, 'name')->textInput() ?>
But I want to create two textboxes with name blog url and site url.
So, How can I create it? What I have to write in place of name?
A: run this code on your command prompt
php composer.phar require --prefer-dist wbraganca/yii2-dynamicform "*"
after completion of above code.
add the following code in your form.
_form.php
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Addresses</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'name',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Address</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]id");
}
?>
<?= $form->field($model, "[{$i}]name")->textInput(['maxlength' => true]) ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
| |
doc_23527049
|
<%= form_tag(:controller => 'orders' , :action => 'process_credit_card') do %>
... bunch of fields ...
<% end %>
carmen-rails' country_select helper looks like this
<%= f.country_select :country_code, {priority: %w(US CA)}, prompt: 'Please select a country' %>
however I do not have a form object f, I use helpers like <%= text_field_tag 'billing_address[phone]' %> to create my form, is there a way I can still use carmen in this form?
UPDATE: I am using ActiveMerchant for payment processing, I can create a form with form_for instead of form_tag but I don't know how, any pointers will be appreciated.
A: this should work...
<%= country_select :country_code, {priority: %w(US CA)}, prompt: 'Select' %>
A: I'm a few years late, but I ran into this problem tonight and found a solution that worked for me by crawling through the carmen-rails source code. Note that the second hash (as the fourth argument) can contain HTML options like class.
<%= country_select(nil, :country_code, { priority: %w(US CA) }, {}) %>
With the other solutions (that did not have nil as the first argument) I was having serialization issues with my AJAX search functionality. The entire hash (including priority and other code) would be serialized with the request. When calling it like I have above, this is no longer an issue and only the country code is serialized. Hopefully this will help someone in the future who ran into the same issue we did.
A: Please use
<%= country_select(nil,:country, { priority: %w(US CA) , prompt: 'Select Country'},:class=>"form-control") %>
Use above with form_tag
<%= f.country_select :country, {priority: %w(US CA), prompt: 'Select Country'},:class=>"form-control" %>
and use above with form_for
A: The correct way to do this isn't by using the country_select gem but a dependency it has countries gem and plain Rails form helpers select_tag and options_for_select: Using country_select gem with form_tag and no model
A: Try:
<%= country_select_tag :country_code, {priority: %w(US CA)}, prompt: 'Please select a country' %>
| |
doc_23527050
|
A: First, generate standard normal values and convert them to a normal distribution with given parameters. Finally, raise to exponential to get log-normal distribution with given mean and std dev.
Random rng = new Random(0);
double[] logNormalValues = new double[1000];
for (int i = 0; i < logNormalValues.length; i++) {
double stdNormal = rng.nextGaussian();
double normalValue = stdDev * stdNormal + mean;
logNormalValues[i] = Math.exp(normalValue);
}
A: you can also get a built in function here. in your above example, you won't actually end up with the stddev and mean noted -- they change when you exp() the values.
https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/distribution/LogNormalDistribution.html
A: or this
public static double LogNormal(double mean, double stddev) {
Random randGen = new Random();
double varx = Math.pow(stddev, 2);
double ess = Math.log(1.0 + (varx/Math.pow(mean,2)));
double mu = Math.log(mean) - (0.5*Math.pow(ess, 2));
return Math.pow(2.71828, (mu+(ess*randGen.nextGaussian() ) ) );
}
| |
doc_23527051
|
So we would get question who answers first data his answer gets submitted and we get next question and so on...
The idea is to have boolean field called answered in the database that would change to true onTap but my problem is how to handle page change since it would be PageView of questions.
I have set a streambuilder that generates PageView but having problem handling that database field listener.
I have no working code unfortunatelly besides StreamBuilder/PageView that looks like this.
return Scaffold(
appBar: AppBar(
title: Text("Lobby"),
),
body: StreamBuilder(
stream: _database.orderByKey().onValue,
builder: (context, snapshot) {
List<FirstRoundQuestion> frqList = [];
if (snapshot.hasData) {
(snapshot.data! as DatabaseEvent)
.snapshot
.children
.forEach((snapshot) {
final frq = Map<String, dynamic>.from(
snapshot.value as Map<dynamic, dynamic>);
frqList.add(FirstRoundQuestion(
question: frq['question'],
answer: frq['answer'],
answered: frq['answered']));
});
return PageView.builder(
reverse: true,
physics: const NeverScrollableScrollPhysics(),
controller: _controller.pageController,
itemCount: frqList.length,
itemBuilder: (context, index) {
return Column(
children: [
Text(frqList[index].question),
TextButton(
onPressed: () => {
///function placeholder
},
child: Text('${frqList[index].answered}'))
],
);
},
);
} else {
return const CircularProgressIndicator();
}
}));
Maybe I am completely wrong with how to go about this quiz app, any answer/advise would be helpfull :)
| |
doc_23527052
|
public string checkMD5(string filename)
{
string output;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
byte[] hash = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder(hash.Length);
foreach (byte b in hash)
{
sb.AppendFormat("{0:X2}", b);
}
output = filename + " MD5 Hash = " + sb.ToString();
}
}
return output;
}
The problem is, it is being fed a list of multiple filenames in the form of
C://file1
C://file2
C://file3
Code executes 1 filename just fine. How do I make the above loop through this list of filenames? Any help is much appreciated.. I have been at this for two days now :(
A: You can use String.Split() to split them, then just loop through each one:
string[] individualFileNames = filename.Split(' ');
foreach(string individualFileName in individualFileNames)
{
// open and process file individualFileName here
}
A: You would want a string array with the file names and then have a simple for or foreach loop:
for (int i = 0; i < fileNameArray.Length; i++)
{
string output = checkMD5(fileNameArray[i]);
}
or
foreach (string fileName in fileNameArray)
{
string output = checkMD5(fileName);
}
To get a array of file names from a directory you can use the function Directory.GetFiles.
Considering that you said the function is being fed a list of multiple filenames in the form of C://file1 C://file2 C://file3 I am going to assume that the file names are in a single string, if that's the case you will have to figure out a way to split it into an array of file names and then pass each one to the function as above, to do this you can try use String.Split like so:
string fileNames = "C://file1 C://file2 C://file3";
string[] fileNameArray = fileNames.Split(' ');
//fileNameArray[0] > C://file1
//fileNameArray[1] > C://file2
//fileNameArray[2] > C://file3
foreach (...)
Keep in mind that if any of the file names have spaces in their paths then this won't work, e.g.:
string fileNames = "C://Some Files//file1 C://file2 C://file3";
string[] fileNameArray = fileNames.Split(' ');
//fileNameArray[0] > C://Some
//fileNameArray[1] > Files//file1
//fileNameArray[2] > C://file2
//fileNameArray[3] > C://file3
In this example C://Some Files//file1 would be split into 2 because the path has a space in the directory name Some Files.
I would recommended just using Directory.GetFiles to get a list of file names than anything else.
| |
doc_23527053
|
java -Durl=http://localhost:8983/solr/update/extract?literal.id=1 -Dtype=application/word -jar post.jar microfost_det.doc
When I query the Solr Index it returns XML as ..
http://localhost:8983/solr/collection1/select?q=microfost&wt=xml&indent=true
The Response was :
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">0</int>
<lst name="params">
<str name="indent">true</str>
<str name="q">microfost</str>
<str name="_">1389196238897</str>
<str name="wt">xml</str>
</lst>
</lst>
<result name="response" numFound="1" start="0">
<doc>
<str name="id">1</str>
<date name="last_modified">1601-01-01T00:00:00Z</date>
<str name="author">fazlan </str>
<str name="author_s">fazlan </str>
<arr name="content_type">
<str>application/msword</str>
</arr>
<arr name="content">
<str>
This is a MSWord document. Microfost.
</str>
</arr>
<long name="_version_">1456677821213573120</long></doc>
</result>
</response>
Now my problem is , I need the name of the document that contains the queried text "microfost" that is , microfost_det.doc ..
Is it possible to get the name of the Word file (that is filename.doc) that contains the queried text ..
.
A: In Solr, the default searchable field is "content". That's why you are getting the result as it's matching with content. First create a custom string field (e.g docname) modifying your schema.xml
Then restart your Solr instance. Execute the following command to update your Solr doc.
curl 'http://localhost:8983/solr/update?commit=true' -H 'Content-type:application/json' -d '[{"id":"1","docname":{"set":"microfost_det.doc"}}]'
After that execute the following query and you'll get the result.
http://localhost:8983/solr/collection1/select?q=docname:microfost*&wt=xml&indent=true
Otherwise, while extracting the document execute the following command
java -Durl="http://localhost:8983/solr/update/extract?literal.id=1&literal.docname=microfost_det.doc" -Dtype=application/word -jar post.jar microfost_det.doc
Any way, you have to store the document name in a separate field.
| |
doc_23527054
| ||
doc_23527055
|
<asp:TreeView ID="mytv" runat="server" ImageSet="Arrows"
ondatabinding="Page_Load" onselectednodechanged="mytv_SelectedNodeChanged">
And the code-behind for this is as follows:
protected void mytv_SelectedNodeChanged(object sender, EventArgs e)
{
// how to call java-script function from here.
}
What I am trying to achieve is to display the content of div as per the tree-node clicked using JavaScript.
Or is there any other way to display the content from database or from div on clicking the treeview node.
A: Use this one inside the method:
ScriptManager.RegisterStartupScript(this, this.GetType(),
"anyName", "alert('test');", true);
A: I just reread your post, if you're just trying to get the selected value from the treeview, you can use something more like this in your JS
function CheckTreeValue()
{
var treeView = document.getElementById('treeviewID');
if(treeView.selectedNodeID.value != null)
{
var selectedNode = document.getElementById(treeView.selectedNodeID.value);
//Get Whatever you need from the node
var text = selectedNode.text;
WebService.PullValue(text, callback);
}
else // No Node Selected
return;
}
You can create the script manually by abusing an
<asp:Literal>
But it is better to use ScriptManager
ScriptManager.RegisterStartupScript(
this,
this.GetType(),
"UniqueScriptKey",
"FunctionYouWantToCall();
alert(document.getElementById('OrAnyJavascript').innerHTML);",
true);
| |
doc_23527056
|
void * foo __attribute__ ((section ("SEC_A"))) = NULL;
void bar(void) __attribute__ ((section("SEC_A")));
However when I do this, gcc complains with:
error: foo causes a section type conflict
If I do not declare the function with the specific section name, gcc is fine with it. But I want both the function and the variable to be in the same section.
Is there any way to do that with gcc? My gcc version is gcc (Ubuntu 4.3.2-1ubuntu12) 4.3.2
A: From the GCC manual:
Some file formats do not support arbitrary sections so the section attribute is not available on all platforms. If you need to map the entire contents of a module to a particular section, consider using the facilities of the linker instead.
IIRC, linux uses a flat memory model, so you don't gain anything by "forcing" things into a single section, anyway, do you?
Hmmm. I suppose you could make an asm function to reserve the space and then do pointer foo to get it's address. Might want to wrap the ugly in a macro...
Another thought would be to split the problem in half; write a small example case of the closest thing you can and still compile, get the asm code, and tinker with it to see what you can get past the downstream stages. If nothing else, you could write something to mungle the asm code for that module, entomb it in you make file, and call it good.
Yet another thought: try putting the variable definitions in a small asm module (e,g, as db's or whatever with the right section declarations) and let the linker handle it.
A: I think you cannot put text (function) and data (BSS) objects into the same section because (some) OSes assume immutability of .TEXT section types for process re-use.
| |
doc_23527057
|
For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true.
// A Java Program to detect cycle in a graph
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
class Graph {
private final int V;
private final List<List<Integer>> adj;
public Graph(int V)
{
this.V = V;
adj = new ArrayList<>(V);
for (int i = 0; i < V; i++)
adj.add(new LinkedList<>());
}
// This function is a variation of DFSUytil() in
// https://www.geeksforgeeks.org/archives/18212
private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack)
{
// Mark the current node as visited and
// part of recursion stack
if (recStack[i])
return true;
if (visited[i])
return false;
visited[i] = true;
recStack[i] = true;
List<Integer> children = adj.get(i);
for (Integer c: children)
if (isCyclicUtil(c, visited, recStack))
return true;
recStack[i] = false;
return false;
}
private void addEdge(int source, int dest) {
adj.get(source).add(dest);
}
// Returns true if the graph contains a
// cycle, else false.
// This function is a variation of DFS() in
// https://www.geeksforgeeks.org/archives/18212
private boolean isCyclic()
{
// Mark all the vertices as not visited and
// not part of recursion stack
boolean[] visited = new boolean[V];
boolean[] recStack = new boolean[V];
// Call the recursive helper function to
// detect cycle in different DFS trees
for (int i = 0; i < V; i++)
if (isCyclicUtil(i, visited, recStack))
return true;
return false;
}
// Driver code
public static void main(String[] args)
{
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 0);
graph.addEdge(2, 3);
graph.addEdge(3, 3);
if(graph.isCyclic())
System.out.println("Graph contains cycle");
else
System.out.println("Graph doesn't "
+ "contain cycle");
}
}
Thank you so much.
A: Edit:
Previously I mentioned the possibility to use dfs instead of bfs,
however using dfs might produce non-minimal cycles. (e.g. if a cycle A->B->C->A exists and a cylce A->B->A exists, it might find the longer one first and it won't find the second one as nodes are only visited once).
As per definition an elementary cycle is one where a node does not repeat itself (besides the starting one), so the case is a bit different. As the questioner (of the bounty @ExceptionHandler) wanted those cycles excluded from the output, using bfs solves that issue.
For a pure (brute-force) elementary cycle search a different path finding algorithm would be required.
A general purpose (aka brute force) implementation would entail the following steps:
*
*For every node n of a directed graph gfind all pathes (using bfs) back to n.If muliple edges between two nodes (with the same direction) exist they can be ignored at this step, as the algorithm itself should work on nodes rather than edges. Multiple edges can be reintroduced into the cycles during step 5.
*if no pathes are found, continue in Step 1 with n+1
*Every identified path is a cylceadd them to a list of cycles, and continue with Step 1 and n+1
*After all nodes have been processed a list containing all possible cycles have been found (including permutations). Subcycles could not have been formed as every node can only be visited once during bfs.In this step all permutations of previously identified are grouped in sets. Only one cylce per set is considered. This can be done by ordering the node and removing duplicates.
*Now the minimum set of cycles has been identified and can be printed out.In case you are looking for edge-specific cycles, replace the connection between two nodes with their respective edge(s).
Example for the graph A->B B->C C->D D->C C->A:
Step 1-3: node A
path identified: A,B,C (A->B B->C C->A)
Step 1-3: node B
path identified: B,C,A (B->C C->A A->B)
Step 1-3: node C
path identified: C,A,B (C->A A->B B->C)
path identified: C,D (C->D D->C)
Step 1-3: node D
path identified: D,C (D->C C->D)
Step 4:
Identified as identical after ordering:
Set1:
A,B,C (A->B B->C C->A)
B,C,A (B->C C->A A->B)
C,A,B (C->A A->B B->C)
Set2:
C,D (C->D D->C)
D,C (D->C C->D)
Therefore remaining cycles:
A,B,C (A->B B->C C->A)
C,D (C->D D->C)
Step 5:
Simply printing out the cycles
(Check the bracket expressions for that,
I simply added them to highlight the relevant edges).
A more efficient sample implementation to identify elementary cycles can be found here, which was directly taken from this answer. If someone wants to come up with a more detailed explanation how that algorithm works exactly feel free to do so.
Modifing the main method to:
public static void main(String[] args) {
String nodes[] = new String[4];
boolean adjMatrix[][] = new boolean[4][4];
for (int i = 0; i < 4; i++) {
nodes[i] = String.valueOf((char) ('A' + i));
}
adjMatrix[0][1] = true;
adjMatrix[1][2] = true;
adjMatrix[2][3] = true;
adjMatrix[3][2] = true;
adjMatrix[2][0] = true;
ElementaryCyclesSearch ecs = new ElementaryCyclesSearch(adjMatrix, nodes);
List cycles = ecs.getElementaryCycles();
for (int i = 0; i < cycles.size(); i++) {
List cycle = (List) cycles.get(i);
for (int j = 0; j < cycle.size(); j++) {
String node = (String) cycle.get(j);
if (j < cycle.size() - 1) {
System.out.print(node + " -> ");
} else {
System.out.print(node + " -> " + cycle.get(0));
}
}
System.out.print("\n");
}
}
leeds to the desired output of:
A -> B -> C -> A
C -> D -> C
Donald B. Johnson paper that describes the approach in more detail can be found here.
| |
doc_23527058
|
Actually, it is only angular2 project, but with ionic component. When I open chrome dev tool and select "go to file", I can not find the .ts file that I want to debug at all.
This is strange to me. I can easily debug any angular2 project, why not in ionic?
I want to use ionic3/angular4 to develop a mobile web.
Is ionic also using webpact, if so, I think I just need to enable sourcemap and then debug it in chrome dev tool.
Have you ever successfully debugged ionic .ts file in chrom?
A: Very simple
Open package.json add below code .
"config": {
"ionic_bundler": "webpack",
"ionic_source_map_type": "#inline-source-map"
}
do chrome://inspect you can see the source file
A: If you are using Visual Studio Code you can install the Cordova Tools extension, which will let you debug on the device, it is a very powerful tool for VSCode which is also the best Editor/IDE that I have found to develop Ionic 3 and Angular 4 apps.
The procedure is straight forward:
*
*Delete existing launch.json file from .vscode directory and go to Debugger and click on the little gear icon.
*Select Cordova as the debugger.
*The extension will create 12 configs for you actually, we need the first one which is 'Run Android on device'
*Now, this is what I do (Mac OS X Sierra), depending on how and what components you have installed in your system this may change. I open Android Studio and then connect my usb cable which is attached to my android test device.
*Once I see my device listed in the Android Monitor Panel and the debug processes running in the Logcat tab, I switch to my VSCode Window and issue in the terminal: ionic cordova android run, then wait for the app to launch on the phone.
*Once the app is showing in the device, click the debug button in VSCode and the debugger should attach.
*Now your the debugger should hit your breakpoints and let you debug your typescript code with the app running on your test device.
I guess you could also debug directly from the Chrome Developer Tools, but it may require you to configure some more additional options regarding location of your source map files within tsconfig.json. I rather recommend you vscode as it has tons of useful features, it's free and also has extensions for Ionic 3 snippets, autocompletion and CLI commands from the UI.
| |
doc_23527059
|
Html:
<body>
<div id="container">
<nav>
<h1> Menu<span id="openIcon"> <i class="fa fa-align-justify" aria-hidden="true"></i></span></h1>
<ul id="sidemenu" style="list-style-type:none">
<li class="list"> <a href="https://yahoo.co.in">Yahoo!!</a></li>
<li class="list"> <a href="https://gmail.com"> GMail </a></li>
<li class="list"> <a href= "https://twitter.com">twitter</a></li>
</ul>
</nav>
</div>
<script src="sidemenu.js"></script>
</body>
A: try with simple side menu
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
(function(){
$('#openIcon').on('click', function(){
$('#sidemenu').toggleClass('active');
});
})();
#openIcon {
cursor: pointer;
}
#sidemenu {
left: -100%;
position: absolute;
}
.active {
left: 0 !important;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<nav>
<h1> Menu<span id="openIcon"> <i class="fa fa-align-justify" aria-hidden="true"></i></span></h1>
<ul id="sidemenu" style="list-style-type:none">
<li class="list"> <a href="https://yahoo.co.in">Yahoo!!</a></li>
<li class="list"> <a href="https://gmail.com"> GMail </a></li>
<li class="list"> <a href= "https://twitter.com">twitter</a></li>
</ul>
</nav>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
and if you need full width menu use something like this
(function(){
var $hideElement = $('#menuDiv');
$('#menu').on('click', function(){
$hideElement.addClass('opend');
});
$('#active_menu').on('click', function(){
$hideElement.removeClass('opend');
});
})();
#menuDiv {
position:fixed;
left:-100%;
top:0;
width:100%;
height:100%;
background:#F5CFD0;
z-index:999;
overflow-x:hidden;
transition-duration:05s;
-moz-transition-duration:0.5s;
-ms-transition-duration:0.5s;
-webkit-transition-duration:0.5s;
}
.opend {
left:0 !important;
}
#active_menu {
position: absolute;
top: 0;
right: 20px;
width: 100%;
padding-top: 15px;
text-align: right;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<a href="#" id="menu"><i class="fa fa-align-justify" aria-hidden="true"></i></a>
<div id="menuDiv">
<a href="#" id="active_menu"><i class="fa fa-times" aria-hidden="true"></i></a>
</div><!-- /.menuDiv -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
A: try with below for side menu
<html>
<head>
<style>
body {
font-family: "Lato", sans-serif;
}
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: #818181;
display: block;
transition: 0.3s
}
.sidenav a:hover, .offcanvas a:focus{
color: #f1f1f1;
}
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
#main {
transition: margin-left .5s;
padding: 16px;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</style>
</head>
<body>
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="https://yahoo.co.in">Yahoo!!</a>
<a href="https://gmail.com"> GMail </a>
<a href= "https://twitter.com">twitter</a>
</div>
<div id="main">
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ Menu</span>
</div>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}
</script>
</body>
</html>
A: <div id="container">
<nav>
<h1> Menu<span id="openIcon" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse"> <i class="fa fa-align-justify" aria-hidden="true"></i></span></h1>
<ul id="bs-example-navbar-collapse" style="list-style-type:none">
<li class="list"> <a href="https://yahoo.co.in">Yahoo!!</a></li>
<li class="list"> <a href="https://gmail.com"> GMail </a></li>
<li class="list"> <a href= "https://twitter.com">twitter</a></li>
</ul>
</nav>
</div>
| |
doc_23527060
|
using (SqlDataReader reader = exportCmd.ExecuteReader())
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";
while (reader.HasRows)
{
while (reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}
writer.Write(reader.GetValue(columnCounter).ToString());
}
writer.WriteLine(string.Empty);
}
reader.NextResult();
}
writer.Dispose();
}
Thanks in advance
A: You could use SqlDataReader.IsDBNull to check whether the column is null, and removed redundant data read as Yosi Dahari mentioned.
using (SqlDataReader reader = exportCmd.ExecuteReader())
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";
while (reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
writer.Write(Separator);
if (reader.IsDBNull(columnCounter))
writer.Write(string.Empty);
else
writer.Write(reader.GetValue(columnCounter).ToString());
}
writer.WriteLine(string.Empty);
}
writer.Dispose();
}
A: This should do the trick
Based on your code i removed all unnecessary lines of code.
As others already said, you were skipping some lines because of this reader.NextResult();
Further more, you dont have to dispose a reader/writer while you are in a Using-block
using (SqlDataReader reader = exportCmd.ExecuteReader()) {
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";
while (reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}
writer.WriteLine(reader.GetValue(columnCounter).ToString());
}
}
}
}
A: One of your results doesnt return any rows, thats why you are missing rows, the outer while (reader.HasRows) exits without checking for next result.
using (SqlDataReader reader = exportCmd.ExecuteReader())
using (StreamWriter writer = new StreamWriter(exportFilename))
{
string Separator = ",";
while (reader.HasRows)
{
while(reader.Read())
{
for (int columnCounter = 0; columnCounter < reader.FieldCount; columnCounter++)
{
if (columnCounter > 0)
{
writer.Write(Separator);
}
writer.Write(reader.GetValue(columnCounter).ToString());
}
writer.WriteLine(string.Empty);
}
While(reader.NextResult() && !reader.hasrows)
{
// might be a bette way to do this , problem is that one of your result has no rows, then it exits...
}
}
writer.Dispose();
}
| |
doc_23527061
|
Code:
app.py
from flask import Flask, request
from flask.templating import render_template
app = Flask(__name__)
app.secret_key = 'mysecret'
app.config["TEMPLATES_AUTO_RELOAD"] = True
@app.route("/")
def index():
items = ["backpack", "handbag", "laptop"]
return render_template("index.html", items=items)
if __name__ == "__main__":
app.secret_key = 'mysecret'
app.run(debug = True)
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
<script type="text/javascript">
var data = '{{ items }}'
myFunc(data)
</script>
</head>
<body>
<div id="dvTable"></div>
</body>
</html>
app.js
function myFunc(data) {
var table = document.createElement("table");
row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = 'Item';
for (var i = 0; i < data.length; i++)
{
var cell = row.insertCell(-1);
cell.innerHTML = data[i];
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
This is not returning anything on the screen. There are no exceptions. Please tell me what's the issue here?
A: You can convert the variable within jinja2 into a json object using the built-in filter tojson.
var data = {{ items | tojson }}
When executing a javascript function which is to change DOM elements, it is important to ensure that these are already loaded. One possibility is the listener used in my example. Another possibility is to put the script tags at the end of the file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
<script type="text/javascript">
(function(items) {
document.addEventListener('DOMContentLoaded', function() {
myFunc(items);
});
})({{ items | tojson }});
</script>
</head>
<body>
<div id="dvTable"></div>
</body>
</html>
| |
doc_23527062
|
ls *.wav -recurse | get-filehash | group -property hash | where { $_.count -gt 1 } | % { $_.group | select -skip 1 } | del
I have two issues. I want to limit this to only one filehash at a time and I need to specify the file name I want to keep.
As an example, I have a folder named Recordings. The first five files listed all have the same filehash but only one has the filename that has already been entered in my database.
Recordings
It would be great if I could use the -Exclude parameter for the del cmdlet but that parameter does not accept pipeline input.
I also considered using the code above and then renaming the remaining file afterward but the code is not limited to one filehash.
A: It all depends on how you want it to work. For example, if you know the file name you want to keep in advance, you could do it this way:
$fileName = 'file1.txt'
$fileHash = Get-FileHash .\$filename
$duplicates = ls -Recurse | Get-FileHash | Where-Object {$_.Hash -eq $fileHash.Hash -and ($_.Path | Split-Path -Leaf) -ne $fileName }
$duplicates | del
This sequence sets the filename, gets the hash of that file, and then the main command checks for other files with that same hash that doesn't have the same filename.
Note: Test first to make sure this will do what you expect before you execute the del command.
Update: It appears that Get-FileHash puts some sort of lock on the files being hashed so you cannot immediately pipe to the del (Remove-Item) command. I modified the results to save the array of duplicates to a variable and then pass that to the delete command which works.
| |
doc_23527063
|
I do about a dozen other Google API calls in the script (that work), so, no it's not a permission/scope issue. No errors are thrown during the ASP part of the script. It just "processes" the call and continues. Very strange.
When I use the Try this API section on Google it works just fine and removes the ASP that I specify.
Is anyone else experiencing this issue?
Here is the section of the pertinent code:
scopes = ['https://www.googleapis.com/auth/admin.directory.user.security',
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/gmail.settings.sharing',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/admin.datatransfer',
'https://www.googleapis.com/auth/admin.directory.group']
credentials = ServiceAccountCredentials.from_json_keyfile_name('../service-account-key.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('REDACTED')
http_auth = delegated_credentials.authorize(Http())
directory_service = discovery.build('admin', 'directory_v1', http=http_auth)
def remove_asps():
##############################################################################################################################
'''
REMOVE ALL APP SPECIFIC PASSWORDS
'''
##############################################################################################################################
asp = directory_service.asps().list(userKey='{0}'.format(user_email)).execute()
app_specific_passwords = asp.get('items', [])
print('3) Removing App Specific Passwords:')
if not app_specific_passwords:
print('- {0} does not have any App Specific Passwords to remove.'.format(user_email))
print('')
else:
for app_specific_password in app_specific_passwords:
print('- Removing App Specific Password - {0} from {1}'.format(app_specific_password['name'],user_email))
delete_asps = directory_service.asps().delete(userKey='{0}'.format(user_email),codeId='{0}'.format(app_specific_password['codeId']))
print('Done.')
print('')
I have also attempted to hard code the values into the call and removing the for-loop, rather than using variables, and that does not work either.
The logs show that the call is run, but no errors are thrown:
googleapiclient.discovery: INFO URL being requested: DELETE https://www.googleapis.com/admin/directory/v1/users/redacted_email/asps/0?
googleapiclient.discovery: INFO URL being requested: DELETE https://www.googleapis.com/admin/directory/v1/users/redacted_email/asps/1?
googleapiclient.discovery: INFO URL being requested: DELETE https://www.googleapis.com/admin/directory/v1/users/redacted_email/asps/2?
Thanks in advance for the help!
| |
doc_23527064
|
project build error non-resolvable import POM: failure to transfer org.jboss.spec:jboss-javaee-6.0:pom:3.0.0.beta1 from http:\\repo1.maven2 was cashed in the local repository,resolution will not be reattempted until the update interval of central
Project build error:'dependencies.dependency.version'for javax.enterprise:cdi-api:jar is missing.
Project build error:'dependencies.dependency.version'for org.jboss.spec.javax.annotation:jboss-annotation-api_1.1_spec:jar is missing.
Project build error:'dependencies.dependency.version'for org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:jar is missing.
It gives this errors when it start to run..
[INFO] Scanning for projects...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http:\\www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Downloading: http:\\repo1.maven.org/maven2/org/jboss/spec/jboss-javaee-6.0/3.0.0.Beta1/jboss-javaee-6.0-3.0.0.Beta1.pom
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project org.jboss.as.quickstarts:jboss-as-helloworld:7.1.1-SNAPSHOT (C:\Users\Heshan\workspace\helloworld\jboss-as-helloworld\pom.xml) has 4 errors
[ERROR] Non-resolvable import POM: Could not transfer artifact org.jboss.spec:jboss-javaee-6.0:pom:3.0.0.Beta1 from/to central (http://repo1.maven.org/maven2): Connect times out @ line 39, column 22 -> [Help 2]
[ERROR] 'dependencies.dependency.version' for javax.enterprise:cdi-api:jar is missing. @ line 53, column 19
[ERROR] 'dependencies.dependency.version' for org.jboss.spec.javax.annotation:jboss-annotations-api_1.1_spec:jar is missing. @ line 61, column 19
[ERROR] 'dependencies.dependency.version' for org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:jar is missing. @ line 69, column 19
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http:\\cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http:\\cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
[INFO] Scanning for projects...
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http:\\www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Downloading: http:\\repo1.maven.org/maven2/org/jboss/spec/jboss-javaee-6.0/3.0.0.Beta1/jboss-javaee-6.0-3.0.0.Beta1.pom.
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR] The project org.jboss.as.quickstarts:jboss-as-helloworld:7.1.1-SNAPSHOT (C:\Users\Heshan\workspace\helloworld\jboss-as-helloworld\pom.xml) has 4 errors
[ERROR] Non-resolvable import POM: Could not transfer artifact org.jboss.spec:jboss-javaee-6.0:pom:3.0.0.Beta1 from/to central (http://repo1.maven.org/maven2): Connect times out @ line 39, column 22 -> [Help 2]
[ERROR] 'dependencies.dependency.version' for javax.enterprise:cdi-api:jar is missing. @ line 53, column 19
[ERROR] 'dependencies.dependency.version' for org.jboss.spec.javax.annotation:jboss-annotations-api_1.1_spec:jar is missing. @ line 61, column 19
[ERROR] 'dependencies.dependency.version' for org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:jar is missing. @ line 69, column 19
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http:\\cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http:\\cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
A:
Non-resolvable import POM: Could not transfer artifact
org.jboss.spec:jboss-javaee-6.0:pom:3.0.0.Beta1 from/to central
(http://repo1.maven.org/maven2): Connect times out @ line 39, column
22 -> [Help 2
Your connection to maven central repo times out. You have a network connectivity issue. Maybe you don't have network connection, or maybe you need to configure a proxy if you do.
By using this link you can see the file actually is in there, so you should be able to download it.
| |
doc_23527065
|
I have a few url match cases, however I want to make them match not just on an explicit url, example:
app.config(function($stateProvider, paths) {
var base = paths.static.views + 'modules/';
$stateProvider
.state('home', {
url : '/',
views : {
'home' : {
templateUrl : base + 'home/_layout.html',
controller: function() {
console.log('home');
}
}
}
})
.state('foo', {
url : '/foo',
views : {
'foo' : {
templateUrl : base + 'foo/_layout.html',
controller: function() {
console.log('foo');
}
}
},
})
.state('bar', {
url : '/bar*',
views : {
'bar' : {
templateUrl : base + 'bar/_layout.html',
controller: function() {
console.log('bar');
}
}
},
})
.state('dog', {
url : '/dog*',
views : {
'dog' : {
templateUrl : base + 'dog/_layout.html',
controller: function() {
console.log('dog');
}
}
},
});
});
So if I navigate to /foo it works, however if my server has a re-write rule (which it does in some cases) it will re-write it to /foo/ and the match case no longer fires.
I've tried adding {url : '/foo*'} but that didn't work either.
I would really like to fix this!
| |
doc_23527066
|
Is there a way to do this?
A: To pause the conversation with the bot, if the user asks to be handed off to a human, you can write a rule that executes a custom action when that intent is triggered, which returns a ConversationPaused event. That way the bot stops listening to the user, and a person from your admin page can reply. There is a ConversationResumed event in that link which you can use to resume the conversation with the bot again.
| |
doc_23527067
|
public class ImageUpdaters : List<IImageUpdater>
{
public ImageUpdaters()
{
Add(new ApplicationTileBackImageUpdater(ApplicationUnits.Imperial));
Add(new ApplicationTileBackImageUpdater(ApplicationUnits.Metric));
Add(new ApplicationTileFrontImageUpdater(ApplicationUnits.Imperial));
Add(new ApplicationTileFrontImageUpdater(ApplicationUnits.Metric));
...
}
}
It's not quite as simple as just passing in a list of all the implementations of IImageUpdater since most are parameterised.
I have another slightly more complicated example where some objects need to share the same instance
public DataProcessors()
{
var snowReportRetriever = new CachingDataRetriever(new UriRetriever("http://.."));
var notificationSender = new NotificationSender(new MessageGenerator(new SQLDataReader()), new MessageSender());
var snowDepthProcessor = new DataProcessor<SnowDepthModel>(
"SnowDepthFact"
, snowReportRetriever
, new SnowDepthParser()
, new SnowDepthModelPersistor()
, new SnowDepthModelNotifier(notificationSender)
, new SQLDataReader());
var runsOfTheDayProcessor = new DataProcessor<ModelList<RunsOfTheDayModel>>
(
"RunsOfTheDayFact"
, snowReportRetriever
, new RunsOfTheDayParser()
, new RunsOfTheDayModelPersistor()
, new SQLDataReader());
...
EDIT: I'm getting somewhere, I can register the individual ImageUpdaters and the List but the list is empty so my assertion fails?
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
container.Register(
Component.For<IList<IImageUpdater>>()
.ImplementedBy<List<IImageUpdater>>()
);
container.Register(
Component.For<IImageUpdater>()
.ImplementedBy<ApplicationTileFrontImageUpdater>()
.DependsOn(Property.ForKey<ApplicationUnits>().Eq(ApplicationUnits.Metric))
.Named("ApplicationTileFrontImageUpdaterMetric")
);
...
var imageUpdaters = container.Resolve<IList<IImageUpdater>>();
Assert.AreEqual(13,imageUpdaters.Count);
A: I've worked it out, if anyone has any feedback on whether this is a good/best solution I'd be very interested
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
container.Register(
Component.For<IImageUpdater>()
.ImplementedBy<ApplicationTileFrontImageUpdater>()
.DependsOn(Property.ForKey<ApplicationUnits>().Eq(ApplicationUnits.Metric))
.Named("ApplicationTileFrontImageUpdaterMetric")
);
container.Register(
Component.For<IImageUpdater>()
.ImplementedBy<ApplicationTileFrontImageUpdater>()
.DependsOn(Property.ForKey<ApplicationUnits>().Eq(ApplicationUnits.Imperial))
.Named("ApplicationTileFrontImageUpdaterImperial")
);
....
container.Register(
Component.For<TestImageUpdaterClass>()
.ImplementedBy<TestImageUpdaterClass>()
);
var tiuc = container.Resolve<TestImageUpdaterClass>();
Assert.AreEqual(13, tiuc.ImageUpdaters.Count);
Then for test purposes a class that consumes a list of IImageUpdaters
public class TestImageUpdaterClass
{
public IList<IImageUpdater> ImageUpdaters { get; set; }
public TestImageUpdaterClass(IList<IImageUpdater> imageUpdaters)
{
ImageUpdaters = imageUpdaters;
}
}
| |
doc_23527068
|
filename x '/mydir/*.sas';
%include x/source2;
Additionally, I need the files to be executed in alphabetical order, e.g.
01_setup_libraries.sas
02_transfer_data.sas
03_create_tables.sas
My tests indicate that this is how filename behaves in that context and that I can just use the code above - however, I am unable to find confirmation if this is actually how filename works.
Is there any documentation on this, or is there an alternative with comparingly little amount of code? (My best guess was to output the files to a dataset, sort the dataset, then execute record by record).
A: Modifying u/Lawrence's solution to use CALL EXECUTE instead which is easier to debug.
%let in_directory = .....;
Filename _dir_ "%bquote (&in_directory.)";
data files_available (keep = Filename);
directory = dopen ( '_dir_' );
if directory > 0 then do;
numfiles = dnum(directory);
do i = 1 to numfiles;
Filename = dread(directory, i);
output files_available;
end;
end;
rc = dclose(directory);
run;
Filename _dir_ clear;
proc sort data=files_available;
by filename;
run;
data files_run;
set files_available;
str = catt('%include ', quote(filenames), " /source2;");
call execute(str);
run;
A: I think your best guess is a good idea, output the file names to a dataset, sort and then %include them:
%macro get_filenames(in_directory);
/* Getting a list of filenames in a directory*/
Filename _dir_ "%bquote (&in_directory.)";
data files_available (keep = Filename);
directory = dopen ( '_dir_' );
if directory > 0 then do;
numfiles = dnum(directory);
do i = 1 to numfiles;
Filename = dread(directory, i);
output files_available;
end;
end;
rc = dclose(directory);
run;
Filename _dir_ clear;
%mend;
%get_filenames(mydir);
proc sql;
select
count(*)
,filename
into
:num_files
,:filenames separated by "|"
from files_available
order by filename;
quit;
%macro run_programs;
%do i=1 %to &num_files.;
%let filename = %scan(%str(&filenames.),&i.,%str(|),m);
%include "mydir/&filename.";
%end;
%mend;
%run_programs;
Some of this will need a tweak but hopefully it helps.
A: Question has been answered in Tom's comment under initial post:
"It will read the files in alphabetical order on Linux, but filenames are case sensitive. So uppercase letters sort before lowercase letters. On Windows it reads them in alphabetical order based on the uppercase version of the filename. Since window file names are not case sensitive then it is essentially also alphabetical." - Tom
| |
doc_23527069
|
The current problem is I cannot change each row along with each result. For example, this is the first chat and the outcome.
Then, a user move on next chat, the next chat rewrite previous chat like this.
this is the code.
...
const renderItem = ({item, index}) => {
return (
<>
<ChatBubble
kind={item.roll}
sentence={item.sentence}
key={item.sentenceNo}
keyValue={item.sentenceNo}
ipaData={ipaData[index]}
resultFlg={resultFlg[conversationIdx]}
anatomyData={anatomyData[conversationIdx]}
phoResultId={phoResultId[conversationIdx]}
/>
</>
);
};
....
<FlatList
keyExtractor={item => item.sentenceNo}
data={conversationContents}
renderItem={renderItem}
style={{marginBottom: 30}}
extraData={[
resultFlg[conversationIdx],
anatomyData[conversationIdx],
phoResultId[conversationIdx],
]}
....
ChatBubble.tsx
...
<CommonMaterialResult
sentence={props.sentence}
ipaData={props.ipaData}
resultFlg={props.resultFlg}
anatomyData={props.anatomyData}
phoResultId={props.phoResultId}
kind={KIND[2]}
/>
...
[CommmonMaterialResult]
...
return (
<View
style={{
marginTop: 0,
marginHorizontal: 0,
marginBottom: 0,
paddingTop: 0,
paddingHorizontal: 0,
}}>
{/* Target Material */}
<View
style={{
alignItems: 'center',
}}>
{props.anatomyData ? (
<WordColored
anatomyData={props.anatomyData}
phoResultId={props.phoResultId}
ipaData={props.ipaData}
kind={props.kind}
/>
) : (
<Text
style={{
fontSize: 15,
// lineHeight: 25,
}}>
{props.sentence}
</Text>
)}
</View>
</View>
);
...
[WordColored]
...
return (
<TouchableOpacity onPress={() => openWindow(wordList, idx)}>
{props.kind === KIND[2] ? (
<Text
style={{
marginRight: 0,
fontSize: 15,
marginRight: 5,
color: font.color,
}}>
{p[1]}
</Text>
) : (
<Text
style={{
marginRight: 5,
fontSize: 23,
lineHeight: 28,
color: font.color,
}}>
{p[1]}
</Text>
)}
</TouchableOpacity>
);
})}
...
| |
doc_23527070
|
(gdb) define print_and_continue
Type commands for definition of "print_and_continue".
End with a line saying just "end".
>break $arg0
>command $bpnum
>print $arg1
>continue
>end
>end
So I want to print the value of variable len which is defined in linked_list.h:109. And I execute the following code:
(gdb) print_and_continue linked_list.h:111 len
Breakpoint 1 at 0x388a: linked_list.h:111. (12 locations)
(gdb) r
...
Breakpoint 1, linked_list<test_struct<1>, 1>::remove_if<run_test<1, 1, 1>(std::vector<int, std::allocator<int> >&)::{lambda(test_struct<1> const&)#1}>(run_test<1, 1, 1>(std::vector<int, std::allocator<int> >&)::{lambda(test_struct<1> const&)#1}&&) (this=0x7fffffffdca0, condition=...) at linked_list.h:112
112 linked_list_node* prev = nullptr;
$1 = void
It seems like $arg1 in print function didn't get replaces by the actual argument. What am I doing wrong?
A:
It seems like $arg1 in print function didn't get replaces by the actual argument.
I don't believe that's what is actually happening. Rather, everything following command $bpnum is attached to the newly-created breakpoint literally (without any expansion at all). You can see that happening with info break, which will show something like:
Num Type Disp Enb Address What
1 breakpoint keep y 0x0000000000001136 at ...
print $arg1
continue
This is generally what you would want (deferring evaluating the argument until the time breakpoint is hit). Otherwise you would print current value of len if you use print len, when what you want is to print the value of len when the breakpoint is hit.
Of course, when the breakpoint is hit, there is no $arg1 (or $arg0) anywhere around, so you get the same output you'd get trying to print any other non-existent GDB variable.
What am I doing wrong?
You are using "quick hack of a language" (which is what the "native" GDB scripting language is), instead of using a proper programming language.
I am 99.99% certain that defining print_and_continue is possible (and probably quite easy) using embedded Python.
That said, I don't believe that print_and_continue is all that useful (in my 20+ years of using GDB, I never needed anything like that).
| |
doc_23527071
|
Sentence is the user input
sentence.replaceAll("\\D", "");
int i = Integer.parseInt(sentence);
i = i * 2 ;
woah.replaceAll("\\d", "" + i);
System.out.println(woah);
A: Strings are immutable.
Generally, every modification you made on an immutable object will "give" you another immutable object.
So it should be :
sentence = sentence.replaceAll("\\D", "");
Indeed you have to do the same for woah.
You may read about what is an immutable object.
| |
doc_23527072
|
the error message
homepage.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '0')
const dispatch = useDispatch();
const danceClass = useSelector((state) => state.class);
const { classes } = danceClass;
const [dance, setDance] = useState(
classes[0] ? classes[0].slice(0, 3) : [],
);
A: If your danceClass object doesn't have a classes property, then classes will be undefined and classes[0] will produce the error you're seeing.
Try using optional chaining instead
const [dance, setDance] = useState(classes?.[0]?.slice(0, 3) ?? []);
The above will also work if classes is an empty array.
A: Because the classes is undefined. You should check like
classes ? classes[0]?.slice(0,3) : []
A: I would suggest you to use fallbacks for possibly undefined values for instance
const dispatch = useDispatch();
const danceClass = useSelector((state) => state?.class ?? {});
const { classes = [] } = danceClass;
const [dance, setDance] = useState(
classes[0]?.slice(0, 3) ?? [],
);
Like that, you are going to check whather or not state.class is a nullish value, if it's nullish, with the use of nullish coaleascing operator you are going to assign an empty object.
Then, when destructuring for classes, if danceClass is an empty object without the property classes, what you're getting is a variable classes initialized as an empty array.
Then again, with the use of chaining operator in classes[0]?.slice(0, 3) you're checking if the first element is nullish, (through the optional chaining operator) if this is your're going to set the dance variable as an empty array again with the use of nullish coaleascing operator
| |
doc_23527073
|
There are quite a few similar discussions on here, and I have tried the suggestions, as well as various examples from the Three.js site, but can't figure out what I am doing wrong. It's not that far off, but it seems to center on 0,0,0 in world space.
I read the Orbit Controls override the camera, so I messed around with controls.target.set but it said the mesh variable was undefined, despite being declared in global.
How can I just center the model in the canvas viewport and make the center of it the point of rotation?
<div class="container">
<canvas id="artifactCanvas"></canvas>
</div>
<script src="{{ asset('/js/three.min.js') }}"></script>
<script src="{{ asset('/js/OrbitControls.js') }}"></script>
<script src="{{ asset('/js/STLLoader.js') }}"></script>
<script>
var scene, renderer, camera, mesh;
var material = new THREE.MeshPhongMaterial( { color: 0xffaf00, specular: 0x111111, shininess: 200 } );
init();
animate();
function init() {
// scene
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xc5e5fc );
// renderer
renderer = new THREE.WebGLRenderer( { canvas: artifactCanvas, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(600, 400);
// lights
var light = new THREE.DirectionalLight( 0xffffff, 2 );
light.position.set( 1, 1, 1 );
scene.add( light );
// camera
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set( 100, 0, 0 );
// Geometry
var loader = new THREE.STLLoader();
loader.load("{{ asset('/stls/test.stl') }}", function ( geometry ) {
mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, 0, 0);
mesh.rotation.set( - Math.PI / 2, 0, 0 );
mesh.scale.set( 1, 1, 1 );
scene.add( mesh );
});
// controls
controls = new THREE.OrbitControls( camera, renderer.domElement );
// Cannot read property 'center' of undefined
//controls.target.set( mesh.center() );
}
function animate() {
renderer.render( scene, camera );
requestAnimationFrame( animate );
}
</script>
| |
doc_23527074
|
calling a host function("std::pow<int, int> ") from a __device__/__global__ function("_calc_psd") is not allowed
from my understanding, this should be using the cuda pow function instead, but it isn't.
A: The error is exactly as the compiler is reported. You can't used host functions in device code, and that include the whole host C++ std library. CUDA includes its own standard library, described in the programming guide, but you should use either pow or fpow (taken from the C standard library, no C++ or namespaces). nvcc will overload the function with the cuda correct device function and inline the resulting code. Something like the following will work:
#include <math.h>
__device__ float func(float x) {
return x * x * fpow(x, 0.123456f);
}
EDIT: The bit I missed the first time is the template specifier reported in the errors. Are you sure that you are passing either float or double arguments to pow? If you are passing integers, there is no overload function in the CUDA standard library, which is why it might be failing. If you need an integer pow function, you will have to roll your own (or do casting, but pow is a rather expensive function and I am certain some cascaded integer multiplication will be faster).
| |
doc_23527075
|
// fieldList="Code,Name";
var result = from Activity in query
select new
{
Code = Activity.Code,
Name = Activity.Name,
StatusCode = Activity.ClaimStatus.Name
};
A: DTO
public class CustomDto
{
public string Code { get; set; }
public string Name { get; set; }
public string StatusCode { get; set; }
}
Convert To Dto
var result = items.AsQueryable().Select(x => new CustomDto()
{
Code = x.Code,
Name = x.Name,
StatusCode = x.ClaimStatus
}).ToList();
| |
doc_23527076
|
What's the best practice for lazily loading those external JavaScripts?
Those routes can be accessed multiple times (e.g. user can go to /upload then /photos then /upload again)
A: In addition to what Alex has stated, if you will be lazy loading AngularJS artefacts such as controllers and directives, you would have to use the relevant provider to register them instead of the module API. Artefacts registered using the module API after the application has been bootstrapped, will not be available to the application. For example, you would define a lazy controller like this...
$controllerProvider.register('SomeLazyController', function($scope)
{
$scope.key = '...';
});
instead of this...
angular.module('app').controller('SomeLazyController', function($scope)
{
$scope.key = '...';
});
I have written a blog post detailing this as well as how to use the 'resolve' method that Alex speaks about, to implement lazy loading in AngularJS. http://ify.io/lazy-loading-in-angularjs/
A: The only way I know to handle cases like this is using the "resolve" method of a route. This method can be used to define a dependency to be loaded before the route's controller is instantiated. One of the different possible return types of this method is a promise. Thus you might use this to start loading your external JavaScript code asynchronously and return a promise that is resolved as soon as your external scripts are loaded.
The documentation for this can be found here: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider in the "when" section.
A: @alex3683's answer is probably the correct AngularJS way, but I don't grasp the concept, so instead I make use of jQuery's getScript(). So, in CoffeeScript:
yourModule.factory 'foo', ->
$.getScript 'https://script-to-load', ->
# whatever you want to do once the script is loaded
And just call it from your controller. Since AngularJS services are lazy and singleton, this will only load the script once.
| |
doc_23527077
|
Sample data:
marital <- sample(1:5, 64614, replace = T)
race <- sample(1:3, 64614, replace = T)
educ <- sample(1:20, 64614, replace = T)
test <- data.frame(educ, marital, race)
test$marital <- as.factor(test$marital)
test$race <- as.factor(test$race)
test$marital <- relevel(test$marital, ref = "3")
require(nnet)
require(aod)
require(lmtest)
testmod <- multinom(marital ~ race*educ, data = test)
testnull <- multinom(marital ~ 1, data = test) #null model for the global test
waldtest(testnull, testmod)
wald.test(b = coef(testmod), Sigma = vcov(testmod), Terms = 1:24) #testing all terms for the global test
As you can see, when I use the waldtest function from lmtest package I get the following error:
Error in solve.default(vc[ovar, ovar]) : 'a' is 0-diml
When I use the wald.test function from aod, I get the following error:
Error in L %*% b : non-conformable arguments
I assume these are related errors as they both seem to do with the variance matrix. I'm not sure why I'm getting these errors though as the data set has no missing values.
A: Just as heads up when using nnet package with multinom: You can also use the package broom to tidy things a bit by doing this:
tidy(multinom_model, conf.int= True, conf.level = 0.95, exponentiate = T)
This will return a tibble with the coefficients exponentiated, confidence intervals (similiar to confint used in lm), as well as the Z-scores, Standard errors and the respective p-value for the Wald Z test (essentially doing z = summary(multinom_model)$coefficients/summary(multinom_model)$standard.errors and the round((1 - pnorm(abs(z), 0, 1)) * 2,digits=5) already
| |
doc_23527078
|
I have a small handler which would read the existing file (contains passwords) and allow the user to enter.I't works but with some probability . i.e sometimes it would work sometimes it wont.
A snip-it which would work every time:
app.all('/acceptForm',function(req,res){
if (req.method === 'POST') {
let body = '';
var match = 0;
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
//get the uid to compare later on in the program
uid = parse(body).uid_text;
//read the UID file.
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(__dirname+'/uid.txt')
...
// write the other information to a file which would be later on re -opened again to read the things again
which have the file name of the 'uid'
firstname = parse(body).first_name;
lastname = parse(body).last_name;
mothername = parse(body).mother_name;
fathername = parse(body).father_name;
email = parse(body).email;
profession = parse(body).profession_text;
gender = parse(body).gender;
language = parse(body).lang_0;
married = parse(body).married;
birthday = parse(body).dateofbirth;
//write the UID and other things to the text file
console.log(language);
var fileContent = uid +'|' + firstname +'|'+ lastname +'|' + mothername +'|' + fathername +'|' + email+'|' + profession+'|' + gender+'|' + married+'|' +birthday + '|';
var filepath = __dirname+"/users/"+uid + ".txt";
fs.writeFile(filepath, fileContent, (err)
...
lineReader.on('line', function (line) {
if(line == uid) {
// if the uid is found...
res.cookie('name',uid, {signed: true}); //write the uid as a cookie back
res.sendFile(__dirname+'/CE/ENG/Kids.html');
} else{
//some failure message
}
});
});
}
}
The problem is as soon as the user sends this it changed to another file and the server has lost track with the client.To counteract that i added the same system with cookies.Now there is a security risk as well has many more risks.
handling a response from kids.html which is stored in another file....
(Has a very low probability that it works successfully).
app.all('/return',function(req,res){
if (req.method === 'POST') {
//read the UID file.
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(__dirname+'/uid.txt')
});
//Handling the information from the client.
lineReader.on('line', function (line) {
if(line == req.signedCookies['name']) {
//uid matches with the database
fs.readdir( __dirname+"/users/", (err, files) => {
files.forEach(file => {
if(file == req.signedCookies['name'] + ".txt"){
let questiondata = '';
req.on('data', chunk => {
questiondata += chunk.toString();
});
req.on('end', () => {
var cleaneddata = questiondata.split('%2C'); //%2C is a spliting term {array}
cleaneddata.splice(0,1);
//add the question data to another file
fs.appendFile( __dirname+"/users/" + req.signedCookies['name'] + ".txt",cleaneddata.toString() + "\r\n", function (err) { //writes inside the temp file for the questions
if (err) throw err;
fs.createReadStream( __dirname+"/users/" + req.signedCookies['name'] + ".txt").pipe(fs.createWriteStream( __dirname+'/users.txt', {flags: 'a'}));
fs.unlink( __dirname+"/users/"+ req.signedCookies['name'] + ".txt",function(err){
if(err) return console.log(err);
res.clearCookie("name");
});
});
});
}
});
})
}
A: As a suggestion:
var lineReader = require('linebyline');
app.post('/return' , (req, res) => {
var cookie = req.signedCookies['name'];
// check cookie
console.log(cookie);
// red the UID file:
rl = readline(__dirname + 'uid.txt');
// BTW: Why no database?!
rl.on('line', function(line, lineCount, byteCount) {
if (line === cookie) {
// ...
}
})
.on('error', function(e) {
// something went wrong
res.status(500).json({
error: err
})
});
// Here you are filling some txt files with data out of your form data..
// I highly suggest using a database instead of using your local directory
// structure and txt files.
})
| |
doc_23527079
|
I am having an issue with the UIAlertController crashing my app when it is called. It works absolutely fine on iOS 8 however doesn't work at all on iOS 7.
Here is the code I am using:
@IBAction func resetAllButton(sender : AnyObject) {
var alert = UIAlertController(title: "Start Over", message: "Are you sure you want to start over? This will erase your budget and all transactions.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "I'm sure!", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in
self.resetView()
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
A: UIAlertController is only available on iOS 8 or higher. You need to use a UIAlertView to present the alert on iOS 7.
| |
doc_23527080
|
odoo.define('ebs_portal_attendance.mn_tasks', function (require) {
"use strict";
$(document).ready(function () {
// Show create timesheet popup
$('#create_timesheet_button').on('click', function () {
var $modal = $('#create_timesheet_popup');
var task_id = $(this).data('task-id');
$modal.modal('show');
});
// Create timesheet
$('#create_timesheet_popup #create_timesheet_button').on('click', function () {
var $modal = $('#create_timesheet_popup');
var task_id = $modal.find('#task_id').val();
var name = $modal.find('#name').val();
var unit_amount = $modal.find('#unit_amount').val();
var date = $modal.find('#date').val();
ajax.jsonRpc("/my/tasks/create_timesheet", 'call', {
'values': {
'name': name,
'task_id': task_id,
'unit_amount': unit_amount,
'date': date,
}
}).then(function (result) {
if (result.success) {
$modal.modal('hide');
alert("Timesheet created successfully!");
} else {
alert("An error occurred while creating the timesheet.");
}
});
});
});
});
<template id="mn_tasks_list" inherit_id="project.portal_tasks_list">
<xpath expr="//t//t//t//tbody//t//tr//td[last()]" position="after">
<td>
<div class="o_download_pdf btn-toolbar flex-sm-nowrap">
<div>
<a role="button" class="btn btn-secondary flex-grow-1 mb-1 create_timesheet_button"
data-toggle="modal"
id='create_timesheet_button' data-target="#create_timesheet_popup" href="#">
<t>Create Timesheet</t>
</a>
</div>
</div>
</td>
</xpath>
</template>
</data>
<template id="create_timesheet_popup" name="Create Timesheet Popup">
<div id="create_timesheet_popup" class="modal fade">
<div class="modal-dialog modal-content"
style="border:solid 2px white; min-height:200px;max-width:800px;margin-top:10px">
<div class="modal-body" id="pop_html">
<a href="#" class="o_popup_btn_close o_not_editable o_default_snippet_text pull-right"
data-dismiss="modal" aria-hidden="true">X</a>
<div class="row">
<div class="col-md-12">
<form class="o_form_sheet">
<div class="o_form_sheet_name">
<h4>Create Timesheet</h4>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" required="required"/>
</div>
<div class="form-group">
<label for="task_id">Task:</label>
<select class="form-control" id="task_id" name="task_id" required="required">
<t t-foreach="tasks" t-as="task">
<option value="{{ task.id }}">{{ task.name }}</option>
</t>
</select>
</div>
<div class="form-group">
<label for="unit_amount">Hours:</label>
<input type="number" class="form-control" id="unit_amount" name="unit_amount"
required="required"/>
</div>
<div class="form-group">
<label for="date">Date:</label>
<input type="date" class="form-control" id="date" name="date" required="required"/>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" id="create_timesheet_button" data-task-id="{{ task.id }}">Create Timesheet</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
@http.route('/my/tasks/create_timesheet', type='json', auth='user')
def create_timesheet(self, values):
task_id = values.get('task_id')
name = values.get('name')
unit_amount = values.get('unit_amount')
date = values.get('date')
try:
# Create new timesheet record
new_timesheet = http.request.env['account.analytic.line'].sudo().create({
'name': name,
'task_id': task_id,
'unit_amount': unit_amount,
'date': date,
})
# Return success message
return {'success': True, 'message': 'Timesheet created successfully'}
except Exception as e:
# Return error message
return {'success': False, 'message': 'An error occurred while creating the timesheet: %s' % e}
with the manifest is as follows:
` # always loaded
'data': [
'security/security.xml',
'security/ir.model.access.csv',
'views/views.xml',
'views/templates.xml',
'views/inherited_templates.xml',
],
'assets': {
'web.assets_backend': [
'model_folder/static/src/js/portal_timesheets.js',
],
},`
My Problem is that button on the portal in the list of tasks where the button is located it's there but now it's not doing anything i tried checking the js via adding console.log("test") to see if anything would appear under the web browser's console but there's nothing... what i am doing wring here please do help me.
Thank you!!
I'm looking to have it work where when the user clicks on create timesheet, a popup would appear and it'll take the task's ID and task.analytical_account_id.id and other inputs to which it'll create at the end a record for that model and appears under his timesheets.
| |
doc_23527081
|
/* package */ final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
Here is an example from AOSP line 180:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/app/Application.java
A: As a comment, it has absolutely no effect on the compiler. It can be used, however, by humans to make it clear that a member (method or field) or class is package-private.
A: By default, members in Java use package-level access - they can be accessed by other classes in the same package, but not by classes in other packages.
Actually using this functionality is fairly rare, since you normally want all of your variables to be private (or protected), and your methods to either be private (for self-use), protected, or public.
There is no explicit "package" modifier, so there's no easy way to know at a glance if the modifier is missing because the author forgot to include the correct one, or because they intentionally wanted the member to have package-level access.
That's why, in the somewhat rare cases when you want to use package, it's good practice to put a /* package */ comment in front of the method declaration, to clearly state that you are intentionally using this access level, rather than accidentally forgetting to specify one.
The comment itself doesn't actually do anything as far as the compiler is concerned - it just makes the code easier to understand.
| |
doc_23527082
|
An example of the field (it's name is "neighborhood") would be:
{"T":0,"N":"jardim Atlantico","I":0}
But in some lines I could have:
{"T":0,"I":0,"N":"JD";"Sorocaba parque"}
So when I run
proc import
datafile='D:\nnl_muest_result_bs.csv'
dbms=dlm
out=muest_Re.I03_nnl_result_bs;
delimiter=';';
guessingrows=32767;
run;
It splits by the semicolon, which is ok for the rest of the fields but not in this one.
How can I tell SAS to split using semicolon but to ignore those inside curly braces {}??
Thanks
A: I haven't found anything useful with proc import but you can solve the problem with a more manual approach.
I created some test data:
a;b;n{c;d}e;g
aa;bb;mm{cc;dd;ee}ff;h
and here is the code where the commented part has to be modified according to your variables as is the length of record (and you maybe need to add a lrecl= and firstobs=2 in the infile statement)
data test;
infile "C:\Dati\EsempiSAS\graffe.txt" pad missover;
input @1 record $CHAR100.;
piece1=substr(record,1,indexc(record,"{")-1);
piece2=substr(record,indexc(record,"{")+1,(indexc(record,"}"))-(indexc(record,"{")+1));
piece3=substr(record,indexc(record,"}")+1);
/*
var1=scan(piece1,1,";");
var2=scan(piece1,2,";");
var3=scan(piece1,3,";");
var4=piece2;
var5=scan(piece3,1,";");
var6=scan(piece3,2,";");
*/
run;
| |
doc_23527083
|
For example I have a strange problem with ActiveDirectoryMembershipProvider that I think will be easily solved with some additional info on what the membership provider tries to do.
I'm using log4net(I can change it, if required)
Similar to java, where you can enable the Spring framework logging by adding log4j.category.org.springframework=ALL
to log4j.properties
A: For exception logging i far prefer the almost automated ELMAH over the manual do it yourself log4net. Give it a try! It can be easily installed via nuget
| |
doc_23527084
|
Declarations :
#define N 128
#define M N
int __attribute__(( aligned(32)))temp8[8];
__m256i vec;
int __attribute__(( aligned(32))) c_result[N][M];
These are my two ways for adding all int value in a vector:
First, non-SIMD version is:
_mm256_store_si256((__m256i *)&temp8[0] , vec);
c_result[i][j]= temp8[0]+temp8[1]+temp8[2]+temp8[3]+temp8[4]+temp8[5]+temp8[6]+temp8[7];
Second, AVX2 version:
c_result[i][j] =_mm256_hadd2_epi32(vec);
I implemented the hadd2 in this way:
// my horizontal addition of epi32
inline int _mm256_hadd2_epi32(__m256i a)
{
__m256i a_hi;
a_hi = _mm256_permute2x128_si256(a, a, 1); //maybe 1 should be 4
a = _mm256_hadd_epi32(a, a_hi);
a = _mm256_hadd_epi32(a, a);
a = _mm256_hadd_epi32(a, a);
return _mm256_extract_epi32(a,0);
}
I use gcc , Linux-mint , skylake microarchitecture.
I guessed it might be because of the following reasons:
There are 4 ALU for integers in skylake microarchitecture that will add them fastly in contrast to restricted vector execution units particularly for permutation that needs at least one cycle to reorder the elements followed by some haddinstructions. The question is, am I missing something or it's not necessary to use SIMD for adding all elements?
UPDATE: I just added the MUL program to the repository here you can access the whole codes of matrix multiplication. if I use the non-SIMD version elapsed time would be 201 ns and with SIMD version I takes 210 ns.
A: The intuition might be that this step...
temp8[0]+temp8[1]+temp8[2]+temp8[3]+temp8[4]+temp8[5]+temp8[6]+temp8[7]
is the expensive part that vectorization should accelerate, but it is probably wrong. Addition is a single muop, and you can execute 4 per cycle on a recent x64 machine as long as you work over registers (not memory). So, in theory, your processor can do this...
cycle 1.
temp8[0]+temp8[1]
temp8[2]+temp8[3]
temp8[4]+temp8[5]
temp8[6]+temp8[7]
cycle 2
(temp8[0]+temp8[1])+(temp8[2]+temp8[3])
(temp8[4]+temp8[5])+(temp8[6]+temp8[7])
and get the answer on cycle 3, with capacity to spare. (Our processors are superscalar and have an out-of-order pipeline so this will happen magically.)
How much faster can a vectorized approach be? You gave us the answer...
a = _mm256_hadd_epi32(a, a_hi);
a = _mm256_hadd_epi32(a, a);
a = _mm256_hadd_epi32(a, a);
We can recognize the 3 cycles... Of course, it looks cheaper, maybe... but what is probably underneath the _mm256_hadd_epi32 intrinsic is the PHADD instruction (~3 muops, 1 instruction every two cycles). The important point is that the processor cannot execute several of the _mm256_hadd_epi32 intrinsics simultaneously while it can do several of the scalar additions simultaneously. Thus, you see, which is faster becomes a technical matter.
Anyhow, to sum up my answer... You should not expect vectorization to help in this instance (at least not help a lot) because it is going against superscalar execution of cheap instructions (add).
Appendix. This code
_mm256_store_si256((__m256i *)&temp8[0] , vec);
c_result[i][j]= temp8[0]+temp8[1]+temp8[2]+temp8[3]+temp8[4]+temp8[5]+temp8[6]+temp8[7];
probably does not get compiled to what you think. Let us flush it out as a function
uint32_t hadd32(__m256i vector) {
uint32_t buffer[sizeof(__m256i)/sizeof(uint32_t)];
_mm256_store_si256((__m256i *)buffer , vector);
uint32_t answer = buffer[0]+buffer[1]+buffer[2]+buffer[3]+buffer[4]+buffer[5]+buffer[6]+buffer[7];
return answer;
}
Several compilers (clang, GCC 7), compile this down to
vpextrd edx, xmm0, 1
vmovd eax, xmm0
add eax, edx
vpextrd edx, xmm0, 2
add eax, edx
vpextrd edx, xmm0, 3
vextracti128 xmm0, ymm0, 0x1
add eax, edx
vmovd edx, xmm0
add eax, edx
vpextrd edx, xmm0, 1
add eax, edx
vpextrd edx, xmm0, 2
add eax, edx
vpextrd edx, xmm0, 3
add eax, edx
where we recognize the additions, but where the temporary buffer as been ignored entirely in favor of vpextrd calls. The lesson here is to always look at the generated assembly.
| |
doc_23527085
|
/Date(1450674000000)/
How do we make that properly formatted as a date so we can display it in our HTML Tables?
A: I'd suggest formating it before you serialise it to Json.
A: As Lazarus suggested you could format it to a string representation of the date before serializing. You might need to add a new string property though. (i'm assuming you don't need the time component of the date object)
formatting could be done as shown below.
string dateStr = dateObject.ToString("dd-MMM-yyyy"); // format depends on your need or preference
Hope this helps.
| |
doc_23527086
|
I am using Azure Cloud Functions with Queue Storage Binding for input and Blob Storage Binding for output, but I can't seen to find an API or a configuration option that would enable me to read more than 1 message.
Does anyone know about such an API?
A: The official documentation doesn't mention any support for processing Storage Queue messages in batches in a single execution of Azure Function. There is an open issue in WebJobs SDK. So, it's not supported.
If you are flexible which service to use for messaging middleware, you could switch to Event Hubs. Event Hub trigger supports (and encourages) processing messages in batches. It won't probably be 10.000 though: the batch size is limited to 256k of data.
To process Storage Queue messages in batches you'd have to get away from Queue Triggered Functions (e.g. run a function on a timer and connect to the table storage to process all the messages, or have a custom polling Web Job, or use Web Job SDK with a custom trigger).
A: I finally found a solution I am perfectly happy with.
Using buffers was not scalable because the runtime can easily exceed 5 minutes limit imposed by the Azure Functions runtime, plus the obvious memory consumption issue, plus I had to use a timer trigger so I would need to somehow make sure all relevant messages are in the queue at a certain time.
What I did now is to using a normal queue binding to acquire a message, and the Node Storage SDK, to implement some sort of "fake" streaming into an Append Blob. So every message is converted one by one into a CSV line, and appended to the respective blob.
Here is my code for that function:
const config = require('./config/config.js')
const storage = require('azure-storage')
const csvTransformer = require('./lib/csvTransform')
const async = require('async')
module.exports = function (context, myQueueItem) {
context.log(
'JavaScript queue trigger function processed work item',
myQueueItem
)
let blobService = storage.createBlobService(config.targetBlobConnection)
let messageDayString = csvTransformer.determineDayFromMessage(myQueueItem)
let blobName = messageDayString + '.csv'
let csvMessage
async.waterfall(
[
function (callback) {
blobService.createContainerIfNotExists(
config.targetBlobContainer,
{ publicAccessLevel: 'blob' },
err => {
callback(err)
}
)
},
function (callback) {
blobService.doesBlobExist(
config.targetBlobContainer,
blobName,
null,
(err, blobResult) => {
context.log('got blobResult: ', blobResult)
callback(err, blobResult)
}
)
},
function (blobResult, callback) {
if (blobResult && blobResult.exists) {
csvMessage = csvTransformer.transformMessageToCSV(myQueueItem, false)
blobService.appendFromText(
config.targetBlobContainer,
blobName,
csvMessage,
null,
(err, appendedBlobResult) => {
context.log('appended to existing blob: ', appendedBlobResult)
callback(err, appendedBlobResult)
}
)
} else {
csvMessage = csvTransformer.transformMessageToCSV(myQueueItem, true)
blobService.createAppendBlobFromText(
config.targetBlobContainer,
blobName,
csvMessage,
null,
(err, createdBlobResult) => {
context.log('created new blob: ', createdBlobResult)
callback(err, blobResult)
}
)
}
}
],
function (err, result) {
if (err) {
context.log.error('Error happened!')
context.log.error(err)
context.done(err)
} else {
context.log('appended CSV message to blob')
context.bindings.outputQueueItem = csvMessage
context.done()
}
}
)
}
| |
doc_23527087
|
class student():
def __init__(self, name, pref_name=None):
self.name = name
self.pref_name = pref_name if pref_name else name
bob = student('robert')
print("Bob name:", bob.name)
print('Bob preferred name:', bob.pref_name)
Can this be made any shorter and easier to read?
def __init__(self, name, pref_name=name)
unfortunately does not work.
| |
doc_23527088
|
For example:
<TextView
android:id="@+id/answer_correctness_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:visibility="visible" />
and
answerCorrectnessText.setText(R.string.correct_label);
answerCorrectnessText.setTextColor(R.color.correct_answer_color);
The space it occupies remains empty!
Thanks.
Ok, here's all the code, hope someone can find the problem:
The layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent">
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="horizontal"> <!-- android:layout_weight="0.15"> -->
<TextView android:id="@+id/question_text" android:layout_width="0dip"
android:layout_height="fill_parent" android:layout_weight="0.9"
android:text="empty"/>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="right" android:text="@string/score_label"/>
<TextView android:id="@+id/score_text" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="right"
android:layout_weight="0.1" android:paddingLeft="5dip"/>
</LinearLayout>
<RadioGroup android:id="@+id/answers_group" android:layout_width="fill_parent"
android:layout_height="0dip" android:orientation="vertical"
android:layout_weight="0.6" android:visibility="invisible">
<!-- May also be generated dynamically if the number of answers differs for each
question -->
<RadioButton android:id="@+id/answerA_button" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/answerB_button" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/answerC_button" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/answerD_button" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RadioButton android:id="@+id/answerE_button" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RadioGroup>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="@+id/answer_button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/answer_label"
android:visibility="invisible"/>
<TextView android:id="@+id/answer_correctness_text" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:visibility="invisible"
android:layout_weight="0.2"/>
<TextView android:id="@+id/correct_caption_text" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/correct_answer_label"
android:visibility="invisible"/>
<TextView android:id="@+id/correct_text" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:visibility="invisible"
android:layout_weight="0.2"/>
<Button android:id="@+id/next_button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/next_label"
android:visibility="invisible"/>
</LinearLayout>
<TextView android:id="@+id/remark_text" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The code:
package com.lightcone.webdatastreams;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import java.util.*;
import android.app.*;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.widget.*;
public class POSTexample extends Activity {
private static final String CHAPTERS_DATA_STATE_KEY="chaptersData";
private static final String QUESTION_STATE_KEY="question";
private static final String CHAPTER_STATE_KEY="chapter";
private static final String SCORE_STATE_KEY="score";
private static final int CORRECT_ANSWER_SCORE=10;
private static final int DEFAULT_CHAPTER=-1;
private static final int DEFAULT_SCORE=0;
private static final int NO_SUCH_CHAPTER_INDICATOR=-2;
// Set address for the questioner script on the server
public static final String host_url =
"http://csep10.phys.utk.edu/cgi-bin/quizforms/course1/questioner2.pl"; // Question script
public static final String TAG = "WEBSTREAM";
private ProgressDialog progDialog;
private int maxBarValue = 200;
private Map<String,Object> postData;
private TextView questionText;
private TextView scoreText;
private RadioGroup answersGroup;
private RadioButton[] answerRadioButtons;
private Button answerButton;
private TextView answerCorrectnessText;
private TextView correctAnswerCaptionText,correctAnswerText;
private Button nextButton;
private TextView remarkText;
private HashMap<Integer,Integer> chaptersData;
private QuestionData question;
private int chapter=DEFAULT_CHAPTER;
private int score=DEFAULT_SCORE;
private boolean chapterNotExists;
/*private class ChapterData implements Serializable
{
public int initialQuestionNum;
public int currentQuestionNum;
}*/
private class QuestionData implements Serializable
{
private static final long serialVersionUID=6800939332788597765L;
public int questionNum;
public String questionText;
public String[] answers;
public int correctAnswer;
public String remark;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState!=null)
{
chapter=savedInstanceState.getInt(CHAPTER_STATE_KEY,DEFAULT_CHAPTER);
score=savedInstanceState.getInt(SCORE_STATE_KEY,DEFAULT_SCORE);
question=(QuestionData)savedInstanceState.getSerializable(
QUESTION_STATE_KEY);
chaptersData=(HashMap<Integer,Integer>)savedInstanceState.
getSerializable(CHAPTERS_DATA_STATE_KEY);
}
if (chaptersData==null)
chaptersData=new HashMap<Integer,Integer>();
setContentView(R.layout.postexample);
questionText=(TextView)findViewById(R.id.question_text);
scoreText=(TextView)findViewById(R.id.score_text);
if (TextUtils.isEmpty(scoreText.getText()))
scoreText.setText(String.valueOf(score));
answersGroup=(RadioGroup)findViewById(R.id.answers_group);
answersGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override public void onCheckedChanged(RadioGroup group,int checkedId)
{ if (!answerButton.isEnabled()) answerButton.setEnabled(true); }
});
/*The assumption is that there's a constant number of possible answers
*for each question, but the radio buttons could also be generated
*dynamically for each question*/
answerRadioButtons=new RadioButton[5];
answerRadioButtons[0]=(RadioButton)findViewById(R.id.answerA_button);
answerRadioButtons[1]=(RadioButton)findViewById(R.id.answerB_button);
answerRadioButtons[2]=(RadioButton)findViewById(R.id.answerC_button);
answerRadioButtons[3]=(RadioButton)findViewById(R.id.answerD_button);
answerRadioButtons[4]=(RadioButton)findViewById(R.id.answerE_button);
answerButton=(Button)findViewById(R.id.answer_button);
answerButton.setOnClickListener(new View.OnClickListener()
{
@Override public void onClick(View v)
{
int checkedRadioButtonID=answersGroup.getCheckedRadioButtonId();
String resourceName=getResources().getResourceName(
checkedRadioButtonID);
char answerLetter=resourceName.charAt(resourceName.indexOf('_')-1);
int userAnswer=answerLetter-'A';
answerButton.setEnabled(false);
if (question.correctAnswer==userAnswer)
{
score+=CORRECT_ANSWER_SCORE;
scoreText.setText(String.valueOf(score));
answerCorrectnessText.setText(R.string.correct_label);
answerCorrectnessText.setTextColor(R.color.correct_answer_color);
remarkText.setText(question.remark);
remarkText.setVisibility(View.VISIBLE);
}
else
{
score+=CORRECT_ANSWER_SCORE;
scoreText.setText(String.valueOf(score));
answerCorrectnessText.setText(R.string.wrong_label);
answerCorrectnessText.setTextColor(R.color.wrong_answer_color);
}
setAnswerComponentsState(false);
}
});
answerCorrectnessText=(TextView)findViewById(R.id.answer_correctness_text);
correctAnswerCaptionText=(TextView)findViewById(R.id.correct_caption_text);
correctAnswerText=(TextView)findViewById(R.id.correct_text);
nextButton=(Button)findViewById(R.id.next_button);
nextButton.setOnClickListener(new View.OnClickListener()
{
@Override public void onClick(View v)
{
if (chaptersData.get(chapter)==question.questionNum+1)
questionText.setText(R.string.no_more_questions_text);
else new BackgroundLoad().execute(host_url);
}
});
remarkText=(TextView)findViewById(R.id.remark_text);
if (chapter==DEFAULT_CHAPTER)
{
Dialog chapterDialog=createChapterDialog();
chapterDialog.show();
}
}
@Override public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.options_menu,menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.change_chapter_item:
Dialog chapterDialog=createChapterDialog();
chapterDialog.show();
return true;
case R.id.reset_score_item:
resetData();
return true;
default: return super.onOptionsItemSelected(item);
}
}
private Dialog createChapterDialog()
{
AlertDialog.Builder dialogBuilder=new AlertDialog.Builder(this);
dialogBuilder.setTitle(null);
LayoutInflater inflater=getLayoutInflater();
/*ViewGroup container=(ViewGroup)chapterDialog.findViewById(android.
R.id.custom);
inflater.inflate(R.layout.change_chapter,container);*/
View dialogView=inflater.inflate(R.layout.change_chapter,null);
dialogBuilder.setView(dialogView);
final EditText chapterEdit=(EditText)dialogView.findViewById(
R.id.chapter_edit);
if (chapter!=DEFAULT_CHAPTER)
chapterEdit.setText(String.valueOf(chapter));
else chapterEdit.setText("1");
final AlertDialog chapterDialog=dialogBuilder.create();
Button okButton=(Button)dialogView.findViewById(R.id.chapter_ok_button);
/*dialogBuilder.setPositiveButton(android.R.string.ok,new DialogInterface.
OnClickListener()*/
okButton.setOnClickListener(new View.OnClickListener()
{
//@Override public void onClick(DialogInterface dialog,int which)
@Override public void onClick(View view)
{
chapterDialog.dismiss();
int newChapter=Integer.parseInt(chapterEdit.getText().toString());
if (chapter!=newChapter)
{
Log.i(TAG,"Here!!!");
chapter=newChapter;
chapterNotExists=false;
if (postData==null) postData=new HashMap<String,Object>();
postData.put("chapter",chapter);
new BackgroundLoad().execute(host_url);
}
}
});
/*//The button does not exist even though we used setPositiveButton!?
ViewGroup.LayoutParams layoutParams=chapterDialog.getButton(AlertDialog.
BUTTON_POSITIVE).getLayoutParams();
layoutParams.width=ViewGroup.LayoutParams.WRAP_CONTENT;*/
return chapterDialog;
}
private void resetData()
{
score=0;
scoreText.setText(String.valueOf(score));
chaptersData.clear();
if (question!=null) chaptersData.put(chapter,question.questionNum);
}
@Override protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (chapter!=DEFAULT_CHAPTER) outState.putInt(CHAPTER_STATE_KEY,chapter);
if (score!=DEFAULT_SCORE) outState.putInt(SCORE_STATE_KEY,score);
if (question!=null)
outState.putSerializable(QUESTION_STATE_KEY,question);
if (chaptersData!=null)
outState.putSerializable(CHAPTERS_DATA_STATE_KEY,chaptersData);
}
// Implement query by POST method and return the response as a string.
private QuestionData doPOST(String host_url, Map<String,Object> data){
QuestionData question=null;
//Compose the request body
StringBuilder requestBodyBuilder=new StringBuilder();
for (String parameterName:data.keySet())
{
requestBodyBuilder.append(parameterName);
requestBodyBuilder.append('=');
requestBodyBuilder.append(data.get(parameterName));
requestBodyBuilder.append('&');
}
requestBodyBuilder.deleteCharAt(requestBodyBuilder.length()-1);
String requestBody=requestBodyBuilder.toString();
//Connect and retrieve data
URL url=null;
HttpURLConnection httpConnection=null;
BufferedWriter requestStream=null;
BufferedReader responseStream=null;
try
{
//Send request
url=new URL(host_url);
URLConnection connection=url.openConnection();
if (!(connection instanceof HttpURLConnection))
throw new IOException("Invalid HTTP connection: " + host_url);
httpConnection=(HttpURLConnection)connection;
httpConnection.setDoOutput(true);
httpConnection.setFixedLengthStreamingMode(requestBody.length());
requestStream=new BufferedWriter(new OutputStreamWriter(httpConnection.
getOutputStream()));
requestStream.write(requestBody);
requestStream.close();
// Extract the response status and the headers
int responseStatus = httpConnection.getResponseCode();
Map<String,List<String>> headers=httpConnection.getHeaderFields();
Log.i(TAG, "\nPOST response and headers:" );
Log.i(TAG, "\nResponse="+headers.get(null));
Log.i(TAG, "Response code = "+responseStatus);
Iterator<String> headerNamesIterator=headers.keySet().iterator();
/*Skip the first header, which is actually not a header but the
*status line of the response*/
headerNamesIterator.next();
while (headerNamesIterator.hasNext())
{
String headerName=headerNamesIterator.next();
//for (String headerName:headers.keySet())
for (String headerValue:headers.get(headerName))
Log.i(TAG, "header="+headerName+" value="+headerValue);
}
//Get response body
if (responseStatus==HttpURLConnection.HTTP_OK)
{
responseStream=new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
question=buildQuestionData(responseStream);
}
}
catch (IOException ioException)
{
Log.e(TAG,"Error occurred while trying to retrieve data from the " +
"server!",ioException);
}
catch (ParseException parseException)
{
Log.e(TAG,"Error occurred while parsing the response received " +
"from the server!",parseException);
if (parseException.getErrorOffset()==NO_SUCH_CHAPTER_INDICATOR)
chapterNotExists=true;
}
finally
{
if (requestStream!=null)
{
//The closing may occur twice if the stream was closed previously
try { requestStream.close(); }
catch (IOException ioException) { }
}
if (responseStream!=null)
{
try { responseStream.close(); }
catch (IOException ioException) { }
}
if (httpConnection!=null) httpConnection.disconnect();
}
return question;
}
private QuestionData buildQuestionData(BufferedReader responseStream)
throws IOException,ParseException
{
//final String errorMessage="Invalid question data retrieved from server: ";
String line=retrieveLine(responseStream);
if (line.startsWith("<font"))
{
throw new ParseException("Chapter " + chapter + " does not exist! " +
"No question was received.",NO_SUCH_CHAPTER_INDICATOR);
}
QuestionData question=new QuestionData();
question.questionNum=extractIntParameter(line,"qnum",false);
line=retrieveLine(responseStream);
question.questionText=extractStringParameter(line,"question",false);
/*The assumption here is that there's a constant number of possible
*answers for each question, but it could also be dynamic*/
question.answers=new String[5];
int letterInt=(int)'A';
for (int counter=0;counter<question.answers.length;counter++)
{
line=retrieveLine(responseStream);
question.answers[counter]=extractStringParameter(line,"answer" +
(char)letterInt,false);
letterInt++;
}
//Chapter number
line=retrieveLine(responseStream);
int receivedChapter=extractIntParameter(line,"chapter",false);
if (chapter!=receivedChapter)
{
throw new ParseException("The chapter number of the question " +
"received from the server (" + receivedChapter +
" is not equal to the chapter number requested (" +
chapter + ")!",-1);
}
//Correct answer
line=retrieveLine(responseStream);
String correctAnswerStr=extractStringParameter(line,"coran",false);
if (correctAnswerStr.length()>1)
{
throw new ParseException("The correct answer must be one " +
"letter only!",-1);
}
char correctAnswer=correctAnswerStr.charAt(0);
char lastValidLetter=(char)((int)'A'+question.answers.length);
if ((correctAnswer<'A')||(correctAnswer>lastValidLetter))
{
throw new ParseException("The correct answer must be between A and " +
lastValidLetter + "! It's actually equal to " + correctAnswer,-1);
}
question.correctAnswer=correctAnswer-'A';
//Remark
line=retrieveLine(responseStream);
question.remark=extractStringParameter(line,"amp",false);
return question;
}
private String retrieveLine(BufferedReader responseStream) throws
IOException,ParseException
{
String line=responseStream.readLine();
if (line==null) throw new ParseException("Unexpected end of data!",-1);
else return line;
}
private String extractDataParameter(String data,String parameterName)
throws ParseException
{
int separator=data.indexOf('=');
if (separator==-1)
{
throw new ParseException("Invalid data! Parameter value could " +
"not be found: " + data,-1);
}
if (!data.substring(0,separator).equals(parameterName))
throw new ParseException("Missing parameter: " + parameterName,-1);
return data.substring(separator+1);
}
private int extractIntParameter(String data,String parameterName,boolean
isNegativeAllowed) throws ParseException
{
String parameterValueStr=extractDataParameter(data,parameterName);
int parameterValue=-1; boolean isValidNumber=true;
try { parameterValue=Integer.parseInt(parameterValueStr); }
catch (NumberFormatException numberException) { isValidNumber=false; }
if ((isValidNumber)&&(!isNegativeAllowed)&&(parameterValue<0))
isValidNumber=false;
if (!isValidNumber)
throw new ParseException("Parameter " + parameterName + " is invalid!" +
"Either it's non-numeric, or is a negative number and only " +
"positive numbers are allowed: " + parameterValueStr,-1);
return parameterValue;
}
private String extractStringParameter(String data,String parameterName,
boolean isEmptyAllowed) throws ParseException
{
String parameterValue=extractDataParameter(data,parameterName).trim();
if ((!isEmptyAllowed)&&(parameterValue.equals("")))
{
throw new ParseException("Parameter " + parameterName + " is an " +
"empty string!",-1);
}
return parameterValue;
}
private void handleResultQuestionData(QuestionData question)
{
if (question!=null)
{
this.question=question;
if (!chaptersData.containsKey(chapter))
chaptersData.put(chapter,question.questionNum);
questionText.setText(question.questionText);
for (int index=0;index<question.answers.length;index++)
answerRadioButtons[index].setText(question.answers[index]);
answersGroup.clearCheck();
answersGroup.setVisibility(View.VISIBLE);
answerButton.setVisibility(View.VISIBLE);
answerButton.setEnabled(false);
setAnswerComponentsState(true);
remarkText.setVisibility(View.INVISIBLE);
}
else
{
AlertDialog.Builder dialogBuilder=new AlertDialog.Builder(this);
if (chapterNotExists)
{
dialogBuilder.setMessage(R.string.chapter_not_exists_text);
dialogBuilder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
@Override public void onClick(DialogInterface dialog,int which)
{ dialog.dismiss(); }
});
}
else
{
dialogBuilder.setMessage(R.string.question_not_retrieved_text);
DialogInterface.OnClickListener listener=new DialogInterface.
OnClickListener()
{
@Override public void onClick(DialogInterface dialog,int which)
{
dialog.dismiss();
switch (which)
{
case Dialog.BUTTON_POSITIVE:
new BackgroundLoad().execute(host_url);
break;
case Dialog.BUTTON_NEGATIVE: finish(); break;
}
}
};
dialogBuilder.setPositiveButton(R.string.try_again_label,listener);
dialogBuilder.setNegativeButton(R.string.exit_label,listener);
} //end else (if chapterNotExists)
dialogBuilder.show();
} //end else (if question!=null)
}
private void setAnswerComponentsState(boolean beforeAnswer)
{
int visibility=(beforeAnswer?View.INVISIBLE:View.VISIBLE);
answerCorrectnessText.setVisibility(visibility);
correctAnswerCaptionText.setVisibility(visibility);
correctAnswerText.setVisibility(visibility);
nextButton.setVisibility(visibility);
}
// Method to create a progress bar dialog of either spinner or horizontal type
@Override
protected Dialog onCreateDialog(int id) {
switch(id) {
case 0: // Spinner
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDialog.setMessage("Loading...");
return progDialog;
case 1: // Horizontal
progDialog = new ProgressDialog(this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(maxBarValue);
progDialog.setMessage("Loading...:");
return progDialog;
default:
return null;
}
}
// Use AsyncTask to perform the web download on a background thread. The three
// argument types inside the < > are a type for the input parameters (Strings in this case),
// a type for any published progress during the background task (Void in this case, because
// we aren't going to publish progress since the task should be very short), and a type
// for the object returned from the background task (in this case it is type String).
private class BackgroundLoad extends AsyncTask <String, Void, QuestionData>{
// Executes the task on a background thread
@Override
protected QuestionData doInBackground(String... params) {
// The notation String... params means that the input parameters are an array of
// strings. In new BackgroundLoad().execute(host_url) above we are
// passing just one argument, so params[0] will correspond to host_url.
return doPOST(params[0], postData);
}
// Executes before the thread run by doInBackground
protected void onPreExecute () {
// Call method to create a progress dialog defined by onCreateDialog()
showDialog(0);
}
// Executes after the thread run by doInBackground has returned. The variable s
// passed is the string value returned by doInBackground.
@Override
protected void onPostExecute(QuestionData question){
// Stop the progress dialog
dismissDialog(0);
// Process the response
handleResultQuestionData(question);
}
}
}
A: Try setting text color using
answerCorrectnessText.setTextColor(getResources().getColor(R.color.correct_answer_color));
A: Have you tried to call answerCorrectnessText.invalidate() after setText and setTextColor ?
A: Try android:text="" in your textview. It should work
| |
doc_23527089
|
I want the same structure as it is now.Because this data needs to be converted to JSON.
This is what i get now.
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 9,
"user": "Student",
"id": "45"
},
{
"count_of_invites": 4,
"user": "Student",
"id": "45"
}
]
}
As you can see the id 45 are repeated.As i want the result as,
Expected output
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 13,
"user": "Student",
"id": "45"
}
]
}
As you can see the duplicate entry should be removed as well as the count_of_invites of duplicate entry should be added.
A: <?php
$data = [
[
'id' => 2,
'name' => 'Paul',
'count' => 4
],
[
'id' => 3,
'name' => 'Peter',
'count' => 5
],
[
'id' => 3,
'name' => 'Peter',
'count' => 7
]
];
foreach($data as $array)
$counts[$array['id']][] = $array['count'];
$counts = array_map('array_sum', $counts);
foreach($data as $k => $array)
$data[$k]['count'] = $counts[$array['id']];
$data = array_unique($data, SORT_REGULAR);
print json_encode($data, JSON_PRETTY_PRINT);
Output:
[
{
"id": 2,
"name": "Paul",
"count": 4
},
{
"id": 3,
"name": "Peter",
"count": 12
}
]
A: You can achieve it this way:
$ids = array();
$output = array();
foreach ($input as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]]=$count($output);
$output[]=$value;
} else {
$output[$ids[$value["id"]]]["count_of_invites"] = $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
A: The count method was declared as variable and i've added with addition assignment operator.
Thank You for helping.
$ids = array();
$output = array();
foreach ($response as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]] = count($output);
$output[] = $value;
}
else {
$output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
| |
doc_23527090
|
Tab tab2 = new Tab();
How do I add a scene to a Tab?
I want to make it so when tab1 is selected the scene is showing and when switched to tab2, it is not there.
I tried doing tab1.setContent, it has to be a node.
I tried doing dialog.setOwner(tab1), it has to be a window.
TabPane tabPane = new TabPane();
Tab tab1 = new Tab("FIRST TAB");
Tab tab2 = new Tab("SECOND TAB");
tab1.setContent(new VBox(new Text("Scene Below:")));
tab2.setContent(new VBox(new Button("dsadsadassda")));
tabPane.getTabs().addAll(tab1, tab2);
final Stage dialog = new Stage();
dialog.initModality(Modality.NONE);
dialog.initOwner(tab1); // I can't, it has to be a window
dialog.initStyle(StageStyle.UTILITY);
dialog.show();
stage.setScene(new Scene(tabPane, 1000, 680));
stage.setMaximized(true);
stage.show();
A: well the design depends on what you want to do , in your case you should specify a CustomTab that extends the JavaFx Tab and as default it would hold a ScrollablePane or whatever pane you want , which will be bound to have the same width and height as the Tab, so when you do setContent() you should be able to pass every JavaFx's object, because you will add that object to the inner tab pane.
| |
doc_23527091
|
What I've tried yet is:
<input size="10" readonly="readonly" ondblclick="setEditable(this)"/>
and in JavaScript:
function setEditable(i){
i.readonly = false;
}
But this does not worked. So how can I make a textbox editable, which is readonly, when user double clicks on it?
A: Update:
To make it readonly again:
var el = document.getElementById('txt');
el.onblur = function(){
this.setAttribute('readonly');
};
You can do this:
<input size="10" readonly="readonly" id="txt" />
JS:
var el = document.getElementById('txt');
el.ondblclick = function(){
this.removeAttribute('readonly');
};
A: as above pure javascript example by sarfraz try to make your javascript unobtrusive
much better practice
Also as a lot of people do if you have jquery on page now you can use that to do same
In jquery
$('#txt').removeAttr("readonly");
A: To make text field editable
document.getElementById("TextFieldId").readOnly=true;
To make text field Uneditable
document.getElementById("TextFieldId").readOnly=false;
| |
doc_23527092
|
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>test</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<filters>
<filter>src/main/resources/filters/test.filter</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources/export</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
and this is my resources
src/main/resources/export/app.properties
Hello ${test_prop}
src/main/resources/filters/test.filter
test_prop = World
When I run mvn resources:resources or mvn clean package the result in target folder is the original app.properties (no filtering). Does anyone know why it is not filtering?
A: From Spring documentation: If you use the spring-boot-starter-parent, you can then refer to your Maven 'project properties' with @..@ placeholders, as shown in the following example:
app.encoding=@project.build.sourceEncoding@
app.java.version=@java.version@
https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html
| |
doc_23527093
|
Template:
<div id="content" data-ng-include data-src="content()"></div>
Controller ("thisview" is a string variable derived from url):
$scope.content = function () {
var thiscontent = 'includes/content/' + thisview + '.html';
return thiscontent;
};
included [thisview].html file (truncated):
[...]
</ul>
</div><!--closes div-->
<div id="anotherdiv">
<p>
[...]
When I load the page, the </div> (as above) is getting moved to the end, effectively nesting #newdiv inside #content. Is this an $sce thing (or other 'code-cleaning/fixing') that I can turn off?
I'd like to inject raw html as I see fit into my template.
Thanks for any pointers.
| |
doc_23527094
|
The code I'm currently using for this is as following:
var email = vm.Reservation.Customer.Email;
var customer = db.Customers.Where(x => x.Email == email).First();
if(customer != null)
{
db.Entry(customer).State = !db.Customers.Any(c => c.Email == customer.Email) ? EntityState.Added : EntityState.Modified;
} else {
db.Customers.Add(vm.Reservation.Customer);
}
vm.Save();
However, it results in just adding a new customer with the modified username and password in the database with the same email.
How can I achieve this?
Thanks in advance.
A: You can do it like this:
var customer = db.Customers.FirstOrDefault(x => x.Email == email);
if(customer != null)
{
//Set the values of 'customer' object using 'vm.Reservation.Customer'
customer.Email = vm.Reservation.Customer.Email;
customer.Field1 = vm.Reservation.Customer.Field1;
customer.Field2 = vm.Reservation.Customer.Field2;
db.Customers.Update(vm.Reservation.Customer);
}
else {
db.Customers.Add(vm.Reservation.Customer);
}
db.SaveChanges();
Note: This code works for EntityFramework with PostgreSql database.
So please mention your database you are using, which will be easier for you to find answers.
A: try this
var email = vm.Reservation.Customer.Email;
var customer = db.Customers.Where(x => x.Email == email).FirstOrDefault();
if(customer != null)
{
customer.FirstName=vm.Reservation.Customer.FirstName;
customer.LastName=vm.Reservation.Customer.LastName;
db.Entry(customer).State = EntityState.Modified;
}
else
{
db.Customers.Add(vm.Reservation.Customer);
}
db.SaveChanges();
| |
doc_23527095
|
BEGIN TRY
BEGIN TRANSACTION
Declare @RecsToKeep Table
(
Id int
)
SELECT Id
FROM RealTable
Where CONVERT (DATE, CreatedDate) > '2017-08-16'
Declare @KeepTheseRecs Table
(
Id int
)
Insert into @KeepTheseRecs
Select *
From RealTable Where Id IN (Select Id From @RecsToKeep)
Truncate Table RealTable
Insert into RealTable
Select *
From @KeepTheseRecs
COMMIT
END TRY
BEGIN CATCH
ROLLBACK
END CATCH
The real table and table variable have the same column structure. Is this the correct way to do this?
A: First, you haven't changed anything in the table based off your query. You are simply moving the records from A to B and back to A.
A simpler method would be to skip the move all together.
delete from RealTable
where someColumn = 'someValue' --or what ever condition you want
If you are really going to stage the records, you're going to at least want a WHERE clause on that Insert Into statement. I really don't see why you need to do this though.
| |
doc_23527096
|
*
*Location
*type
*pick datetime
*drop datetime
so please let me know how to get available cars which is not booked now between a date time if car booked then it should not be in list. list should be come only available cars by search.
Cars Table
----------------------------------------------
id | name | type | location | pincode
----------------------------------------------
1 A plain delhi 110093
2 B plain deldi 110093
3 C plain deldi 110093
4 D plain deldi 110093
5 E plain deldi 110093
Booking Table
id | car_id | user_id | pick_date | drop_date
-----------------------------------------------------------------------------
1 1 1 2016-05-10 13:00:00 2016-05-12 16:00:00
2 1 1 2016-05-12 18:00:00 2016-05-12 23:00:00
A: In the your_startdate and your_enbdate you should insert your date range
Select cars.*
from cars
Left join booking on cars.id=booking.id and pick_date between your_startdate and your_enddate
Where booking.id is null
A: Use this query...
Find the cars id's from booking that are booked on given dates and then find all the cars from cars table where id not equal to booked cars..
SELECT * FROM cars WHERE id NOT IN (SELECT car_id FROM booking
WHERE pick_date >= '2015-06-03'
AND drop_date <= '2015-06-05'
);
A: According your search variables, first select car_id from Booking table between pick datetime and drop datetime.
Now you have a list of car_id which is booked between that date and time.
Use a loop and make a select query from cars table where id != car_id and location and type will be as your search variables.
A: use between query and know which car are booked and also know the specific time car available are not .
given_time_here_search_time = "2016-05-11 15:00:00"; //user input
query should be something like this
SELECT * FROM cars
WHERE id NOT IN (SELECT car_id
FROM booking
WHERE given_time_here_search_time
between pick_date
AND drop_date ) and location='delhi' and type='plain';
| |
doc_23527097
|
However, this look doesn't match my tool and I would like it to be inside of a Bootstrap dropdown instead.
I would like for this:
//Font select
const fontsSelect = document.getElementsByClassName('fonts-select')[0],
styledTextArea = document.getElementsByClassName('styledTextarea')[0];
fontsSelect.addEventListener('change', function() {
styledTextArea.style.fontFamily = fontsSelect.value;
});
<select class="form-control form-control-sm fonts-select">
<option selected disabled>Select font...</option>
<option value="Arial">Arial</option>
<option value="Cambria">Cambria</option>
<option value="Courier">Courier</option>
<option value="Calibri">Calibri</option>
<option value="Futura">Futura</option>
<option value="Franklin Gothic">Franklin Gothic</option>
<option value="Garamond">Garamond</option>
<option value="Helvetica">Helvetica</option>
<option value="Rockwell">Rockwell</option>
<option value="Times New Roman">Times New Roman</option>
<option value="Verdana">Verdana</option>
</select>
<textarea class="styledTextarea" rows="15" placeholder="Write something.."></textarea>
To look something like this:
<ul>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="dropdowntools" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Fonts</a>
<div class="dropdown-menu fonts-select" aria-labelledby="dropdowntools">
<a selected disabled>Select font...</a>
<a value="Arial">Arial</a>
<a value="Cambria">Cambria</a>
<a value="Courier">Courier</a>
<a value="Calibri">Calibri</a>
<a value="Futura">Futura</a>
<a value="Franklin Gothic">Franklin Gothic</a>
<a value="Garamond">Garamond</a>
<a value="Helvetica">Helvetica</a>
<a value="Rockwell">Rockwell</a>
<a value="Times New Roman">Times New Roman</a>
<a value="Verdana">Verdana</a>
</div>
</li>
</ul>
I've been trying to experiment with it with no luck. I couldn't figure out how can I target this styledTextArea.style.fontFamily = fontsSelect.value; to instead be a "link value"
Can this be done without a submit button?
I would reallllly appreciate any help. Thank you!
EDIT: Here's a working fiddle using select option
And here's the output I'd like to achieve
A: @ixcode, you are not having any submit button so that the program will change the font style.
| |
doc_23527098
|
somehow the line
pf.NFile = !( oldPatch.FindAll(s => s.Equals(f)).Count() == 0);
is always returning false. is there something wrong with my logic of cross checking?
List<string> newPatch = DirectorySearch(_newFolder);
List<string> oldPatch = DirectorySearch(_oldFolder);
foreach (string f in newPatch)
{
string filename = Path.GetFileName(f);
string Dir = (Path.GetDirectoryName(f).Replace(_newFolder, "") + @"\");
PatchFile pf = new PatchFile();
pf.Dir = Dir;
pf.FName = filename;
pf.NFile = !( oldPatch.FindAll(s => s.Equals(f)).Count() == 0);
nPatch.Files.Add(pf);
}
foreach (string f in oldPatch)
{
string filename = Path.GetFileName(f);
string Dir = (Path.GetDirectoryName(f).Replace(_oldFolder, "") + @"\");
PatchFile pf = new PatchFile();
pf.Dir = Dir;
pf.FName = filename;
if (!nPatch.Files.Exists(item => item.Dir == pf.Dir &&
item.FName == pf.FName))
{
nPatch.removeFiles.Add(pf);
}
}
A: I don't have the classes you are using (like DirectorySearch and PatchFile), so i can't compile your code, but IMO the line _oldPatch.FindAll(... doesn't return anything because you are comparing the full path (c:\oldpatch\filea.txt is not c:\newpatch\filea.txt) and not the file name only. IMO your algorithm could be simplified, something like this pseudocode (using List.Contains instead of List.FindAll):
var _newFolder = "d:\\temp\\xml\\b";
var _oldFolder = "d:\\temp\\xml\\a";
List<FileInfo> missing = new List<FileInfo>();
List<FileInfo> nPatch = new List<FileInfo>();
List<FileInfo> newPatch = new DirectoryInfo(_newFolder).GetFiles().ToList();
List<FileInfo> oldPatch = new DirectoryInfo(_oldFolder).GetFiles().ToList();
// take all files in new patch
foreach (var f in newPatch)
{
nPatch.Add(f);
}
// search for hits in old patch
foreach (var f in oldPatch)
{
if (!nPatch.Select (p => p.Name.ToLower()).Contains(f.Name.ToLower()))
{
missing.Add(f);
}
}
// new files are in missing
One possible solution with less code would be to select the file names, put them into a list an use the predefined List.Except or if needed List.Intersect methods. This way a solution to which file is in A but not in B could be solved fast like this:
var locationA = "d:\\temp\\xml\\a";
var locationB = "d:\\temp\\xml\\b";
// takes file names from A and B and put them into lists
var filesInA = new DirectoryInfo(locationA).GetFiles().Select (n => n.Name).ToList();
var filesInB = new DirectoryInfo(locationB).GetFiles().Select (n => n.Name).ToList();
// Except retrieves all files that are in A but not in B
foreach (var file in filesInA.Except(filesInB).ToList())
{
Console.WriteLine(file);
}
I have 1.xml, 2.xml, 3.xml in A and 1.xml, 3.xml in B. The output is 2.xml - missing in B.
| |
doc_23527099
|
part of input xml:
<h5 class="Paragraf">
§ 113 a 114
<br/>
zrusen
</h5>
what would I like to have on output:
§ 113 a 114 -> A_Header_5
zrusen -> A_Header_5-Podnadpis
part of xslt condition which I created but it’s not doing what I want:
<xsl:when test="(self::h5) and not (child::br)">A_Header_5</xsl:when>
<xsl:when test="(self::h5) and (child::br)">
<xsl:if test="text()[1]">A_Header_5</xsl:if>
<xsl:if test="text()[2]">A_Header_5-Podnadpis</xsl:if>
</xsl:when>
unfortunately output with this xslt conditions looks this:
§ 113 a 114 -> A_Header_5A_Header_5-Podnadpis
zrusen -> A_Header_5A_Header_5-Podnadpis
Thank you
A: This is not exactly the same logic as in your post, but without a full _ Minimal, Complete, and Verifiable example_ it is hard to spot the root cause of your dissatisfaction with your code.
The following code iterates over all text() nodes and distinguishes on the basis of the existence of a following <BR /> element.
XSLT 1.0:
<xsl:template match="h5">
<xsl:for-each select="text()">
<xsl:if test="."><xsl:value-of disable-output-escaping = "yes" select="concat(normalize-space(.),' -> ')" /></xsl:if>
<xsl:if test="following-sibling::br">A_Header_5</xsl:if>
<xsl:if test="not(following-sibling::br)">A_Header_5-Podnadpis</xsl:if>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
Output:
§ 113 a 114 -> A_Header_5
zrusen -> A_Header_5-Podnadpis
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.