I feel like a more complete answer is needed to describe how this works more thoroughly.
Firstly, if you need advanced formatting, check the manual on how to use HTML in string resources.
Then you can use <br/>
, etc. However, this requires setting the text using code.
If it's just plain text, there are many ways to escape a newline character (LF) in static string resources.
The cleanest way is to enclose the string in double quotes.
This will make it so whitespace is interpreted exactly as it appears, not collapsed.
Then you can simply use newline normally in this method (don't use indentation).
<string name="str1">"Line 1.
Line 2.
Line 3."</string>
Note that some characters require special escaping in this mode (such as \"
).
The escape sequences below also work in quoted mode.
The most elegant way to escape the newline in XML is with its code point (10 or 0xA in hex) by using its XML/HTML entity 

or
. This is the XML way to escape any character.
However, this seems to work only in quoted mode.
Another method is to simply use \n
, though it negatively affects legibility, in my opinion (since it's not a special escape sequence in XML, Android Studio doesn't highlight it).
<string name="str1">"Line 1.
Line 2. Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>
Do not include a newline or any whitespace after any of these escape sequences, since that will be interpreted as extra space.
You mention the user switching between Activities pretty quickly. Could it be that you're calling unbindService
before the service connection has been established? This may have the effect of failing to unbind, then leaking the binding.
Not entirely sure how you could handle this... Perhaps when onServiceConnected
is called you could call unbindService
if onDestroy
has already been called. Not sure if that'll work though.
If you haven't already, you could add an onUnbind method to your service. That way you can see exactly when your classes unbind from it, and it might help with debugging.
@Override
public boolean onUnbind(Intent intent) {
Log.d(this.getClass().getName(), "UNBIND");
return true;
}
You can need to pass in the string 'int64'
:
>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]}) # some test dataframe
>>> df['a'].astype('int64')
0 1
1 2
Name: a, dtype: int64
There are some alternative ways to specify 64-bit integers:
>>> df['a'].astype('i8') # integer with 8 bytes (64 bit)
0 1
1 2
Name: a, dtype: int64
>>> import numpy as np
>>> df['a'].astype(np.int64) # native numpy 64 bit integer
0 1
1 2
Name: a, dtype: int64
Or use np.int64
directly on your column (but it returns a numpy.array
):
>>> np.int64(df['a'])
array([1, 2], dtype=int64)
You can also do:
(from u in table
orderby u.Status descending
select u).Take(1);
I had the same error code when I used @Transaction
on a wrong method/actionlevel.
methodWithANumberOfDatabaseActions() {
methodA( ...)
methodA( ...)
}
@Transactional
void methodA( ...) {
... ERROR message
}
I had to place the @Transactional
just above the method methodWithANumberOfDatabaseActions()
, of course.
That solved the error message in my case.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
A couple of plain old foreach
loops provides a clean solution:
foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
result.AppendLine(level1Element.Attribute("name").Value);
foreach (XElement level2Element in level1Element.Elements("level2"))
{
result.AppendLine(" " + level2Element.Attribute("name").Value);
}
}
As of April 2017, this is the current URL used for sharing:
I think this example will help you in understanding this more simply.
Path differences in Windows
Windows absolute path C:\Windows\calc.exe
Windows non absolute path (relative path) calc.exe
In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.
Path differences in Linux
Linux absolute path /home/users/c/computerhope/public_html/cgi-bin
Linux non absolute path (relative path) /public_html/cgi-bin
In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.
It is a best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.
Package Explorer / View Menu / Package Presentation... / Hierarchical
The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.
Use pyplot.suptitle
or Figure.suptitle
:
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
ax=fig.add_subplot(2,2,i)
ax.imshow(data)
fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()
with git 1.7, there's a really easy way using git rebase
:
stage your files:
git add $files
create a new commit and re-use commit message of your "broken" commit
git commit -c master~4
prepend fixup!
in the subject line (or squash!
if you want to edit commit (message)):
fixup! Factored out some common XPath Operations
use git rebase -i --autosquash
to fixup your commit
I've simplified clone45 steps:
Open the ports as he mentioned
sudo su
sudo yum install vsftpd
echo -n "Public IP of your instance: " && read publicip
echo -e "anonymous_enable=NO\npasv_enable=YES\npasv_min_port=1024\npasv_max_port=1048\npasv_address=$publicip\nchroot_local_user=YES" >> /etc/vsftpd/vsftpd.conf
sudo /etc/init.d/vsftpd restart
Actually I don't see any nulls:
given:
static void Main()
{
string[] testArray = new string[]
{
"aa",
"ab",
"ac",
"ad",
"ab",
"af"
};
Array.Sort(testArray, StringComparer.InvariantCulture);
Array.ForEach(testArray, x => Console.WriteLine(x));
}
I obtained:
Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like
template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64
I solved the problem by creating a symbolic link to the library. I.e.
The actual library resides in
/usr/local/mysql/lib
And then I created a symbolic link in
/usr/lib
Using the command:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
so that I have the following mapping:
ls -l libmysqlclient.18.dylib
lrwxr-xr-x 1 root wheel 44 16 Jul 14:01 libmysqlclient.18.dylib -> /usr/local/mysql/lib/libmysqlclient.18.dylib
That was it. After that everything worked fine.
EDIT:
Notice, that since MacOS El Capitan the System Integrity Protection (SIP, also known as "rootless") will prevent you from creating links in /usr/lib/
.
You could disable SIP by following these instructions, but you can create a link in /usr/local/lib/
instead:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
pChart is another great PHP graphing library.
One thing I didn't realize at first when reading the accepted answer was that making an inner class static is basically the same thing as moving it to its own separate class.
Thus, when getting the error
xxx is not an enclosing class
You can solve it in either of the following ways:
static
keyword to the inner class, orThe simplest way is like this:
import os
retvalue = os.popen("ps -p 2993 -o time --no-headers").readlines()
print retvalue
This will be returned as a list
You could also try this to make your query... shown here with INSERT
<?php
$week=array('one'=>'monday','two'=>'tuesday','three'=>'wednesday','four'=>'thursday','five'=>'friday','six'=>'saturday','seven'=>'sunday');
$keys = array_keys($week);
$string = "INSERT INTO my_table ('";
$string .= implode("','", $keys);
$string .= "') VALUES ('";
$string .= implode("','", $week);
$string .= "');";
echo $string;
?>
Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different
Write your style in any tag using style={{prop:"value"}}
import React, { Component } from "react";
import { Redirect } from "react-router";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<div>
<div
style={{
color: "red",
fontSize: 40,
background: "green"
}}// this is inline style in reactjs
>
</div>
</div>
</div>
);
}
}
export default InlineStyle;
Is very easy, I use this code:
Controller:
$langs = Language::all()->toArray();
return view('NAATIMockTest.Admin.Language.index', compact('langs'));
View:
<script type="text/javascript">
var langs = <?php echo json_decode($langs); ?>;
console.log(langs);
</script>
hope it has been helpful, regards!
Caution! The scripts have a limit: it handles up to 500 values in a single drop-down list.
More Info
This solution is not perfect, but it gives some benefits:
First of all, here's working example, so you can test it before going further.
Installation:
Data > Validation
Prepare Data
Data looks like a single table with all possible variants inside it. It must be located on a separate sheet, so it can be used by the script. Look at this example:
Here we have four levels, each value repeats. Note that 2 columns on the right of data are reserved, so don't type/paste there any data.
First simple Data Validation (DV)
Prepare a list of unique values. In our example, it is a list of Planets. Find free space on sheet with data, and paste formula: =unique(A:A)
On your mainsheet select first column, where DV will start. Go to Data > Validation and select range with a unique list.
Script
Paste this code into script editor:
function onEdit(event) _x000D_
{_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data1'; // name of sheet with data_x000D_
var NumOfLevels = 4; // number of levels of data validation_x000D_
var lcol = 2; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,2]; // offsets for levels_x000D_
// ^ means offset column #4 on one position right._x000D_
_x000D_
// =====================================================================================_x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
// Change Settings:_x000D_
//--------------------------------------------------------------------------------------_x000D_
var TargetSheet = 'Main'; // name of sheet with data validation_x000D_
var LogSheet = 'Data2'; // name of sheet with data_x000D_
var NumOfLevels = 7; // number of levels of data validation_x000D_
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc._x000D_
var lrow = 2; // number of row where validation starts_x000D_
var offsets = [1,1,1,1,1,1,1]; // offsets for levels_x000D_
// ===================================================================================== _x000D_
SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets);_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function SmartDataValidation(event, TargetSheet, LogSheet, NumOfLevels, lcol, lrow, offsets) _x000D_
{_x000D_
//--------------------------------------------------------------------------------------_x000D_
// The event handler, adds data validation for the input parameters_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
var FormulaSplitter = ';'; // depends on regional setting, ';' or ',' works for US_x000D_
//--------------------------------------------------------------------------------------_x000D_
_x000D_
// =================================== key variables =================================_x000D_
//_x000D_
// ss sheet we change (TargetSheet)_x000D_
// br range to change_x000D_
// scol number of column to edit_x000D_
// srow number of row to edit _x000D_
// CurrentLevel level of drop-down, which we change_x000D_
// HeadLevel main level_x000D_
// r current cell, which was changed by user_x000D_
// X number of levels could be checked on the right_x000D_
//_x000D_
// ls Data sheet (LogSheet)_x000D_
//_x000D_
// ======================================================================================_x000D_
_x000D_
// Checks_x000D_
var ts = event.source.getActiveSheet();_x000D_
var sname = ts.getName(); _x000D_
if (sname !== TargetSheet) { return -1; } // not main sheet_x000D_
// Test if range fits_x000D_
var br = event.range;_x000D_
var scol = br.getColumn(); // the column number in which the change is made_x000D_
var srow = br.getRow() // line number in which the change is made_x000D_
var ColNum = br.getWidth();_x000D_
_x000D_
if ((scol + ColNum - 1) < lcol) { return -2; } // columns... _x000D_
if (srow < lrow) { return -3; } // rows_x000D_
// Test range is in levels_x000D_
var columnsLevels = getColumnsOffset_(offsets, lcol); // Columns for all levels _x000D_
var CurrentLevel = getCurrentLevel_(ColNum, br, scol, columnsLevels);_x000D_
if(CurrentLevel === 1) { return -4; } // out of data validations_x000D_
if(CurrentLevel > NumOfLevels) { return -5; } // last level _x000D_
_x000D_
_x000D_
/*_x000D_
ts - sheet with validation, sname = name of sheet_x000D_
_x000D_
NumOfLevels = 4 _x000D_
offsets = [1,1,1,2] - last offset is 2 because need to skip 1 column_x000D_
columnsLevels = [4,5,6,8] - Columns of validation_x000D_
_x000D_
Columns 7 is skipped_x000D_
|_x000D_
1 2 3 4 5 6 7 8 9 _x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
1 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
2 | | | | v | V | ? | x | ? | | lrow = 2 - number of row where validation starts_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
3 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
4 | | | | | | | x | | |_x000D_
|----+----+----+----+----+----+----+----+----+_x000D_
| | | | |_x000D_
| | | | Currentlevel = 3 - the number of level to change_x000D_
| | | |_x000D_
| | | br - cell, user changes: scol - column, srow - row,_x000D_
| | ColNum = 1 - width _x000D_
|__|________ _.....____|_x000D_
| v_x000D_
| Drop-down lists _x000D_
|_x000D_
| lcol = 4 - number of column where validation starts_x000D_
*/_x000D_
// Constants_x000D_
var ReplaceCommas = getDecimalMarkIsCommaLocals(); // // ReplaceCommas = true if locale uses commas to separate decimals_x000D_
var ls = SpreadsheetApp.getActive().getSheetByName(LogSheet); // Data sheet _x000D_
var RowNum = br.getHeight();_x000D_
/* Adjust the range 'br' _x000D_
??? !_x000D_
xxx x_x000D_
xxx x _x000D_
xxx => x_x000D_
xxx x_x000D_
xxx x_x000D_
*/ _x000D_
br = ts.getRange(br.getRow(), columnsLevels[CurrentLevel - 2], RowNum); _x000D_
// Levels_x000D_
var HeadLevel = CurrentLevel - 1; // main level_x000D_
var X = NumOfLevels - CurrentLevel + 1; // number of levels left _x000D_
// determine columns on the sheet "Data"_x000D_
var KudaCol = NumOfLevels + 2;_x000D_
var KudaNado = ls.getRange(1, KudaCol); // 1 place for a formula_x000D_
var lastRow = ls.getLastRow();_x000D_
var ChtoNado = ls.getRange(1, KudaCol, lastRow, KudaCol); // the range with list, returned by a formula_x000D_
_x000D_
// ============================================================================= > loop >_x000D_
var CurrLevelBase = CurrentLevel; // remember the first current level_x000D_
_x000D_
_x000D_
_x000D_
for (var j = 1; j <= RowNum; j++) // [01] loop rows start_x000D_
{ _x000D_
// refresh first val _x000D_
var currentRow = br.getCell(j, 1).getRow(); _x000D_
loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrLevelBase, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} // [01] loop rows end_x000D_
_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getColumnsOffset_(offsets, lefColumn)_x000D_
{_x000D_
// Columns for all levels_x000D_
var columnsLevels = [];_x000D_
var totalOffset = 0; _x000D_
for (var i = 0, l = offsets.length; i < l; i++)_x000D_
{ _x000D_
totalOffset += offsets[i];_x000D_
columnsLevels.push(totalOffset + lefColumn - 1);_x000D_
} _x000D_
_x000D_
return columnsLevels;_x000D_
_x000D_
}_x000D_
_x000D_
function test_getCurrentLevel()_x000D_
{_x000D_
var br = SpreadsheetApp.getActive().getActiveSheet().getRange('A5:C5');_x000D_
var scol = 1;_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/_x000D_
Logger.log(getCurrentLevel_(1, br, scol, [1,2,3])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxx| |xxxxx|_x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(2, br, scol, [1,3,5])); // 2_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxx| |xxxxxxxxxxx| _x000D_
levels 1 2 3_x000D_
level 2_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,5,6])); // 2_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxx| |xxxxx| _x000D_
levels 1 2 3_x000D_
level 3_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,8])); // 3_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels 1 2 3_x000D_
level 4 (error)_x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [1,2,3]));_x000D_
_x000D_
_x000D_
/*_x000D_
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |_x000D_
range |xxxxxxxxxxxxxxxxx| _x000D_
dv range |xxxxxxxxxxxxxxxxx|_x000D_
levels _x000D_
level 1 (error) _x000D_
_x000D_
*/ _x000D_
Logger.log(getCurrentLevel_(3, br, scol, [5,6,7])); // 1 _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getCurrentLevel_(ColNum, br, scol, columnsLevels)_x000D_
{_x000D_
var colPlus = 2; // const_x000D_
if (ColNum === 1) { return columnsLevels.indexOf(scol) + colPlus; }_x000D_
var CurrentLevel = -1;_x000D_
var level = 0;_x000D_
var column = 0;_x000D_
for (var i = 0; i < ColNum; i++ )_x000D_
{_x000D_
column = br.offset(0, i).getColumn();_x000D_
level = columnsLevels.indexOf(column) + colPlus;_x000D_
if (level > CurrentLevel) { CurrentLevel = level; }_x000D_
}_x000D_
return CurrentLevel;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
function loopColumns_(HeadLevel, X, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
for (var k = 1; k <= X; k++)_x000D_
{ _x000D_
HeadLevel = HeadLevel + k - 1; _x000D_
CurrentLevel = CurrLevelBase + k - 1;_x000D_
var r = ts.getRange(currentRow, columnsLevels[CurrentLevel - 2]);_x000D_
var SearchText = r.getValue(); // searched text _x000D_
X = loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts);_x000D_
} _x000D_
}_x000D_
_x000D_
_x000D_
function loopColumn_(X, SearchText, HeadLevel, HeadLevel, currentRow, NumOfLevels, CurrentLevel, lastRow, FormulaSplitter, CurrLevelBase, columnsLevels, br, KudaNado, ChtoNado, ReplaceCommas, ts)_x000D_
{_x000D_
_x000D_
_x000D_
// if nothing is chosen!_x000D_
if (SearchText === '') // condition value =''_x000D_
{_x000D_
// kill extra data validation if there were _x000D_
// columns on the right_x000D_
if (CurrentLevel <= NumOfLevels) _x000D_
{_x000D_
for (var f = 0; f < X; f++) _x000D_
{_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel + f - 1]); _x000D_
// clean & get rid of validation_x000D_
cell.clear({contentsOnly: true}); _x000D_
cell.clear({validationsOnly: true});_x000D_
// exit columns loop _x000D_
}_x000D_
}_x000D_
return 0; // end loop this row _x000D_
}_x000D_
_x000D_
_x000D_
// formula for values_x000D_
var formula = getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts); _x000D_
KudaNado.setFormula(formula);_x000D_
_x000D_
_x000D_
// get response_x000D_
var Response = getResponse_(ChtoNado, lastRow, ReplaceCommas);_x000D_
var Variants = Response.length;_x000D_
_x000D_
_x000D_
// build data validation rule_x000D_
if (Variants === 0.0) // empty is found_x000D_
{_x000D_
return;_x000D_
} _x000D_
if(Variants >= 1.0) // if some variants were found_x000D_
{_x000D_
_x000D_
var cell = ts.getRange(currentRow, columnsLevels[CurrentLevel - 1]);_x000D_
var rule = SpreadsheetApp_x000D_
.newDataValidation()_x000D_
.requireValueInList(Response, true)_x000D_
.setAllowInvalid(false)_x000D_
.build();_x000D_
// set validation rule_x000D_
cell.setDataValidation(rule);_x000D_
} _x000D_
if (Variants === 1.0) // // set the only value_x000D_
{ _x000D_
cell.setValue(Response[0]);_x000D_
SearchText = null;_x000D_
Response = null;_x000D_
return X; // continue doing DV_x000D_
} // the only value_x000D_
_x000D_
return 0; // end DV in this row_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getDVListFormula_(CurrentLevel, currentRow, columnsLevels, lastRow, ReplaceCommas, FormulaSplitter, ts)_x000D_
{_x000D_
_x000D_
var checkVals = [];_x000D_
var Offs = CurrentLevel - 2;_x000D_
var values = [];_x000D_
// get values and display values for a formula_x000D_
for (var s = 0; s <= Offs; s++)_x000D_
{_x000D_
var checkR = ts.getRange(currentRow, columnsLevels[s]);_x000D_
values.push(checkR.getValue());_x000D_
} _x000D_
_x000D_
var LookCol = colName(CurrentLevel-1); // gets column name "A,B,C..."_x000D_
var formula = '=unique(filter(' + LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84_x000D_
_x000D_
var mathOpPlusVal = ''; _x000D_
var value = '';_x000D_
_x000D_
// loop levels for multiple conditions _x000D_
for (var i = 0; i < CurrentLevel - 1; i++) { _x000D_
formula += FormulaSplitter; // =unique(filter(A2:A84;_x000D_
LookCol = colName(i);_x000D_
_x000D_
value = values[i];_x000D_
_x000D_
mathOpPlusVal = getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas); // =unique(filter(A2:A84;B2:B84="Text"_x000D_
_x000D_
if ( Array.isArray(mathOpPlusVal) )_x000D_
{_x000D_
formula += mathOpPlusVal[0];_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;ROUND(B2:B84_x000D_
formula += mathOpPlusVal[1];_x000D_
}_x000D_
else_x000D_
{_x000D_
formula += LookCol + '2:' + LookCol + lastRow; // =unique(filter(A2:A84;B2:B84_x000D_
formula += mathOpPlusVal;_x000D_
}_x000D_
_x000D_
_x000D_
} _x000D_
_x000D_
formula += "))"; //=unique(filter(A2:A84;B2:B84="Text"))_x000D_
_x000D_
return formula;_x000D_
}_x000D_
_x000D_
_x000D_
function getValueAndMathOpForFunction_(value, FormulaSplitter, ReplaceCommas)_x000D_
{_x000D_
var result = '';_x000D_
var splinter = ''; _x000D_
_x000D_
var type = typeof value;_x000D_
_x000D_
_x000D_
// strings_x000D_
if (type === 'string') return '="' + value + '"';_x000D_
// date_x000D_
if(value instanceof Date)_x000D_
{_x000D_
return ['ROUND(', FormulaSplitter +'5)=ROUND(DATE(' + value.getFullYear() + FormulaSplitter + (value.getMonth() + 1) + FormulaSplitter + value.getDate() + ')' + '+' _x000D_
+ 'TIME(' + value.getHours() + FormulaSplitter + value.getMinutes() + FormulaSplitter + value.getSeconds() + ')' + FormulaSplitter + '5)']; _x000D_
} _x000D_
// numbers_x000D_
if (type === 'number')_x000D_
{_x000D_
if (ReplaceCommas)_x000D_
{_x000D_
return '+0=' + value.toString().replace('.', ','); _x000D_
}_x000D_
else_x000D_
{_x000D_
return '+0=' + value;_x000D_
}_x000D_
}_x000D_
// booleans_x000D_
if (type === 'boolean')_x000D_
{_x000D_
return '=' + value;_x000D_
} _x000D_
// other_x000D_
return '=' + value;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
function getResponse_(allRange, l, ReplaceCommas)_x000D_
{_x000D_
var data = allRange.getValues();_x000D_
var data_ = allRange.getDisplayValues();_x000D_
_x000D_
var response = [];_x000D_
var val = '';_x000D_
for (var i = 0; i < l; i++)_x000D_
{_x000D_
val = data[i][0];_x000D_
if (val !== '') _x000D_
{_x000D_
var type = typeof val;_x000D_
if (type === 'boolean' || val instanceof Date) val = String(data_[i][0]);_x000D_
if (type === 'number' && ReplaceCommas) val = val.toString().replace('.', ',')_x000D_
response.push(val); _x000D_
}_x000D_
}_x000D_
_x000D_
return response; _x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function colName(n) {_x000D_
var ordA = 'a'.charCodeAt(0);_x000D_
var ordZ = 'z'.charCodeAt(0);_x000D_
_x000D_
var len = ordZ - ordA + 1;_x000D_
_x000D_
var s = "";_x000D_
while(n >= 0) {_x000D_
s = String.fromCharCode(n % len + ordA) + s;_x000D_
n = Math.floor(n / len) - 1;_x000D_
}_x000D_
return s; _x000D_
}_x000D_
_x000D_
_x000D_
function getDecimalMarkIsCommaLocals() {_x000D_
_x000D_
_x000D_
// list of Locals Decimal mark = comma_x000D_
var LANGUAGE_BY_LOCALE = {_x000D_
af_NA: "Afrikaans (Namibia)",_x000D_
af_ZA: "Afrikaans (South Africa)",_x000D_
af: "Afrikaans",_x000D_
sq_AL: "Albanian (Albania)",_x000D_
sq: "Albanian",_x000D_
ar_DZ: "Arabic (Algeria)",_x000D_
ar_BH: "Arabic (Bahrain)",_x000D_
ar_EG: "Arabic (Egypt)",_x000D_
ar_IQ: "Arabic (Iraq)",_x000D_
ar_JO: "Arabic (Jordan)",_x000D_
ar_KW: "Arabic (Kuwait)",_x000D_
ar_LB: "Arabic (Lebanon)",_x000D_
ar_LY: "Arabic (Libya)",_x000D_
ar_MA: "Arabic (Morocco)",_x000D_
ar_OM: "Arabic (Oman)",_x000D_
ar_QA: "Arabic (Qatar)",_x000D_
ar_SA: "Arabic (Saudi Arabia)",_x000D_
ar_SD: "Arabic (Sudan)",_x000D_
ar_SY: "Arabic (Syria)",_x000D_
ar_TN: "Arabic (Tunisia)",_x000D_
ar_AE: "Arabic (United Arab Emirates)",_x000D_
ar_YE: "Arabic (Yemen)",_x000D_
ar: "Arabic",_x000D_
hy_AM: "Armenian (Armenia)",_x000D_
hy: "Armenian",_x000D_
eu_ES: "Basque (Spain)",_x000D_
eu: "Basque",_x000D_
be_BY: "Belarusian (Belarus)",_x000D_
be: "Belarusian",_x000D_
bg_BG: "Bulgarian (Bulgaria)",_x000D_
bg: "Bulgarian",_x000D_
ca_ES: "Catalan (Spain)",_x000D_
ca: "Catalan",_x000D_
tzm_Latn: "Central Morocco Tamazight (Latin)",_x000D_
tzm_Latn_MA: "Central Morocco Tamazight (Latin, Morocco)",_x000D_
tzm: "Central Morocco Tamazight",_x000D_
da_DK: "Danish (Denmark)",_x000D_
da: "Danish",_x000D_
nl_BE: "Dutch (Belgium)",_x000D_
nl_NL: "Dutch (Netherlands)",_x000D_
nl: "Dutch",_x000D_
et_EE: "Estonian (Estonia)",_x000D_
et: "Estonian",_x000D_
fi_FI: "Finnish (Finland)",_x000D_
fi: "Finnish",_x000D_
fr_BE: "French (Belgium)",_x000D_
fr_BJ: "French (Benin)",_x000D_
fr_BF: "French (Burkina Faso)",_x000D_
fr_BI: "French (Burundi)",_x000D_
fr_CM: "French (Cameroon)",_x000D_
fr_CA: "French (Canada)",_x000D_
fr_CF: "French (Central African Republic)",_x000D_
fr_TD: "French (Chad)",_x000D_
fr_KM: "French (Comoros)",_x000D_
fr_CG: "French (Congo - Brazzaville)",_x000D_
fr_CD: "French (Congo - Kinshasa)",_x000D_
fr_CI: "French (Côte d’Ivoire)",_x000D_
fr_DJ: "French (Djibouti)",_x000D_
fr_GQ: "French (Equatorial Guinea)",_x000D_
fr_FR: "French (France)",_x000D_
fr_GA: "French (Gabon)",_x000D_
fr_GP: "French (Guadeloupe)",_x000D_
fr_GN: "French (Guinea)",_x000D_
fr_LU: "French (Luxembourg)",_x000D_
fr_MG: "French (Madagascar)",_x000D_
fr_ML: "French (Mali)",_x000D_
fr_MQ: "French (Martinique)",_x000D_
fr_MC: "French (Monaco)",_x000D_
fr_NE: "French (Niger)",_x000D_
fr_RW: "French (Rwanda)",_x000D_
fr_RE: "French (Réunion)",_x000D_
fr_BL: "French (Saint Barthélemy)",_x000D_
fr_MF: "French (Saint Martin)",_x000D_
fr_SN: "French (Senegal)",_x000D_
fr_CH: "French (Switzerland)",_x000D_
fr_TG: "French (Togo)",_x000D_
fr: "French",_x000D_
gl_ES: "Galician (Spain)",_x000D_
gl: "Galician",_x000D_
ka_GE: "Georgian (Georgia)",_x000D_
ka: "Georgian",_x000D_
de_AT: "German (Austria)",_x000D_
de_BE: "German (Belgium)",_x000D_
de_DE: "German (Germany)",_x000D_
de_LI: "German (Liechtenstein)",_x000D_
de_LU: "German (Luxembourg)",_x000D_
de_CH: "German (Switzerland)",_x000D_
de: "German",_x000D_
el_CY: "Greek (Cyprus)",_x000D_
el_GR: "Greek (Greece)",_x000D_
el: "Greek",_x000D_
hu_HU: "Hungarian (Hungary)",_x000D_
hu: "Hungarian",_x000D_
is_IS: "Icelandic (Iceland)",_x000D_
is: "Icelandic",_x000D_
id_ID: "Indonesian (Indonesia)",_x000D_
id: "Indonesian",_x000D_
it_IT: "Italian (Italy)",_x000D_
it_CH: "Italian (Switzerland)",_x000D_
it: "Italian",_x000D_
kab_DZ: "Kabyle (Algeria)",_x000D_
kab: "Kabyle",_x000D_
kl_GL: "Kalaallisut (Greenland)",_x000D_
kl: "Kalaallisut",_x000D_
lv_LV: "Latvian (Latvia)",_x000D_
lv: "Latvian",_x000D_
lt_LT: "Lithuanian (Lithuania)",_x000D_
lt: "Lithuanian",_x000D_
mk_MK: "Macedonian (Macedonia)",_x000D_
mk: "Macedonian",_x000D_
naq_NA: "Nama (Namibia)",_x000D_
naq: "Nama",_x000D_
pl_PL: "Polish (Poland)",_x000D_
pl: "Polish",_x000D_
pt_BR: "Portuguese (Brazil)",_x000D_
pt_GW: "Portuguese (Guinea-Bissau)",_x000D_
pt_MZ: "Portuguese (Mozambique)",_x000D_
pt_PT: "Portuguese (Portugal)",_x000D_
pt: "Portuguese",_x000D_
ro_MD: "Romanian (Moldova)",_x000D_
ro_RO: "Romanian (Romania)",_x000D_
ro: "Romanian",_x000D_
ru_MD: "Russian (Moldova)",_x000D_
ru_RU: "Russian (Russia)",_x000D_
ru_UA: "Russian (Ukraine)",_x000D_
ru: "Russian",_x000D_
seh_MZ: "Sena (Mozambique)",_x000D_
seh: "Sena",_x000D_
sk_SK: "Slovak (Slovakia)",_x000D_
sk: "Slovak",_x000D_
sl_SI: "Slovenian (Slovenia)",_x000D_
sl: "Slovenian",_x000D_
es_AR: "Spanish (Argentina)",_x000D_
es_BO: "Spanish (Bolivia)",_x000D_
es_CL: "Spanish (Chile)",_x000D_
es_CO: "Spanish (Colombia)",_x000D_
es_CR: "Spanish (Costa Rica)",_x000D_
es_DO: "Spanish (Dominican Republic)",_x000D_
es_EC: "Spanish (Ecuador)",_x000D_
es_SV: "Spanish (El Salvador)",_x000D_
es_GQ: "Spanish (Equatorial Guinea)",_x000D_
es_GT: "Spanish (Guatemala)",_x000D_
es_HN: "Spanish (Honduras)",_x000D_
es_419: "Spanish (Latin America)",_x000D_
es_MX: "Spanish (Mexico)",_x000D_
es_NI: "Spanish (Nicaragua)",_x000D_
es_PA: "Spanish (Panama)",_x000D_
es_PY: "Spanish (Paraguay)",_x000D_
es_PE: "Spanish (Peru)",_x000D_
es_PR: "Spanish (Puerto Rico)",_x000D_
es_ES: "Spanish (Spain)",_x000D_
es_US: "Spanish (United States)",_x000D_
es_UY: "Spanish (Uruguay)",_x000D_
es_VE: "Spanish (Venezuela)",_x000D_
es: "Spanish",_x000D_
sv_FI: "Swedish (Finland)",_x000D_
sv_SE: "Swedish (Sweden)",_x000D_
sv: "Swedish",_x000D_
tr_TR: "Turkish (Turkey)",_x000D_
tr: "Turkish",_x000D_
uk_UA: "Ukrainian (Ukraine)",_x000D_
uk: "Ukrainian",_x000D_
vi_VN: "Vietnamese (Vietnam)",_x000D_
vi: "Vietnamese"_x000D_
}_x000D_
_x000D_
_x000D_
var SS = SpreadsheetApp.getActiveSpreadsheet();_x000D_
var LocalS = SS.getSpreadsheetLocale();_x000D_
_x000D_
_x000D_
if (LANGUAGE_BY_LOCALE[LocalS] == undefined) {_x000D_
return false;_x000D_
_x000D_
}_x000D_
//Logger.log(true);_x000D_
return true;_x000D_
}_x000D_
_x000D_
/*_x000D_
function ReplaceDotsToCommas(dataIn) {_x000D_
var dataOut = dataIn.map(function(num) {_x000D_
if (isNaN(num)) {_x000D_
return num;_x000D_
} _x000D_
num = num.toString();_x000D_
return num.replace(".", ",");_x000D_
});_x000D_
return dataOut;_x000D_
}_x000D_
*/
_x000D_
Here's set of variables that are to be changed, you'll find them in script:
var TargetSheet = 'Main'; // name of sheet with data validation
var LogSheet = 'Data2'; // name of sheet with data
var NumOfLevels = 7; // number of levels of data validation
var lcol = 9; // number of column where validation starts; A = 1, B = 2, etc.
var lrow = 2; // number of row where validation starts
var offsets = [1,1,1,1,1,1,1]; // offsets for levels
I suggest everyone, who knows scripts well, send your edits to this code. I guess, there's simpler way to find validation list and make script run faster.
Everything in the java.lang
package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util
package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
For object iteration we usually use a for..in
loop. This structure will loop through all enumerable properties, including ones who are inherited via prototypal inheritance. For example:
let obj = {_x000D_
prop1: '1',_x000D_
prop2: '2'_x000D_
}_x000D_
_x000D_
for(let el in obj) {_x000D_
console.log(el);_x000D_
console.log(obj[el]);_x000D_
}
_x000D_
However, for..in
will loop over all enumerable elements and this will not able us to split the iteration in chunks. To achieve this we can use the built in Object.keys()
function to retrieve all the keys of an object in an array. We then can split up the iteration into multiple for loops and access the properties using the keys array. For example:
let obj = {_x000D_
prop1: '1',_x000D_
prop2: '2',_x000D_
prop3: '3',_x000D_
prop4: '4',_x000D_
};_x000D_
_x000D_
const keys = Object.keys(obj);_x000D_
console.log(keys);_x000D_
_x000D_
_x000D_
for (let i = 0; i < 2; i++) {_x000D_
console.log(obj[keys[i]]);_x000D_
}_x000D_
_x000D_
_x000D_
for (let i = 2; i < 4; i++) {_x000D_
console.log(obj[keys[i]]);_x000D_
}
_x000D_
objective-c is the primary language used.
i believe there is a mono touch framework that can be used with c#
Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code
As another respondent notes, the file type can be spoofed (e.g., .exe renamed .pdf), which checking for the MIME type will not prevent (i.e., the .exe will show a MIME of "application/pdf" if renamed as .pdf). I believe a check of the true file type can only be done server side; an easy way to check it using System.IO.BinaryReader is described here:
http://forums.asp.net/post/2680667.aspx
and VB version here:
http://forums.asp.net/post/2681036.aspx
Note that you'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get them by implementing this solution and debugging the code.
This is an old question, but comes out high in my Google search for 'perl merge hashes' - and yet it does not mention the very helpful CPAN module Hash::Merge
Suppose you are running a test python file named request.py
In request.py, you write
import request
so this also most likely a circular import.
Solution:
Just change your test file to another name such as aaa.py
, other than request.py
.
Do not use names that are already used by other libs.
Another simple way is to use the pivot
function to format the data as you need first.
df.plot()
does the rest
df = pd.DataFrame([
['red', 0, 0],
['red', 1, 1],
['red', 2, 2],
['red', 3, 3],
['red', 4, 4],
['red', 5, 5],
['red', 6, 6],
['red', 7, 7],
['red', 8, 8],
['red', 9, 9],
['blue', 0, 0],
['blue', 1, 1],
['blue', 2, 4],
['blue', 3, 9],
['blue', 4, 16],
['blue', 5, 25],
['blue', 6, 36],
['blue', 7, 49],
['blue', 8, 64],
['blue', 9, 81],
], columns=['color', 'x', 'y'])
df = df.pivot(index='x', columns='color', values='y')
df.plot()
pivot effectively turns the data into:
function x() {}
is equivalent (or very similar) to
var x = function() {}
unless I'm mistaken.
So there is nothing funny going on.
You can try with regular expression
string s;
Regex r = new Regex ("a|b|c");
bool containsAny = r.IsMatch (s);
It looks like you are trying to parse each line. You've been shown by another answer how to use getline
in a loop to seperate each line. The other tool you are going to want is istringstream
, to seperate each token.
std::string line;
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string token;
while (iss >> token)
{
// do something with token
}
}
As already mentioned in the Poi's JavaDocs (https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#setCellType%28int%29) don't use:
cell.setCellType(Cell.CELL_TYPE_STRING);
but use:
DataFormatter df = new DataFormatter();
String value = df.formatCellValue(cell);
More examples on http://massapi.com/class/da/DataFormatter.html
static void Main(string[] args)
{
// For the sake of this example, we're just printing the arguments to the console.
for (int i = 0; i < args.Length; i++) {
Console.WriteLine("args[{0}] == {1}", i, args[i]);
}
}
The arguments will then be stored in the args
string array:
$ AppB.exe firstArg secondArg thirdArg
args[0] == firstArg
args[1] == secondArg
args[2] == thirdArg
Another option is to bind 'View.TrackActivityInSolutionExplorer' to a keyboard short-cut, which is the same as 'Tools-->Options-->Projects and Solutions-->Track Active Item in Solution Explorer'
If you activate the short-cut twice the file is selected in the solution explorer, and the tracking is disabled again.
Visual Studio 2013+
There is now a feature built in to the VS2013 solution explorer called Sync with Active Document. The icon is two arrows in the solution explorer, and has the hotkey Ctrl + [, S to show the current document in the solution explorer. Does not enable the automatic setting mentioned above, and only happens once.
The accepted answer has a couple of shortcomings:
Considering the above, your options could even have different values, but toggle the same class:
<select class="div-toggle" data-target=".my-info-1">
<option value="orange" data-show=".citrus">Orange</option>
<option value="lemon" data-show=".citrus">Lemon</option>
<option value="apple" data-show=".pome">Apple</option>
<option value="pear" data-show=".pome">Pear</option>
</select>
<div class="my-info-1">
<div class="citrus hide">Citrus is...</div>
<div class="pome hide">A pome is...</div>
</div>
jQuery:
$(document).on('change', '.div-toggle', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.div-toggle').trigger('change');
});
CSS:
.hide {
display: none;
}
Here's a JSFiddle to see it in action.
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
Unicode string literals (string literals prefixed by u
) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.
If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'
. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n
to your string literal. So when you print the 'hello\nworld'
string, the words will be printed on separate lines. That's very handy!
On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:
'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'
In such situations you can just prefix the string literal with the r
character like this: r'hello\nworld'
and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.
Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.
From the lexical definition of a string literal:
string ::= "'" stringitem* "'"
stringitem ::= stringchar | escapeseq
stringchar ::= <any source character except "\" or newline or the quote>
escapeseq ::= "\" <any source character>
It is clear that string literals (raw or not) containing a bare quote character: 'hello'world'
or ending with a backslash: 'hello world\'
are not valid.
You can get Browser type here:
<script>
var browser_type = Object.keys($.browser)[0];
alert(browser_type);
</script>
If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods
Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.
@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.
Alternatively, You can also check that a method is callable on an object or not?.
@current_user.respond_to?:your_method_name
If you don't want parent class methods then just subtract the parent class methods from it.
@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.
Adding to the above answers:
This can be easily achieved via storyboard.
Just go to the \eclipse-java-helios-SR2-win32\eclipse\configuration.settings directory and change or remove org.eclipse.ui.ide.prefs file.
F12 (only on Linux and Windows)
OR
Ctrl ? I
(? ? I if you're on Mac)
This can be done using Visual Studio
too (at least in version 2013 onwards).
In VS 2013 it is also possible to filter the list of rows the inserts statement are based on, this is something not possible in SSMS as for as I know.
Perform the following steps:
This will create the (conditional) insert statements for the selected table to the active window or file.
The "Filter" and "Script" buttons Visual Studio 2013:
The solutions is to use:
delete require.cache[require.resolve(<path of your script>)]
Find here some basic explanations for those who, like me, are a bit new in this:
Suppose you have a dummy example.js
file in the root of your directory:
exports.message = "hi";
exports.say = function () {
console.log(message);
}
Then you require()
like this:
$ node
> require('./example.js')
{ message: 'hi', say: [Function] }
If you then add a line like this to example.js
:
exports.message = "hi";
exports.say = function () {
console.log(message);
}
exports.farewell = "bye!"; // this line is added later on
And continue in the console, the module is not updated:
> require('./example.js')
{ message: 'hi', say: [Function] }
That's when you can use delete require.cache[require.resolve()]
indicated in luff's answer:
> delete require.cache[require.resolve('./example.js')]
true
> require('./example.js')
{ message: 'hi', say: [Function], farewell: 'bye!' }
So the cache is cleaned and the require()
captures the content of the file again, loading all the current values.
This is what I have after doing purge of all the python versions and reinstalling only 3.6.
root@esp32:/# python
Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
root@esp32:/# python3
Python 3.8.0 (default, Dec 15 2019, 14:19:02)
[GCC 6.2.0 20161005] on linux
Type "help", "copyright", "credits" or "license" for more information.
Also the pip and pip3 commands are totally f up:
root@esp32:/# pip
Traceback (most recent call last):
File "/usr/local/bin/pip", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
root@esp32:/# pip3
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 7, in <module>
from pip._internal.cli.main import main
File "/usr/local/lib/python3.5/dist-packages/pip/_internal/cli/main.py", line 60
sys.stderr.write(f"ERROR: {exc}")
^
SyntaxError: invalid syntax
I am totally noob at Linux, I just wanted to update Python from 2.x to 3.x so that Platformio could upgrade and now I messed up everything it seems.
You still have an option to implement in your enum this:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...}
Actually, the ticked answer is exactly right, but the answer can be in ES6
shape:
HTMLInputElementObject.oninput = () => {
console.log('run'); // Do something
}
Or can be written like below:
HTMLInputElementObject.addEventListener('input', (evt) => {
console.log('run'); // Do something
});
Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.
If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.
For example, in a query you link two tables in a select statement with a join:
SELECT a, b from table1 LEFT JOIN table2 USING (common_field);
Add following code in info.plist file
<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>
You need to manually download the apt deb package. Then run dpkg and it should install.
You can also look at the event.metaKey
attribute on the event if you are working with keydown events. Worked wonderfully for me! You can try it here.
You can set the id of the body of the page to some value that represents the current page. Then for each element in the menu you set a class specific to that menu item. And within your CSS you can set up a rule that will highlight the menu item specifically...
That probably didn't make much sense, so here's an example:
<body id="index">
<div id="menu">
<ul>
<li class="index" ><a href="index.html">Index page</a></li>
<li class="page1" ><a href="page1.html">Page 1</a></li>
</ul>
</div> <!-- menu -->
</body>
In the page1.html, you would set the id of the body to: id="page1"
.
Finally in your CSS you have something like the following:
#index #menu .index, #page1 #menu .page1 {
font-weight: bold;
}
You would need to alter the ID for each page, but the CSS remains the same, which is important as the CSS is often cached and can require a forced refresh to update.
It's not dynamic, but it's one method that's simple to do, and you can just include
the menu html from a template file using PHP or similar.
Use the following code
$("#modal").trigger('click');
From Primitives Data Types:
float:
Thefloat
data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations forbyte
andshort
, use afloat
(instead ofdouble
) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings coversBigDecimal
and other useful classes provided by the Java platform.
double
: Thedouble
data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.
In Class1:
Class2 inst = new Class2();
inst.UpdateEmployee();
From @NHG comment — works perfectly
{% for post in posts|slice(0,10) %}
First off, rmaddy's answer (above) is right: implementing NSCoding
doesn't help. However, you need to implement NSCoding
to use NSKeyedArchiver
and all that, so it's just one more step... converting via NSData
.
Example methods
- (NSUserDefaults *) defaults {
return [NSUserDefaults standardUserDefaults];
}
- (void) persistObj:(id)value forKey:(NSString *)key {
[self.defaults setObject:value forKey:key];
[self.defaults synchronize];
}
- (void) persistObjAsData:(id)encodableObject forKey:(NSString *)key {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:encodableObject];
[self persistObj:data forKey:key];
}
- (id) objectFromDataWithKey:(NSString*)key {
NSData *data = [self.defaults objectForKey:key];
return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}
So you can wrap your NSCoding
objects in an NSArray
or NSDictionary
or whatever...
Another option is to use showtext
package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.
# install.packages('showtext', dependencies = TRUE)
library(showtext)
Import some Google Fonts
# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")
Load font from the current search path into showtext
# Check the current search path for fonts
font_paths()
#> [1] "C:\\Windows\\Fonts"
# List available font files in the search path
font_files()
#> [1] "AcadEref.ttf"
#> [2] "AGENCYB.TTF"
#> [428] "pala.ttf"
#> [429] "palab.ttf"
#> [430] "palabi.ttf"
#> [431] "palai.ttf"
# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")
font_families()
#> [1] "sans" "serif" "mono" "wqy-microhei"
#> [5] "Montserrat" "Roboto" "Palatino"
## automatically use showtext for new devices
showtext_auto()
Plot: need to open Windows graphics device as showtext
does not work well with RStudio built-in graphics device
# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()
myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"
library(ggplot2)
a <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text = element_text(size = 16, family = myFont1)) +
annotate("text", 4, 30, label = 'Palatino Linotype',
family = myFont3, size = 10) +
annotate("text", 1, 11, label = 'Roboto', hjust = 0,
family = myFont2, size = 10)
## On-screen device
print(a)
## Save to PNG
ggsave("plot_showtext.png", plot = a,
type = 'cairo',
width = 6, height = 6, dpi = 150)
## Save to PDF
ggsave("plot_showtext.pdf", plot = a,
device = cairo_pdf,
width = 6, height = 6, dpi = 150)
## turn showtext off if no longer needed
showtext_auto(FALSE)
Edit: another workaround to use showtext
in RStudio. Run the following code at the beginning of the R session (source)
trace(grDevices::png, exit = quote({
showtext::showtext_begin()
}), print = FALSE)
Send a Location
header to redirect. Keep in mind this only works before any other output is sent.
header('Location: index.php'); // redirect to index.php
Use SimpleDateFormat parse method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString,formatter);
SQL server determines case sensitivity by COLLATION
.
COLLATION
can be set at various levels.
One can check the COLLATION
at each level as mentioned in Raj More's answer.
Check Server Collation
SELECT SERVERPROPERTY('COLLATION')
Check Database Collation
SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;
Check Column Collation
select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name
Check Expression Collation
For expression level COLLATION
you need to look at the expression. :)
It would be generally at the end of the expression as in below example.
SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;
Collation Description
For getting description of each COLLATION
value try this.
SELECT * FROM fn_helpcollations()
And you should see something like this.
You can always put a WHERE
clause to filter and see description only for your COLLATION
.
You can find a list of collations here.
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
This is needed for background location tracking since iOS 9.
you can set QVariant data for all items, then you can get the value when you need it.
there is an example code for this situation:
ui.comboBoxSheetSize->addItem("128 m", QVariant(128));
ui.comboBoxSheetSize->addItem("256 m", QVariant(256));
ui.comboBoxSheetSize->addItem("512 m", QVariant(512));
ui.comboBoxSheetSize->addItem("1024 m", QVariant(1024));
...
void Page::onComboSheetSizeChanged( int index )
{
int value = ui.comboBoxSheetSize->itemData(index).toInt();
}
by the way, i think i misunderstood your question. i think the way you get data is smart enough?
If you don't know when data will be added to #data
, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
See the NSString Class Reference.
NSString *string = @"5";
int value = [string intValue];
The selected answer didn't work for me, but it's close. I found a tutorial that worked for me and the certificate I obtained from StartCom.
Change the leader and trailer so the file looks similar to this:
-----BEGIN PKCS7-----
[... certificate content here ...]
-----END PKCS7-----
For example, my StartCom certificate began with:
-----BEGIN CERTIFICATE-----
and ended with:
-----END CERTIFICATE-----
Run the following OpenSSL command (works on Ubuntu 14.04.4, as of this writing):
openssl pkcs7 -print_certs –in pkcs7.p7b -out pem.cer
The output is a .cer with the certificate chain.
Reference: http://www.freetutorialssubmit.com/extract-certificates-from-P7B/2206
You need to stringify the object.
fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.
It is possible to go directly to a datatable, with JSON.NET and code like this:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
For me it works after adding only one line in httpd.conf as below (bold line).
<VirtualHost *:80>
ServerName: xxxxx
#ProxyPassReverse is not needed
ProxyPass /log4j ws://localhost:4711/logs
<VirtualHost *:80>
Apache version is 2.4.6 on CentOS.
.bashrc
is not sourced when you log in using SSH. You need to source it in your .bash_profile
like this:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
The 4K limit you read about is for the entire cookie, including name, value, expiry date etc. If you want to support most browsers, I suggest keeping the name under 4000 bytes, and the overall cookie size under 4093 bytes.
One thing to be careful of: if the name is too big you cannot delete the cookie (at least in JavaScript). A cookie is deleted by updating it and setting it to expire. If the name is too big, say 4090 bytes, I found that I could not set an expiry date. I only looked into this out of interest, not that I plan to have a name that big.
To read more about it, here are the "Browser Cookie Limits" for common browsers.
While on the subject, if you want to support most browsers, then do not exceed 50 cookies per domain, and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.
This means you can have 1 cookie of 4093 bytes, or 2 cookies of 2045 bytes, etc.
I used to say 4095 bytes due to IE7, however now Mobile Safari comes in with 4096 bytes with a 3 byte overhead per cookie, so 4093 bytes max.
The ng-if
directive, like other directives creates a child scope. See the script below (or this jsfiddle)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
function main($scope) {_x000D_
$scope.testa = false;_x000D_
$scope.testb = false;_x000D_
$scope.testc = false;_x000D_
$scope.obj = {test: false};_x000D_
}_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
<div ng-controller="main">_x000D_
_x000D_
Test A: {{testa}}<br />_x000D_
Test B: {{testb}}<br />_x000D_
Test C: {{testc}}<br />_x000D_
{{obj.test}}_x000D_
_x000D_
<div>_x000D_
testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
</div>_x000D_
<div ng-if="!testa">_x000D_
testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
</div>_x000D_
<div ng-if="!someothervar">_x000D_
object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>
_x000D_
So, your checkbox changes the testb
inside of the child scope, but not the outer parent scope.
Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.
This version is a more complete one:
const typeOf = obj => {
let type = ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1]
if (type === 'Object') {
const results = (/^(function|class)\s+(\w+)/).exec(obj.constructor.toString())
type = (results && results.length > 2) ? results[2] : ''
}
return type.toLowerCase()
}
Now not only you can have these results: (as they've been answered here)
undefined or empty -> undefined
null -> null
NaN -> number
5 -> number
{} -> object
[] -> array
'' -> string
function () {} -> function
/a/ -> regexp
new Date() -> date
new Error -> error
Promise.resolve() -> promise
function *() {} -> generatorfunction
new WeakMap() -> weakmap
new Map() -> map
But also you can get the type of every instance or object you construct from classes or functions: (which is not valid between other answers, all of them return object)
class C {
constructor() {
this.a = 1
}
}
function F() {
this.b = 'Foad'
}
typeOf(new C()) // -> c
typeOf(new F()) // -> f
You can use "svn export" for creating a copy of that folder without svn data, or you can add that folder to ignore list
There is some overhead with reflection, but it's a lot smaller on modern VMs than it used to be.
If you're using reflection to create every simple object in your program then something is wrong. Using it occasionally, when you have good reason, shouldn't be a problem at all.
To indent any old JSON, just bind it as Object
, like:
Object json = mapper.readValue(input, Object.class);
and then write it out with indentation:
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
this avoids your having to define actual POJO to map data to.
Or you can use JsonNode
(JSON Tree) as well.
Assuming you want curl installed: just execute the install command and see what happens.
$ sudo yum install curl
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.cat.pdx.edu
* epel: mirrors.kernel.org
* extras: mirrors.cat.pdx.edu
* remi-php72: repo1.sea.innoscale.net
* remi-safe: repo1.sea.innoscale.net
* updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
Others have already properly compared delete
with splice
.
Another interesting comparison is delete
versus undefined
: a deleted array item uses less memory than one that is just set to undefined
;
For example, this code will not finish:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
It produces this error:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
So, as you can see undefined
actually takes up heap memory.
However, if you also delete
the ary-item (instead of just setting it to undefined
), the code will slowly finish:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
These are extreme examples, but they make a point about delete
that I haven't seen anyone mention anywhere.
To add to the above answers, ensure you define your function like this:
public function functionName(Request $request) {
//
}
Note the "(Request $request)", now set a session like this:
$request->session()->put('key', 'value');
And retrieve the session in this way:
$data = $request->session()->get('key');
To erase the session try this:
$request->session()->forget('key');
or
$request->session()->flush();
First thing first, button()
is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func)
which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
if
using(var db = new MyDbContext())
{
await db.Database.ExecuteSqlCommandAsync(@"TRUNCATE TABLE MyTable"););
}
causes
Cannot truncate table 'MyTable' because it is being referenced by a FOREIGN KEY constraint.
I use this :
using(var db = new MyDbContext())
{
await db.Database.ExecuteSqlCommandAsync(@"DELETE FROM MyTable WHERE ID != -1");
}
The quirky syntax using conditions on the target (described by Mads) is the only supported way to perform conditional execution in core ANT.
ANT is not a programming language and when things get complicated I choose to embed a script within my build as follows:
<target name="prepare-copy" description="copy file based on condition">
<groovy>
if (properties["some.condition"] == "true") {
ant.copy(file:"${properties["some.dir"]}/true", todir:".")
}
</groovy>
</target>
ANT supports several languages (See script task), my preference is Groovy because of it's terse syntax and because it plays so well with the build.
Apologies, David I am not a fan of ant-contrib.
you can use a powerful library for management String which is undrescore.string.js
_('a <a href="#">link</a>').stripTags()
=> 'a link'
_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()
=> 'a linkalert("hello world!")'
Don't forget to import this lib as following :
<script src="underscore.js" type="text/javascript"></script>
<script src="underscore.string.js" type="text/javascript"></script>
<script type="text/javascript"> _.mixin(_.str.exports())</script>
I am using MacOSX with Eclipse 4.3 (Krepler). What I originally tried was to install Maven via the terminal using Brew. It installed correctly Maven 3.0.4. However when I tried to import any ready maven projects (File > Import > Maven) it would display the following two errors:
No marketplace entries found to handle Execution default-testResources
What I did is go to Help > Eclipse Marketplace and type "Maven" in the search bar and install the first default Maven client for Eclipse. Everything worked for me from this point.
Hope it helps to you too.
My problem was that the old assemblies were in the _bin_deployableAssemblies folder under the Web Application. This meant the old assemblies were overwriting the GAC assemblies when building the project.
I built a program that inserts multiple lines to a server that was located in another city.
I found out that using this method was about 10 times faster than executemany
. In my case tup
is a tuple containing about 2000 rows. It took about 10 seconds when using this method:
args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str)
and 2 minutes when using this method:
cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)
change it to 32-bit (true) it works
if you get this Length cannot be less than zero. Parameter name: length issue in iis server configuation do the simple thing change the connection string in web.config file like your sql server name and server name and restart iis then try to load the page it works
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
I don't think we can compare them side by side like who is better. That won't be a fair comparison simply because they are solving two different problems. Their requirements are different. It will be like comparing apples to oranges. They are different.
HTTP is a request-response protocol. The client (browser) wants something, the server gives it. That is. If the data client wants is big, the server might send streaming data to void unwanted buffer problems. Here the main requirement or problem is how to make the request from clients and how to response the resources(hypertext) they request. That is where HTTP shine.
In HTTP, only client requests. The server only responds.
WebSocket is not a request-response protocol where only the client can request. It is a socket(very similar to TCP socket). Mean once the connection is open, either side can send data until the underlining TCP connection is closed. It is just like a normal socket. The only difference with TCP socket is WebSocket can be used on the web. On the web, we have many restrictions on a normal socket. Most firewalls will block other ports than 80 and 433 that HTTP used. Proxies and intermediaries will be problematic as well. So to make the protocol easier to deploy to existing infrastructures WebSocket use HTTP handshake to upgrade. That means when the first time connection is going to open, the client sent an HTTP request to tell the server saying "That is not HTTP request, please upgrade to WebSocket protocol".
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Once the server understands the request and upgraded to WebSocket protocol, none of the HTTP protocols applied anymore.
So my answer is Neither one is better than each other. They are completely different.
Well, we can make everything under the name called HTTP as well. But shall we? If they are two different things, I will prefer two different names. So do Hickson and Michael Carter .
It's simple, Modulus operator(%) returns remainder after integer division. Let's take the example of your question. How 27 % 16 = 11? When you simply divide 27 by 16 i.e (27/16) then you get remainder as 11, and that is why your answer is 11.
A Regex
approach using lazy match and back-reference:
foreach (Match match in Regex.Matches(
"morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
@"<([^>]+)>(.*?)</\1>"))
{
Console.WriteLine("{0}={1}",
match.Groups[1].Value,
match.Groups[2].Value);
}
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration
I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.
Note that these parens are not part of a method call — they're only implicit string literal concatenation.
Python 2:
def fun():
print ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
Python 3 (with parens for print function):
def fun():
print(('{0} Here is a really '
'long sentence with {1}').format(3, 5))
Personally I think it's cleanest to separate concatenating the long string literal from printing it:
def fun():
s = ('{0} Here is a really '
'long sentence with {1}').format(3, 5)
print(s)
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
Based on @cudds's answer:
function s3size()
{
for path in $*; do
size=$(aws s3 ls "s3://$path" --recursive | grep -v -E "(Bucket: |Prefix: |LastWriteTime|^$|--)" | awk 'BEGIN {total=0}{total+=$3}END{printf "%.2fGb\n", (total/1024/1024/1024)}')
echo "[s3://$path]=[$size]"
done
}
...
$ s3size bucket-a bucket-b/dir
[s3://bucket-a]=[24.04Gb]
[s3://bucket-b/dir]=[26.69Gb]
Also, Cyberduck conveniently allows for calculation of size for a bucket or a folder.
(Following is a late but complete answer)
FileReader.readAsBinaryString()
is deprecated. Don't use it! It's no longer in the W3C File API working draft:
void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);
NB: Note that File
is a kind of extended Blob
structure.
Mozilla still implements readAsBinaryString()
and describes it in MDN FileApi documentation:
void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);
The reason behind readAsBinaryString()
deprecation is in my opinion the following: the standard for JavaScript strings are DOMString
which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.
We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob
and typed arrays
(ArrayBuffer
and the not-yet-implemented but not necessary StringView
) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.
XMLHttpRequest.send()
has the following invocations options:
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
XMLHttpRequest.sendAsBinary()
has the following invocations options:
void sendAsBinary( in DOMString body );
sendAsBinary() is NOT a standard and may not be supported in Chrome.
So you have several options:
send()
the FileReader.result
of FileReader.readAsArrayBuffer ( fileObject )
. It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.send()
the FileReader.result
of FileReader.readAsDataURL( fileObject )
. It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.sendAsBinary()
the FileReader.result
of FileReader.readAsBinaryString( fileObject )
MDN states that:
The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.
One more very basic and simple solution. Run the related python version's installation file (setup file) and click repair mode. It hardly takes one-two minutes and everything works perfectly after that :)
Open where your KEYTOOL.EXE in yourJAVA file such as e.g C:\Program Files\Java\bin\keytool.exe.
HOLD SHIFT and Right Click on the BIN Folder where your keytool.exe is located and click open CMD or RUN Command from here.
This opens cmd. then type in
keytool -exportcert -alias NAME OF YOUR KEYSTORE -keystore PATH OF KEYSTORE.jks" | "C:\OpenSSL\bin\openssl" sha1 -binary | "C:\OpenSSL\bin\openssl" base64
If str
is null, undefined or 0, this code will set it to "hai"
function(nodeBox, str) {
str = str || "hai";
.
.
.
If you also need to pass 0, you can use:
function(nodeBox, str) {
if (typeof str === "undefined" || str === null) {
str = "hai";
}
.
.
.
Use xpath more directly for both performance and clarity.
time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"
df <- data.frame(
latitude=data[["number(//point/@latitude)"]],
longitude=data[["number(//point/@longitude)"]],
start_valid_time=sapply(data[time_path], xmlValue),
hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))
leading to
> head(df, 2)
latitude longitude start_valid_time hourly_temperature
1 29.81 -82.42 2014-02-14T18:00:00-05:00 60
2 29.81 -82.42 2014-02-14T19:00:00-05:00 55
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
For brevity, we can understand these two APIs like below:
X.class.isAssignableFrom(Y.class)
If X
and Y
are the same class, or X
is Y
's super class or super interface, return true, otherwise, false.
X.class.isInstance(y)
Say y
is an instance of class Y
, if X
and Y
are the same class, or X
is Y
's super class or super interface, return true, otherwise, false.
Add a style = color:black !important;
in your input type.
The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}
Demo:
input {_x000D_
font: small-caption;_x000D_
font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
ImageView Button = (ImageView)findViewById(R.id.button);
Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("http://google.com/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
I realise this answer is late, but I found a rather simple, elegant, and effective solution to this problem and felt it necessary to post it here.
However one thing I feel I need to make clear is that this doesn't start gif animation on mouseover, pause it on mouseout, and continue it when you mouseover it again. That, unfortunately, is impossible to do with gifs. (It is possible to do with a string of images displayed one after another to look like a gif, but taking apart every frame of your gifs and copying all those urls into a script would be time consuming)
What my solution does is make an image looks like it starts moving on mouseover. You make the first frame of your gif an image and put that image on the webpage then replace the image with the gif on mouseover and it looks like it starts moving. It resets on mouseout.
Just insert this script in the head section of your HTML:
$(document).ready(function()
{
$("#imgAnimate").hover(
function()
{
$(this).attr("src", "GIF URL HERE");
},
function()
{
$(this).attr("src", "STATIC IMAGE URL HERE");
});
});
And put this code in the img tag of the image you want to animate.
id="imgAnimate"
This will load the gif on mouseover, so it will seem like your image starts moving. (This is better than loading the gif onload because then the transition from static image to gif is choppy because the gif will start on a random frame)
for more than one image just recreate the script create a function:
<script type="text/javascript">
var staticGifSuffix = "-static.gif";
var gifSuffix = ".gif";
$(document).ready(function() {
$(".img-animate").each(function () {
$(this).hover(
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(staticGifSuffix, gifSuffix));
},
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(gifSuffix, staticGifSuffix));
}
);
});
});
</script>
</head>
<body>
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
</body>
That code block is a functioning web page (based on the information you have given me) that will display the static images and on hover, load and display the gif's. All you have to do is insert the url's for the static images.
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Start your activity with request code :
StartActivityForResult(intent,1234);
And you can close it from any other activity like this :
finishActivity(1234);
you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.
Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html
If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.
I generate a table dynamically out a database, receive the data in JSON and put it into a table. Every table row got a unique ID
, which is needed for further actions, so, if the DOM is altered you need a different approach:
$("table").delegate("tr", "click", function() {
var id=$(this).attr('id');
alert("ID:"+id);
});
Getting a bit like code golf here, but since nearly all the answers so far are bash (barring one lonely cmd one), here's a windows cross-platform command that uses powershell (because awesome):
ls *.avi|%{ ffmpeg -i $_ <ffmpeg options here> $_.name.replace($_.extension, ".mp4")}
You can change *.avi to whatever matches your source footage.
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
i am using my custom implementation in kotlin:
/**
* Created by Anton Kogan on 10/9/2020
*/
object JsonParser {
val TAG = "JsonParser"
/**
* parse json object
* @param objJson
* @param include - all keys, that you want to display
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?, map :HashMap<String, String>, include : Array<String>?): Map<String, String> {
// If obj is a json array
if (objJson is JSONArray) {
for (i in 0 until objJson.length()) {
parseJson(objJson[i], map, include)
}
} else if (objJson is JSONObject) {
val it: Iterator<*> = objJson.keys()
while (it.hasNext()) {
val key = it.next().toString()
// If you get an array
when (val jobject = objJson[key]) {
is JSONArray -> {
Log.e(TAG, " JSONArray: $jobject")
parseJson(
jobject, map, include
)
}
is JSONObject -> {
Log.e(TAG, " JSONObject: $jobject")
parseJson(
jobject, map, include
)
}
else -> {
//
if(include == null || include.contains(key)) // here is check for include param
{
map[key] = jobject.toString()
Log.e(TAG, " adding to map: $key $jobject")
}
}
}
}
}
return map
}
/**
* parse json object
* @param objJson
* @param include - all keys, that you want to display
* @return Map<String, String>
* @throws JSONException
*/
@Throws(JSONException::class)
fun parseJson(objJson: Any?, map :HashMap<String, String>): Map<String, String> {
return parseJson(objJson, map, null)
}
}
You can use it like:
val include= arrayOf(
"atHome",//JSONArray
"cat",
"dog",
"persons",//JSONArray
"man",
"woman"
)
JsonParser.parseJson(jsonObject, map, include)
val linearContent: LinearLayout = taskInfoFragmentBinding.infoContainer
here is some useful links:
json parsing :
plugin: https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-
create POJOs from json: https://codebeautify.org/jsonviewer
Retrofit: https://square.github.io/retrofit/
Add position:fixed
. Then the cover is fixed over the whole screen, also when you scroll.
And add maybe also margin: 0; padding:0;
so it wont have some space's around the cover.
#dimScreen
{
position:fixed;
padding:0;
margin:0;
top:0;
left:0;
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
}
And if it shouldn't stick on the screen fixed, use position:absolute;
CSS Tricks have also an interesting article about fullscreen property.
Edit:
Just came across this answer, so I wanted to add some additional things.
Like Daniel Allen Langdon mentioned in the comment, add top:0; left:0;
to be sure, the cover sticks on the very top and left of the screen.
If you some elements are at the top of the cover (so it doesn't cover everything), then add z-index
. The higher the number, the more levels it covers.
If your directory structure is like this,
site
application
controller
folder_1
first_controller.php
second_controller.php
folder_2
first_controller.php
second_controller.php
And when you are going to redirect it in same controller in which you are working then just write the following code.
$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
redirect('same_controller/method', 'refresh');
}
And if you want to redirect to another control then use the following code.
$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
redirect('folder_name/any_controller_name/method', 'refresh');
}
I am facing a similar problem here. Our users are migrating their jobs from freestyle to pipeline. They do not want Jenkinsfile stored in their repos(historical reason) and still want to use "Git Parameter" plugin
So we have to use use "Pipeline script" and develop a different plugin which works like "Git Parameter".
This new plugin does not integrate with SCM setting in the project. The plugin is at https://plugins.jenkins.io/list-git-branches-parameter
Hope it helps you as well
for ex.
<input b="demo">
And
(input[@b='demo'])[1]
compile('com.android.support:support-v4:19.1.0'){
force = true
}
Helped me, taken from here
greadlink is the gnu readlink that implements -f. You can use macports or others as well, I prefer homebrew.
List.indexOf()
will give you what you want, provided you know precisely what you're after, and provided that the equals()
method for Party
is well-defined.
Party searchCandidate = new Party("FirstParty");
int index = cave.parties.indexOf(searchCandidate);
This is where it gets interesting - subclasses shouldn't be examining the private properties of their parents, so we'll define equals()
in the superclass.
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CaveElement)) {
return false;
}
CaveElement that = (CaveElement) o;
if (index != that.index) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
return true;
}
It's also wise to override hashCode
if you override equals
- the general contract for hashCode
mandates that, if x.equals(y)
, then x.hashCode() == y.hashCode().
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + index;
return result;
}
EDIT:
I don't think Any of the commands will work. In linux Ctrl-L will do the job. in windows there is no equivalent. You can only Exit MySql, Type CLS
and then re-enter MySql.
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good way to transmit information between threads is the built-in Queue.Queue class, as it offers thread safety.
I created the following decorator to make it act in a similar fashion to the threadpool:
def threaded(f, daemon=False):
import Queue
def wrapped_f(q, *args, **kwargs):
'''this function calls the decorated function and puts the
result in a queue'''
ret = f(*args, **kwargs)
q.put(ret)
def wrap(*args, **kwargs):
'''this is the function returned from the decorator. It fires off
wrapped_f in a new thread and returns the thread object with
the result queue attached'''
q = Queue.Queue()
t = threading.Thread(target=wrapped_f, args=(q,)+args, kwargs=kwargs)
t.daemon = daemon
t.start()
t.result_queue = q
return t
return wrap
Then you just use it as:
@threaded
def long_task(x):
import time
x = x + 5
time.sleep(5)
return x
# does not block, returns Thread object
y = long_task(10)
print y
# this blocks, waiting for the result
result = y.result_queue.get()
print result
The decorated function creates a new thread each time it's called and returns a Thread object that contains the queue that will receive the result.
UPDATE
It's been quite a while since I posted this answer, but it still gets views so I thought I would update it to reflect the way I do this in newer versions of Python:
Python 3.2 added in the concurrent.futures
module which provides a high-level interface for parallel tasks. It provides ThreadPoolExecutor
and ProcessPoolExecutor
, so you can use a thread or process pool with the same api.
One benefit of this api is that submitting a task to an Executor
returns a Future
object, which will complete with the return value of the callable you submit.
This makes attaching a queue
object unnecessary, which simplifies the decorator quite a bit:
_DEFAULT_POOL = ThreadPoolExecutor()
def threadpool(f, executor=None):
@wraps(f)
def wrap(*args, **kwargs):
return (executor or _DEFAULT_POOL).submit(f, *args, **kwargs)
return wrap
This will use a default module threadpool executor if one is not passed in.
The usage is very similar to before:
@threadpool
def long_task(x):
import time
x = x + 5
time.sleep(5)
return x
# does not block, returns Future object
y = long_task(10)
print y
# this blocks, waiting for the result
result = y.result()
print result
If you're using Python 3.4+, one really nice feature of using this method (and Future objects in general) is that the returned future can be wrapped to turn it into an asyncio.Future
with asyncio.wrap_future
. This makes it work easily with coroutines:
result = await asyncio.wrap_future(long_task(10))
If you don't need access to the underlying concurrent.Future
object, you can include the wrap in the decorator:
_DEFAULT_POOL = ThreadPoolExecutor()
def threadpool(f, executor=None):
@wraps(f)
def wrap(*args, **kwargs):
return asyncio.wrap_future((executor or _DEFAULT_POOL).submit(f, *args, **kwargs))
return wrap
Then, whenever you need to push cpu intensive or blocking code off the event loop thread, you can put it in a decorated function:
@threadpool
def some_long_calculation():
...
# this will suspend while the function is executed on a threadpool
result = await some_long_calculation()
The above answers were helpful, but in case this helps anyone - I had this exact problem, and it turned out that I was (windows networking) sharing the root folder that the site was being hosted from. We killed the share, and added the Users permission to read/execute and it worked again just fine.
I suspect the share messed it up.
You might find Perl or Python useful to get data from the serial port. To send data to the server, the solution could be easy if the server is (let's say) an HTTP application or even a popular database. The solution would be not so easy if it is some custom/proprietary TCP application.
This works for me (mostly).
Put this at the bottom of your page.
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="application/javascript" src="/script/jquery.browser.js">
</script>
<script type="application/javascript" src="/script/jquery-iframe-auto-height.js">
</script>
<script type="application/javascript">
jQuery('iframe').iframeAutoHeight();
$(window).load(
function() {
jQuery('iframe').iframeAutoHeight();
}
);
// for when content is not html e.g. a PDF
function setIframeHeight() {
$('.iframe_fullHeight').each(
function (i, item) {
item.height = $(document).height();
}
);
};
$(document).ready( function () {
setIframeHeight();
});
$(window).resize( function () {
setIframeHeight();
});
</script>
The first half is from ???, and works when there is html in the iframe.
The second half sets the iframe to page height (not content height), when iframes class is iframe_fullHeight
. You can use this if the content is a PDF or other such like, but you have to set the class. Also can only be used when being full height is appropriate.
Note: for some reason, when it recalculates after window resize, it gets height wrong.
You need to install “Visual Studio extension development” workload and “Class Designer” optional component from the Visual Studio 2017 Installer to get the feature.
See: Visual Studio Community 2017 component directory
But this kind of item is not available on all project types. Just try for yourself:
In a Console App (.NET Framework) is available;
In a Console App (.NET Core) is not available.
I couldn't find more info on future availability also for .NET Core projects.
You have your slash backwards, it should be "\n"
Even though --files
is no longer supported, you can use an env variable to provide a list of files:
// karma.conf.js
function getSpecs(specList) {
if (specList) {
return specList.split(',')
} else {
return ['**/*_spec.js'] // whatever your default glob is
}
}
module.exports = function(config) {
config.set({
//...
files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
});
});
Then in CLI:
$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run
Looks like Windows might just let you do this...
Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.
To validate base64 image we can use this regex
/^data:image/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}
private validBase64Image(base64Image: string): boolean {
const regex = /^data:image\/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}/;
return base64Image && regex.test(base64Image);
}
You will find multiple different methods that people use and they each have there own place.
<?php if($first_condition): ?>
/*$first_condition is true*/
<?php elseif ($second_condition): ?>
/*$first_condition is false and $second_condition is true*/
<?php else: ?>
/*$first_condition and $second_condition are false*/
<?php endif; ?>
If in your php.ini attribute short_open_tag = true
(this is normally found on line 141
of the default php.ini file) you can replace your php open tag from <?php
to <?
. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php
. short_open_tag
is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag
turned off.
A quick search of short_open_tag
in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag
That's a lot of people having problems with something they should just not play with.
with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag
set to true
.
short_open_tag
will be removed in PHP6 so don't use short hand tags.
all future PHP versions will be dropping short_open_tag
"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working
and
Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .
Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem
and
To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?
You may also see people use the following example:
<?php if($first_condition){ ?>
/*$first_condition is true*/
<?php }else if ($second_condition){ ?>
/*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
/*$first_condition and $second_condition are false*/
<?php } ?>
This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.
The following example shows when to use the bracket method
<?php
if($first_condition){
/*$first_condition is true*/
}else if ($second_condition){
/*$first_condition is false and $second_condition is true*/
}else{
/*$first_condition and $second_condition are false*/
}
?>
If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.
UPDATE
based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.
layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/layoutTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</RelativeLayout>
class file:
setContentView(R.layout.layout_dynamic);
layoutTest=(LinearLayout)findViewById(R.id.layoutTest);
TextView textView = new TextView(getApplicationContext());
textView.setText("testDynamic textView");
layoutTest.addView(textView);
I know I'm late to the party, but to specifically answer the two questions:
"I just want to disable specific clicky-things so that:
How hard can this be?"
They stop clicking
1. For buttons like <button>
or <input type="button">
you add the attribute: disabled
.
<button type="submit" disabled>Register</button>
<input type="button" value="Register" disabled>
2. For links, ANY link... actually, any HTML element, you can use CSS3 pointer events.
.selector { pointer-events:none; }
Browser support for pointer events is awesome by today's state of the art (5/12/14). But we usually have to support legacy browsers in the IE realm, so IE10 and below DO NOT support pointer events: http://caniuse.com/pointer-events. So using one of the JavaScript solutions mentioned by others here may be the way to go for legacy browsers.
More info about pointer events:
They look disabled
Obviously this a CSS answer, so:
1. For buttons like <button>
or <input type="button">
use the [attribute]
selector:
button[disabled] { ... }
input[type=button][disabled] { ... }
--
Here's a basic demo with the stuff I mentioned here: http://jsfiddle.net/bXm5B/4/
Hope this helps.
http://blog.mongodb.org/post/183689081/storing-large-objects-and-files-in-mongodb
There is a Mongoose plugin available on NPM called mongoose-file. It lets you add a file field to a Mongoose Schema for file upload. I have never used it but it might prove useful. If the images are very small you could Base64 encode them and save the string to the database.
Storing some small (under 1MB) files with MongoDB in NodeJS WITHOUT GridFS
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "@doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
The head
command can get the first n
lines. Variations are:
head -7 file
head -n 7 file
head -7l file
which will get the first 7 lines of the file called "file"
. The command to use depends on your version of head
. Linux will work with the first one.
To append lines to the end of the same file, use:
echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file
or:
echo 'first line to add
second line to add
third line to add' >>file
to do it in one hit.
So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt
file to output.txt
and append a line with five "="
characters, you could use something like:
( head -10 input.txt ; echo '=====' ) > output.txt
In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.
a simple line , after that you can see also a doted line
import java.awt.*;
import javax.swing.*;
import java.awt.Graphics.*;
import java.awt.Graphics2D.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Event.*;
import java.awt.Component.*;
import javax.swing.SwingUtilities;
/**
*
* @author junaid
*/
public class JunaidLine extends JPanel{
//private Graphics Graphics;
private void doDrawing(Graphics g){
Graphics2D g2d=(Graphics2D) g;
float[] dash1 = {2f,0f,2f};
g2d.drawLine(20, 40, 250, 40);
BasicStroke bs1 = new BasicStroke(1,BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND,1.0f,dash1,2f);
g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent( g);
doDrawing(g);
}
}
class BasicStrokes extends JFrame{
public BasicStrokes(){
initUI();
}
private void initUI(){
setTitle("line");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
add(new JunaidLine());
setSize(280,270);
setLocationRelativeTo(null);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
BasicStrokes bs = new BasicStrokes();
bs.setVisible(true);
}
});
}
}
In C++
Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.
Global variables and ordinary functions have external linkage.
Static object or function name at file scope is local to translation unit. That is called as Internal Linkage
Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.
You can run:
valgrind --leak-check=full --log-file="logfile.out" -v [your_program(and its arguments)]
$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";
if(strlen($string) >= 50)
{
echo substr($string, 50); //prints everything after 50th character
echo substr($string, 0, 50); //prints everything before 50th character
}
Alternatively, you could do the following:
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in typeof(PaymentTerm).GetEnumValues())
{
var type = item.GetType();
var name = type.GetField(item.ToString()).GetCustomAttributesData().FirstOrDefault()?.NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
selectListItems.Add(new SelectListItem(name, type.Name));
}
If you are running python version 3.9 pandas wont work as of now. So install python version 3.7 or below to mitigate this issue. Or else if you want to stick with python 3.9 try install pandas by compiling the library
If you want to pass the form to the controller for validation purposes you can simply pass it as an argument to the method handling the submission. Use the form name, so for the original question it would be something like:
<button ng-click="submit(customerForm)">Save</button>
This seems like an easy task, but you have to take care of several things:
<script>
or <style>
contents, or HTML tags or attributes, which is not always desiredtitle
and alt
(in a controlled manner) as wellGuarding against xss attacks generally can’t be solved by using the approaches below. E.g. if a fetch
call reads a URL from somewhere on the page, then sends a request to that URL, the functions below won’t stop that, since this scenario is inherently unsafe.
This basically selects all elements that contain normal text, goes through their child nodes — among those are also text nodes —, seeks those text nodes out and replaces their contents.
You can optionally specify a different root target
, e.g. replaceOnDocument(/€/g, "$", { target: someElement });
; by default, the <body>
is chosen.
const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {
// Handle `string` — see the last section
[
target,
...target.querySelectorAll("*:not(script):not(noscript):not(style)")
].forEach(({childNodes: [...nodes]}) => nodes
.filter(({nodeType}) => nodeType === document.TEXT_NODE)
.forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
};
replaceOnDocument(/€/g, "$");
Now, this is a little more complex: you need to check three cases: whether a node is a text node, whether it’s an element and its attribute should be replaced, or whether it’s an element and its property should be replaced. A replacer
object provides methods for text nodes and for elements.
Before replacing attributes and properties, the replacer needs to check whether the element has a matching attribute; otherwise new attributes get created, undesirably. It also needs to check whether the targeted property is a string, since only strings can be replaced, or whether the matching property to the targeted attribute is not a function, since this may lead to an xss attack.
In the example below, you can see how to use the extended features: in the optional third argument, you may add an attrs
property and a props
property, which is an iterable (e.g. an array) each, for the attributes to be replaced and the properties to be replaced, respectively.
You’ll also notice that this snippet uses flatMap
. If that’s not supported, use a polyfill or replace it by the reduce
–concat
, or map
–reduce
–concat
construct, as seen in the linked documentation.
const replaceOnDocument = (() => {
const replacer = {
[document.TEXT_NODE](node, pattern, string){
node.textContent = node.textContent.replace(pattern, string);
},
[document.ELEMENT_NODE](node, pattern, string, {attrs, props} = {}){
attrs.forEach((attr) => {
if(typeof node[attr] !== "function" && node.hasAttribute(attr)){
node.setAttribute(attr, node.getAttribute(attr).replace(pattern, string));
}
});
props.forEach((prop) => {
if(typeof node[prop] === "string" && node.hasAttribute(prop)){
node[prop] = node[prop].replace(pattern, string);
}
});
}
};
return (pattern, string, {target = document.body, attrs: [...attrs] = [], props: [...props] = []} = {}) => {
// Handle `string` — see the last section
[
target,
...[
target,
...target.querySelectorAll("*:not(script):not(noscript):not(style)")
].flatMap(({childNodes: [...nodes]}) => nodes)
].filter(({nodeType}) => replacer.hasOwnProperty(nodeType))
.forEach((node) => replacer[node.nodeType](node, pattern, string, {
attrs,
props
}));
};
})();
replaceOnDocument(/€/g, "$", {
attrs: [
"title",
"alt",
"onerror" // This will be ignored
],
props: [
"value" // Changing an `<input>`’s `value` attribute won’t change its current value, so the property needs to be accessed here
]
});
If you need to make it work with HTML entities like ­
, the above approaches will just literally produce the string ­
, since that’s an HTML entity and will only work when assigning .innerHTML
or using related methods.
So let’s solve it by passing the input string to something that accepts an HTML string: a new, temporary HTMLDocument
. This is created by the DOMParser
’s parseFromString
method; in the end we read its documentElement
’s textContent
:
string = new DOMParser().parseFromString(string, "text/html").documentElement.textContent;
If you want to use this, choose one of the approaches above, depending on whether or not you want to replace HTML attributes and DOM properties in addition to text; then simply replace the comment // Handle `string` — see the last section
by the above line.
Now you can use replaceOnDocument(/Güterzug/g, "Güter­zug");
.
NB: If you don’t use the string handling code, you may also remove the {
}
around the arrow function body.
Note that this parses HTML entities but still disallows inserting actual HTML tags, since we’re reading only the textContent
. This is also safe against most cases of xss: since we’re using parseFromString
and the page’s document
isn’t affected, no <script>
gets downloaded and no onerror
handler gets executed.
You should also consider using \xAD
instead of ­
directly in your JavaScript string, if it turns out to be simpler.
Let me try to make it simple, suppose URL of the site is http://example.com/ and let's suppose you need to sign up by filling username and password, so we go to the login page say http://example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
You can use [].reduce
for a more compact implementation of RobG's approach:
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};
Reading the friendly manual? Who'd want to do that?
start = Time.now
largest_known_fixnum = 1
smallest_known_bignum = nil
until smallest_known_bignum == largest_known_fixnum + 1
if smallest_known_bignum.nil?
next_number_to_try = largest_known_fixnum * 1000
else
next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky
end
if next_number_to_try <= largest_known_fixnum ||
smallest_known_bignum && next_number_to_try >= smallest_known_bignum
raise "Can't happen case"
end
case next_number_to_try
when Bignum then smallest_known_bignum = next_number_to_try
when Fixnum then largest_known_fixnum = next_number_to_try
else raise "Can't happen case"
end
end
finish = Time.now
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"
You don't have to change it in the jquery-ui css file (it can be confusing if you change the default files), it is enough if you add
div.ui-datepicker{
font-size:10px;
}
in a stylesheet loaded after the ui-files
div.ui-datepicker is needed in case ui-widget is mentioned after ui-datepicker in the declaration
The problem almost always has something to do with "nested" z-indexes. As an Example:
<div style="z-index:1">
some content A
<div style="z-index:1000000000">
some content B
</div>
</div>
<div style="z-index:10">
Some content C
</div>
if you look at the z-index only you would expect B,C,A, but because B is nested in a div that is expressly set to 1, it will show up as C,B,A.
Setting position:fixed locks the z-index for that element and all its children, which is why changing that can solve the problem.
The solution is to find the parent element that has the z-index set and either adjust the setting or move the content so the layers and their parent containers stack up the way you want. Firebug in Firefox has a tab in the far right named "Layout" and you can quickly go up the parent elements and see where the z-index is set.
POD stands for Plain Old Data - that is, a class (whether defined with the keyword struct
or the keyword class
) without constructors, destructors and virtual members functions. Wikipedia's article on POD goes into a bit more detail and defines it as:
A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
Greater detail can be found in this answer for C++98/03. C++11 changed the rules surrounding POD, relaxing them greatly, thus necessitating a follow-up answer here.
You can set the onClick
event in your custom adapter's getView
method..
check the link http://androidforbeginners.blogspot.it/2010/03/clicking-buttons-in-listview-row.html
Tele2 provides ftp://speedtest.tele2.net , you can log in as anonymous and upload anything to test your upload speed. For download testing they provide fixed size files, you can choose which fits best to your test.
You can connect with username of anonymous and any password (e.g. anonymous ). You can upload files to upload folder. You can't create new folder here. Your file is deleted immediately after successful upload.
Found here: http://speedtest.tele2.net/
Do you mean in Python or using ctypes?
In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.
In the second case, you can use type()
:
>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>
For more reference on ctypes, an its type, see the official documentation.
If you are not already using lodash I wouldn't recommend installing it just for this one method. I suggest instead a more narrowly specialized library such as 'clone':
npm install clone
Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray()
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
Try the following:
SELECT * FROM
(
SELECT Id, Name, Age, Comments, Row_Number() OVER(PARTITION BY Name, Age ORDER By Name)
AS Rank
FROM Customers
) AS B WHERE Rank>1
In my case, the module containing the component using the *ngFor resulting in this error, was not included in the app.module.ts. Including it there in the imports array resolved the issue for me.
I was facing the same issue, I resolved this by replacing dependencies in App level Build.gradle file
"""
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'androidx.multidex:multidex:2.0.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
BY
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.multidex:multidex:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
This resolves my issue.
Using subprocess.run
import subprocess
ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
processNames = subprocess.run(['grep', 'process_name'],
input=ps.stdout, capture_output=True)
print(processNames.stdout)
import os
list = os.popen('pwd').read()
In this case you will only have one element in the list.
You can also use the Properties class
Here's the constants file called
# this will hold all of the constants
frameWidth = 1600
frameHeight = 900
Here is the code that uses the constants
public class SimpleGuiAnimation {
int frameWidth;
int frameHeight;
public SimpleGuiAnimation() {
Properties properties = new Properties();
try {
File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
}
catch (FileNotFoundException fileNotFoundException) {
System.out.println("Could not find the properties file" + fileNotFoundException);
}
catch (Exception exception) {
System.out.println("Could not load properties file" + exception.toString());
}
this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
}
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
use id of the element except x_path.It will work 100%
Check out the help command:
svn help copy
-r [--revision] arg : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
To actually specify this on the command line using your example:
svn copy -r123 http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Where 123
would be the revision number in trunk you want to copy. As others have noted, you can also use the @ syntax. I prefer the clearer separation of the revision # from the URL, personally.
As noted in the help, you can replace a revision # with certain words as well:
svn copy -rPREV http://svn.example.com/repos/calc/trunk \
http://svn.example.com/repos/calc/branches/my-calc-branch
Would copy the "revision just before COMMITTED".
select substring(@string,charindex('@first',@string)+1,charindex('@second',@string)-(charindex('@first',@string)+1))
There are a lot of different ways to look at this decision from development, IT, and business objectives, so don't feel bad if it seems overwhelming. But also - don't overthink scalability.
Think about your requirements.
I've engineered websites which have serviced over 8M uniques a day and delivered terabytes of video a week built on infrastructures starting at $250k in capital hardware unr by a huge $MM IT labor staff.
But I've also had smaller websites which were designed to generate $10-$20k per year, didn't have very high traffic, db or processing requirements, and I ran those off a $10/mo generic hosting account without compromise.
In the future, deployment will look more like Heroku than AWS, just because of progress. There is zero value in the IT knob-turning of scaling internet infrastructures which isn't increasingly automatable, and none of it has anything to do with the value of the product or service you are offering.
Also, keep in mind with a commercial website - scalability is what we often call a 'good problem to have' - although scalability issues with sites like Facebook and Twitter were very high-profile, they had zero negative effect on their success - the news might have even contributed to more signups (all press is good press).
If you have a service which is generating a 100k+ uniques a day and having scaling issues, I'd be glad to take it off your hands for you no matter what the language, db, platform, or infrastructure you are running on!
Scalability is a fixable implementation problem - not having customers is an existential issue.
Edit: As per the Mr Me comment on this answer, it looks like compression is now available for JPG/WebP formats ( see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL ).
As far as I know, you cannot compress images using canvas, instead, you can resize it. Using canvas.toDataURL will not let you choose the compression ratio to use. You can take a look at canimage that does exactly what you want : https://github.com/nfroidure/CanImage/blob/master/chrome/canimage/content/canimage.js
In fact, it's often sufficient to just resize the image to decrease it's size but if you want to go further, you'll have to use newly introduced method file.readAsArrayBuffer to get a buffer containing the image data.
Then, just use a DataView to read it's content according to the image format specification (http://en.wikipedia.org/wiki/JPEG or http://en.wikipedia.org/wiki/Portable_Network_Graphics).
It'll be hard to deal with image data compression, but it is worse a try. On the other hand, you can try to delete the PNG headers or the JPEG exif data to make your image smaller, it should be easier to do so.
You'll have to create another DataWiew on another buffer and fill it with the filtered image content. Then, you'll just have to encode you're image content to DataURI using window.btoa.
Let me know if you implement something similar, will be interesting to go through the code.
Actually, this is a duplicate of Encrypt Password in Configuration Files?.
The best solution I found so far is in this answert: https://stackoverflow.com/a/1133815/1549977
Pros: Password is saved a a char array, not as a string. It's still not good, but better than anything else.
Github uses the following .gitignore for their programs
https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder
to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
string server = builder.DataSource;
string database = builder.InitialCatalog;
or
System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;
You can use percent values:
background: yellow url("arrow1.gif") no-repeat 95% 50%;
Not pixel perfect, but…
int()
only works for strings that look like integers; it will fail for strings that look like floats. Use float()
instead.
I made a sample project to demonstrate how I handled this, which is indeed another sys.path hack as indicated above. Python Sibling Import Example, which relies on:
if __name__ == '__main__':
import os
import sys
sys.path.append(os.getcwd())
This seems to be pretty effective so long as your working directory remains at the root of the Python project. If anyone deploys this in a real production environment it'd be great to hear if it works there as well.
I think you should casting variable or use Integer
class by call out method doubleValue()
.
I had the same problem and wrote a simple python module which compares two same-size images using pillow's ImageChops to create a black/white diff image and sums up the histogram values.
You can get either this score directly, or a percentage value compared to a full black vs. white diff.
It also contains a simple is_equal function, with the possibility to supply a fuzzy-threshold under (and including) the image passes as equal.
The approach is not very elaborate, but maybe is of use for other out there struggling with the same issue.
The correct answer (as of Dec 2018) is... you can't. Upgrading conda install python=3.6
may work, but it might not if you have packages that are necessary, but cannot be uninstalled.
Anaconda uses a default environment named base
and you cannot create a new (e.g. python 3.6) environment with the same name. This is intentional. If you want your base Anaconda to be python 3.6, the right way to do this is to install Anaconda for python 3.6. As a package manager, the goal of Anaconda is to make different environments encapsulated, hence why you must source activate into them and why you can't just quietly switch the base package at will as this could lead to many issues on production systems.
Note that PHP mail settings come from your php.ini
file. The default looks more or less like this:
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =
; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = On
; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log =
By editing your php.ini
file you should be able to fix the problem without changing your PHP scripts. Also, you can test a connection with the telnet tool and the HELO
, MAIL FROM
, RCPT TO
, DATA
, QUIT
commands if you directly connect to an SMTP server. With sendmail
, you don't even need that, sendmail
should know what it's doing (although in your case it probably wasn't and the sendmail
settings probably needed a little help.)
Update: in most cases, telnet
is not installed anymore because it's considered dangerous (i.e. it gives you a clear text connection which is generally fine on your local network, but not so much to remote computers). Instead, we have nc
which is very similar for testing things such as SMTP but doesn't really allow for remote shell connections. That being said, more and more SMTP is going to use encryption as well so the best tool to test is still sendmail
.
I solved the problem with this code:
using System.IO;
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")))
After trying every answer I could find here and online, I was still getting errors for some missing headers. When trying to compile pyRFR, I was getting errors about stdexcept
not being found, which apparently was not installed in /usr/include
with the other headers. However, I found where it was hiding in Mojave and added this to the end of my ~/.bash_profile
file:
export CPATH=/Library/Developer/CommandLineTools/usr/include/c++/v1
Having done that, I can now compile pyRFR and other C/C++ programs. According to echo | gcc -E -Wp,-v -
, gcc was looking in the old location for these headers (without the /c++/v1
), but not the new location, so adding that to CFLAGS fixed it.
Edit depending on comment
In some versions - as suggested in comments - the exception thrown may be different.
Thus the solution below is slightly modified
Intent launchIntent = null;
try{
launchIntent = getPackageManager().getLaunchIntentForPackage("applicationId");
} catch (Exception ignored) {}
if(launchIntent == null){
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
} else {
startActivity(launchIntent);
}
Original Answer
Although answered well, there is a pretty simple implementation that handles if the app is not installed. I do it like this
try{
startActivity(getPackageManager().getLaunchIntentForPackage("applicationId"));
} catch (PackageManager.NameNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("https://play.google.com/store/apps/details?id=" + "applicationId")));
}
Replace "applicationId" with the package that you want to open such as com.google.maps, etc.
$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName
OR
$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName
Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight
public class MainActivity extends AppCompatActivity {
Button button;
Boolean light=true;
CameraDevice cameraDevice;
private CameraManager cameraManager;
private CameraCharacteristics cameraCharacteristics;
String cameraId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
cameraManager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = cameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(light){
try {
cameraManager.setTorchMode(cameraId,true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
light=false;}
else {
try {
cameraManager.setTorchMode(cameraId,false);
} catch (CameraAccessException e) {
e.printStackTrace();
}
light=true;
}
}
});
}
}
A convenient option is to use javax.xml.bind.JAXB:
StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();
The [reverse] process (unmarshal) would be:
Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);
No need to deal with checked exceptions in this approach.
I think, It is the simplest way to find MAX
and second MAX
Salary.You may try this way.
SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.
SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary
I think cffi for python can be an option.
The goal is to call C code from Python. You should be able to do so without learning a 3rd language: every alternative requires you to learn their own language (Cython, SWIG) or API (ctypes). So we tried to assume that you know Python and C and minimize the extra bits of API that you need to learn.
I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:
private DataTable GetDataTableFromDGV(DataGridView dgv) {
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns) {
if (column.Visible) {
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows) {
for (int i = 0; i < row.Cells.Count; i++) {
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
One option using your data (for future reference, use set.seed()
to make examples using sample
reproducible):
DF <- data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
colnames(DF)[apply(DF,1,which.max)]
[1] "V3" "V1" "V2"
A faster solution than using apply
might be max.col
:
colnames(DF)[max.col(DF,ties.method="first")]
#[1] "V3" "V1" "V2"
...where ties.method
can be any of "random"
"first"
or "last"
This of course causes issues if you happen to have two columns which are equal to the maximum. I'm not sure what you want to do in that instance as you will have more than one result for some rows. E.g.:
DF <- data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(7,6,4))
apply(DF,1,function(x) which(x==max(x)))
[[1]]
V2 V3
2 3
[[2]]
V1
1
[[3]]
V2
2
If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf
or /etc/security/limits.conf
file (where the file is located depends on your specific Linux distribution).
For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf
file.
* hard nofile 10000
Then logout and relogin to your system and you should be able to do:
ulimit -n 10000
without a permission error.