'SET' is forgotten
ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
For only one line, you need
...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" />
...
Yes, you want to use tee
:
tee - read from standard input and write to standard output and files
Just pipe your command to tee and pass the file as an argument, like so:
exec 1 | tee ${LOG_FILE}
exec 2 | tee ${LOG_FILE}
This both prints the output to the STDOUT and writes the same output to a log file. See man tee
for more information.
Note that this won't write stderr to the log file, so if you want to combine the two streams then use:
exec 1 2>&1 | tee ${LOG_FILE}
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:
class Foo {
protected function stuff() {
// secret stuff, you want to test
}
}
class SubFoo extends Foo {
public function exposedStuff() {
return $this->stuff();
}
}
Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.
I also found another way of doing this that gives proper 'x10(superscript)5' notation on the axes. I'm posting it here in the hope it might be useful to some. I got the code from here so I claim no credit for it, that rightly goes to Brian Diggs.
fancy_scientific <- function(l) {
# turn in to character string in scientific notation
l <- format(l, scientific = TRUE)
# quote the part before the exponent to keep all the digits
l <- gsub("^(.*)e", "'\\1'e", l)
# turn the 'e+' into plotmath format
l <- gsub("e", "%*%10^", l)
# return this as an expression
parse(text=l)
}
Which you can then use as
ggplot(data=df, aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=fancy_scientific)
To write inline styling use:
<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>
Inline styling serves a purpose however, it is not recommended in most situations.
The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.
if you have the file structure:
index.html
>>/css/
>>/css/styles.css
Then in your HTML document between <head>
and </head>
write:
<link href="css/styles.css" rel="stylesheet" />
Then, change your div structure to be:
<div id="someidname" class="someclassname">
asdfashdjkfhaskjdf
</div>
In css, you can reference your div from the ID or the CLASS.
To do so write:
.someclassname { height: 100px; }
OR
#someidname { height: 100px; }
Note that if you do both, the one that comes further down the file structure will be the one that actually works.
For example... If you have:
.someclassname { height: 100px; }
.someclassname { height: 150px; }
Then in this situation the height will be 150px.
EDIT:
To answer your secondary question from your edit, probably need overflow: hidden;
or overflow: visible;
. You could also do this:
<div class="span12">
<div style="height:100px;">
asdfashdjkfhaskjdf
</div>
</div>
This replaces the last comma with a newline:
ls -1 | tr '\n' ',' | sed 's/,$/\n/'
ls -m
includes newlines at the screen-width character (80th for example).
Mostly Bash (only ls
is external):
saveIFS=$IFS; IFS=$'\n'
files=($(ls -1))
IFS=,
list=${files[*]}
IFS=$saveIFS
Using readarray
(aka mapfile
) in Bash 4:
readarray -t files < <(ls -1)
saveIFS=$IFS
IFS=,
list=${files[*]}
IFS=$saveIFS
Thanks to gniourf_gniourf for the suggestions.
There is a better way to do this. Use the concat Method. Example
declare a global variable. this works good on angular 10, just pass it to Vanilla JavaScript. Example:
HTML
<input id="edValue" type="text" onKeyPress="edValueKeyPress($event)"><br>
<span id="lblValue">The text box contains: </span>
CODE
emptyString = ''
edValueKeyPress ($event){
this.emptyString = this.emptyString.concat($event.key);
console.log(this.emptyString);
}
Try to remove %
chars as below
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
Try this.(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);
I know I am a little late to the party, but I've used this trick a couple of times (and I know it's a bit unusual):
I create an generic interface InfoRunnable<T>
with one method:
public T run(Object... args);
And if I need to do something before passing it to the constructor I just do this:
super(new InfoRunnable<ThingToPass>() {
public ThingToPass run(Object... args) {
/* do your things here */
}
}.run(/* args here */));
pyspellchecker
is the one of the best solutions for this problem. pyspellchecker
library is based on Peter Norvig’s blog post.
It uses a Levenshtein Distance algorithm to find permutations within an edit distance of 2 from the original word.
There are two ways to install this library. The official document highly recommends using the pipev package.
pip
pip install pyspellchecker
git clone https://github.com/barrust/pyspellchecker.git
cd pyspellchecker
python setup.py install
the following code is the example provided from the documentation
from spellchecker import SpellChecker
spell = SpellChecker()
# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])
for word in misspelled:
# Get the one `most likely` answer
print(spell.correction(word))
# Get a list of `likely` options
print(spell.candidates(word))
Search (Ctrl+F) your harddrive(s) for: SDK Manager.exe or adb.exe
What about this?
git stash save stashname
git stash apply stash^{/stashname}
this.WindowState = FormWindowState.Minimized;
You should name your list cars
instead of car
, so that its name matches its content.
Then you can simply say cars.get(0).getPrice()
. And if your Car
class doesn't have this method yet, you need to create it.
Warning! SQL Server 14 Express, SQL Server Management Studio, and SQL 2014 LocalDB are separate downloads, make sure you actually installed SQL Server and not just the Management Studio! SQL Server 14 express with LocalDB download link
Youtube video about entire process.
Writeup with pictures about installing SQL Server
How to select a local server:
When you are asked to connect to a 'database server' right when you open up SQL Server Management Studio do this:
1) Make sure you have Server Type: Database
2) Make sure you have Authentication: Windows Authentication (no username & password)
3) For the server name field look to the right and select the drop down arrow, click 'browse for more'
4) New window pops up 'Browse for Servers', make sure to pick 'Local Servers' tab and under 'Database Engine' you will have the local server you set up during installation of SQL Server 14
How do I create a local database inside of Microsoft SQL Server 2014?
1) After you have connected to a server, bring up the Object Explorer toolbar under 'View' (Should open by default)
2) Now simply right click on 'Databases' and then 'Create new Database' to be taken through the database creation tools!
Performance of Split vs RegExp
var i = 0;_x000D_
_x000D_
var split_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
"1234,453,123,324".split(",").length -1;_x000D_
i++;_x000D_
}_x000D_
var split_end = new Date().getTime();_x000D_
var split_time = split_end - split_start;_x000D_
_x000D_
_x000D_
i= 0;_x000D_
var reg_start = new Date().getTime();_x000D_
while (i < 30000) {_x000D_
("1234,453,123,324".match(/,/g) || []).length;_x000D_
i++;_x000D_
}_x000D_
var reg_end = new Date().getTime();_x000D_
var reg_time = reg_end - reg_start;_x000D_
_x000D_
alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");
_x000D_
Using the momentjs library, this can be achieved with the startOf()
and endOf()
methods on the moment's current date object, passing the string 'day'
as arguments:
Local GMT:
var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today
var start = moment.utc().startOf('day');
var end = moment.utc().endOf('day');
If you want to call the incremented number directly in a function, this solution works bettter:
Function inc(ByRef data As Integer)
data = data + 1
inc = data
End Function
for example:
Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))
If the function inc()
returns no value, the above line will generate an error.
add the -s
(silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body
curl -vs google.com 2>&1 | less
Edited answer: IE understands just screen and print as import media. All other CSS supplied along with the import statement causes IE8 to ignore the import statement. Geco browser like safari or mozilla didn't have this problem.
If you're still having trouble even after configuring your package.json according to the documentation (if you've opted to use package.json to track rather than separate config files):
"rules": {
"no-console": "off"
},
And it still isn't working for you, don't forget you need to go back to the command line and do npm install again. :)
autopep8 -i script.py
Use autopep8
autopep8
automagically formats Python code to conform to the PEP 8
nullstyle
guide. It uses the pep8
utility to determine what parts of the
nullcode
needs to be formatted. autopep8
is capable of fixing most of the
nullformatting
issues that can be reported by pep8
.
pip install autopep8
autopep8 script.py # print only
autopep8 -i script.py # write file
some of these ans are now out of date, so im answering,
FusedLocationProviderClient fusedLocationProviderClient; //set global variable
Location currentLocation;//set global var
private boolean mLocationPermissionGranted; //set global var
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext()); //write this oncreate
fetchLastLocation(); // call the funct for current location
//here is the function
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{
Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}else {
mLocationPermissionGranted=true;
}
Task<Location> task= fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
currentLocation =location;
Toast.makeText(getContext(), currentLocation.getLatitude()+"" +
" "+currentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
//if you want to show in google maps
SupportMapFragment supportMapFragment =(SupportMapFragment)
getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(MapsFragment.this);
}
}
});
}
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
As you comment in your question, awk
is really the way to go. To use cut
is possible together with tr -s
to squeeze spaces, as kev's answer shows.
Let me however go through all the possible combinations for future readers. Explanations are at the Test section.
tr -s ' ' < file | cut -d' ' -f4
awk '{print $4}' file
while read -r _ _ _ myfield _
do
echo "forth field: $myfield"
done < file
sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' file
Given this file, let's test the commands:
$ cat a
this is line 1 more text
this is line 2 more text
this is line 3 more text
this is line 4 more text
$ cut -d' ' -f4 a
is
# it does not show what we want!
$ tr -s ' ' < a | cut -d' ' -f4
1
2 # this makes it!
3
4
$
$ awk '{print $4}' a
1
2
3
4
This reads the fields sequentially. By using _
we indicate that this is a throwaway variable as a "junk variable" to ignore these fields. This way, we store $myfield
as the 4th field in the file, no matter the spaces in between them.
$ while read -r _ _ _ a _; do echo "4th field: $a"; done < a
4th field: 1
4th field: 2
4th field: 3
4th field: 4
This catches three groups of spaces and no spaces with ([^ ]*[ ]*){3}
. Then, it catches whatever coming until a space as the 4th field, that it is finally printed with \1
.
$ sed -r 's/^([^ ]*[ ]*){3}([^ ]*).*/\2/' a
1
2
3
4
(Repeating here my answer elsewhere.)
In theory, linux (the kernel underlying android) has mac80211_hwsim driver, which simulates WiFi. It can be used to set up several WiFi devices (an acces point, and another WiFi device, and so on), which would make up a WiFi network.
It's useful for testing WiFi programs under linux. Possibly, even under user-mode linux or other isolated virtual "boxes" with linux.
In theory, this driver could be used for tests in the android systems where you don't have a real WiFi device (or don't want to use it), and also in some kind of android emulators. Perhaps, one can manage to use this driver in android-x86, or--for testing--in android-x86 run in VirtualBox.
If you are using the tidyverse, you can use
as_data_frame(table(myvector))
to get a tibble (i.e. a data frame with some minor variations from the base class)
You can create a config class witch static properties
class Config
{
static $dbHost = 'localhost';
static $dbUsername = 'user';
static $dbPassword = 'pass';
}
then you can simple use it:
Config::$dbHost
Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.
Why?
For example you have 2 data source in your project. And you can choose witch of them is enabled.
Somewhere in config file you choose:
$dataSource = 'mysql' // or 'json'
When you change source whole app shoud switch to new data source, work fine and dont need change in code.
Example:
Config:
class Config
{
// ....
static $dataSource = 'mysql';
/ .....
}
Singleton class:
class AppConfig
{
private static $instance;
private $dataSource;
private function __construct()
{
$this->init();
}
private function init()
{
switch (Config::$dataSource)
{
case 'mysql':
$this->dataSource = new StorageMysql();
break;
case 'json':
$this->dataSource = new StorageJson();
break;
default:
$this->dataSource = new StorageMysql();
}
}
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getDataSource()
{
return $this->dataSource;
}
}
... and somewhere in your code (eg. in some service class):
$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection
We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.
pip install -r requirements.txt
and in the requirements.txt file you put your modules in a list, with one item per line.
Django=1.3.1
South>=0.7
django-debug-toolbar
Consider TextArea
People finding this via Google and looking for a better way to manage the display of their snippets should also consider <textarea>
which gives a lot of control over width/height, scrolling etc. Noting that @vsync mentioned the deprecated tag <xmp>
, I find <textarea readonly>
is an excellent substitute for displaying HTML without the need to escape anything inside it (except where </textarea>
might appear within).
For example, to display a single line with controlled line wrapping, consider <textarea rows=1 cols=100 readonly>
your html or etc with any characters including tabs and CrLf's </textarea>
.
<textarea rows=5 cols=100 readonly>Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</textarea>
_x000D_
To compare all...
<h2>Compared: TEXTAREA, XMP, PRE, SAMP, CODE</h2>_x000D_
<p>Note that CSS can be used to override default fixed space fonts in each or all these.</p>_x000D_
_x000D_
_x000D_
<textarea rows=5 cols=100 readonly>TEXTAREA: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed natively</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u></textarea>_x000D_
_x000D_
<xmp>XMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>displayed natively</b>._x000D_
However, note that & (&) will not act as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</xmp>_x000D_
_x000D_
<pre>PRE: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</pre>_x000D_
_x000D_
<samp>SAMP: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</samp>_x000D_
_x000D_
<code>CODE: Example text with Newlines,_x000D_
tabs & space,_x000D_
html tags etc <b>are interpreted, not displayed</b>._x000D_
However, note that & still acts as an escape char.._x000D_
Eg: <u>(text)</u>_x000D_
</code>
_x000D_
Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.
let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
formelem.required = true;
});
If you wish to make all input, textarea, and select elements required.
if you want to hold the arguments from Terminal, try the following code:
A = ARGV[0].to_i
B = ARGV[1].to_i
puts "#{A} + #{B} = #{A + B}"
You can use find with a Predicate as follows:
list.Find(x => x.Id == IdToFind);
This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).
I was able to fully automate it with the following command:
echo pass | ssh -tt user@server "sudo script"
Advantages:
Regarding security: as Kurt said, running this command will show your password on your local bash history, and it's better to save the password in a different file or save the all command in a .sh file and execute it. NOTE: The file need to have the correct permissions so that only the allowed users can access it.
There are a lot of answers here using mutt or mailx or people saying mail doesn't support "-a"
First, Ubuntu 14.0.4 mail from mailutils supports this:
mail -A filename -s "subject" [email protected]
Second, I found that by using the "man mail" command and searching for "attach"
I made a tool using Python with some bash to trigger a Jenkins build. Basically you have to collect these two values from post-commit when a commit hits the SVN server:
REPOS="$1"
REV="$2"
Then you use "svnlook dirs-changed $1 -r $2" to get the path which is has just committed. Then from that you can check which repository you want to build. Imagine you have hundred of thousand of projects. You can't check the whole repository, right?
You can check out my script from GitHub.
Don't forget to check whether the string is empty or null
. If we forget checking null
or empty then we would get NullPointerException
or StringIndexOutOfBoundException
if a given String is null or empty.
public class StartWithUpperCase{
public static void main(String[] args){
String str1 = ""; //StringIndexOfBoundException if
//empty checking not handled
String str2 = null; //NullPointerException if
//null checking is not handled.
String str3 = "Starts with upper case";
String str4 = "starts with lower case";
System.out.println(startWithUpperCase(str1)); //false
System.out.println(startWithUpperCase(str2)); //false
System.out.println(startWithUpperCase(str3)); //true
System.out.println(startWithUpperCase(str4)); //false
}
public static boolean startWithUpperCase(String givenString){
if(null == givenString || givenString.isEmpty() ) return false;
else return (Character.isUpperCase( givenString.codePointAt(0) ) );
}
}
Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.
PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS
vLine VARCHAR2(30000);
vFile UTL_FILE.file_type;
vExists boolean;
vLength number;
vBlockSize number;
BEGIN
UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);
FETCH p_Input INTO vLine;
IF p_input%ROWCOUNT > 0
THEN
IF vExists THEN
vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
ELSE
--even if the append flag is passed if the file doesn't exist open it with W.
vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
END IF;
--GET HANDLE TO FILE
IF p_Header IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Header);
END IF;
UTL_FILE.PUT_LINE(vFile, vLine);
DBMS_OUTPUT.PUT_LINE('Record count > 0');
--LOOP THROUGH CURSOR VAR
LOOP
FETCH p_Input INTO vLine;
EXIT WHEN p_Input%NOTFOUND;
UTL_FILE.PUT_LINE(vFile, vLine);
END LOOP;
IF p_Footer IS NOT NULL THEN
UTL_FILE.PUT_LINE(vFile, p_Footer);
END IF;
CLOSE p_Input;
UTL_FILE.FCLOSE(vFile);
ELSE
DBMS_OUTPUT.PUT_LINE('Record count = 0');
END IF;
EXCEPTION
WHEN UTL_FILE.INVALID_PATH THEN
DBMS_OUTPUT.PUT_LINE ('invalid_path');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_MODE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_mode');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_FILEHANDLE THEN
DBMS_OUTPUT.PUT_LINE ('invalid_filehandle');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INVALID_OPERATION THEN
DBMS_OUTPUT.PUT_LINE ('invalid_operation');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.READ_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('read_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.WRITE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('write_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN UTL_FILE.INTERNAL_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('internal_error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('other write error');
DBMS_OUTPUT.PUT_LINE(SQLERRM);
RAISE;
END;
Just use DataRow.IsNull. It has overrides accepting a column index, a column name, or a DataColumn object as parameters.
Example using the column index:
if (table.rows[0].IsNull(0))
{
//Whatever I want to do
}
And although the function is called IsNull
it really compares with DbNull
(which is exactly what you need).
What if I want to check for DbNull but I don't have a DataRow? Use Convert.IsDBNull.
To run multiple commands just add &&
between two commands like this: command1 && command2
And if you want to run them in two different terminals then you do it like this:
gnome-terminal -e "command1" && gnome-terminal -e "command2"
This will open 2 terminals with command1
and command2
executing in them.
Hope this helps you.
Answer is adding this 2 lines of code to Global.asax.cs Application_Start method
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.All;
Reference: Handling Circular Object References
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.You can use reset_index
to turn the index back into a column:
monthly_mean.reset_index().plot(x='index', y='A')
If you are moving branches to a new repo from an old one and do NOT have all the old repo branches local, you will need to track them first.
for remote in `git branch -r | grep -v '\->'`; do git branch --track $remote; done
Then add your new remote repo:
git remote add bb <path-to-new-repo>
Then you can push all using this command:
git push -u bb --all
Or you can configure the repo using the git config commands noted in the other responses here if you are not doing this one time or are only looking to move local branches.
The important point, the other responses only push all LOCAL branches. If the branches only exist on an alternate REMOTE repository they will not move without tracking them first. The for loop presented here will help with that.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
UseEnvironment.NewLine
instead of vbcrlf
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
Try
import sys
print(sys.version)
This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
If you type:
git status
Git will tell you what is staged, etc., including instructions on how to unstage:
use "git reset HEAD <file>..." to unstage
I find Git does a pretty good job of nudging me to do the right thing in situations like this.
Note: Recent Git versions (1.8.4.x) have changed this message:
(use "git rm --cached <file>..." to unstage)
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
>>> nums = [1, 2, 3, 4, 5]
>>> min(map((lambda t: ((float(t[0])/t[1]), t)), ((x, y) for x in nums for y in nums)))[1]
(1, 5)
You'll have to create a function for this. I don't think there is any built-in function for that purpose. All PHP arrays are associative by default. So, if you are unsure about their keys, here is the code:
<?php
$given_array = array('Monday' => 'boring',
'Friday' => 'yay',
'boring',
'Sunday' => 'fun',
7 => 'boring',
'Saturday' => 'yay fun',
'Wednesday' => 'boring',
'my life' => 'boring');
$repeating_value = "boring";
function array_value_positions($array, $value){
$index = 0;
$value_array = array();
foreach($array as $v){
if($value == $v){
$value_array[$index] = $value;
}
$index++;
}
return $value_array;
}
$value_array = array_value_positions($given_array, $repeating_value);
$result = "The value '$value_array[0]' was found at these indices in the given array: ";
$key_string = implode(', ',array_keys($value_array));
echo $result . $key_string . "\n";//Output: The value 'boring' was found at these indices in the given array: 0, 2, 4, 6, 7
I can show you with an example:
function fullName(first, last) {_x000D_
let fullName = first + " " + last;_x000D_
return fullName;_x000D_
}_x000D_
_x000D_
function fullNameStringInterpolation(first, last) {_x000D_
let fullName = `${first} ${last}`;_x000D_
return fullName;_x000D_
}_x000D_
_x000D_
console.log('Old School: ' + fullName('Carlos', 'Gutierrez'));_x000D_
_x000D_
console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));
_x000D_
This simple in below solution worked for me. http://forums.codeblocks.org/index.php?topic=17336.0
I had a similar problem. Please note I'm a total n00b in C++ and IDE's but heres what I did (after some research) So of course I downloaded the version that came with the compiler and it didn't work. Heres what I did: 1) go to settings in the upper part 2) click compiler 3) choose reset to defaults.
Hopefully this works
Please make sure to Log In to Travis first. The rebuild button doesn't appear until you're logged in. I know this is obvious, but someone just tripped on it as well ;-)
In debian/ubuntu, you'll need to edit the /etc/init.d/mongodb script. Really, this file should be pulling the settings from /etc/mongodb.conf but it doesn't seem to pull the default directory (probably a bug)
This is a bit of a hack, but adding these to the script made it start correctly:
add:
DBDIR=/database/mongodb
change:
DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --config $CONF run"}
to:
DAEMON_OPTS=${DAEMON_OPTS:-"--unixSocketPrefix=$RUNDIR --dbpath $DBDIR --config $CONF run"}
Base URL should be absolute, including the protocol:
$config['base_url'] = "http://somesite.com/somedir/";
If using the URL helper, then base_url()
will output the above string.
Passing arguments to base_url()
or site_url()
will result in the following (assuming $config['index_page'] = "index.php";
:
echo base_url('assets/stylesheet.css'); // http://somesite.com/somedir/assets/stylesheet.css
echo site_url('mycontroller/mymethod'); // http://somesite.com/somedir/index.php/mycontroller/mymethod
I had the same issue. Please follow these steps:
System.Data.SQLite.Core
package by
SQLite Development Team
from NuGet
.build
folder inside packages
folderBelow ONLINE tool:
http://www.javadecompilers.com/apk
it do ALL by one click: decompiled .java files + resources + xml (in one .zip file) with very good decompiler (jadx return java code in places/functions where other compiles return comments inside function like "unable to decompile" or some android assembler/machine code)
You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.
If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-
First copy the table
CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;
Then drop columns that you want to be after the column you will insert
ALTER TABLE my_tab DROP COLUMN three;
Now add the new column (two in this example) and the ones you removed.
ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));
Lastly add back the data for the re-created columns
UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);
Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?
Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array
and Arrays
classes in particular) have no such method.
This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.
If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:
The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;
The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;
If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.
An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.
If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.
If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:
public static int indexOfIntArray(int[] array, int key) {
int returnvalue = -1;
for (int i = 0; i < array.length; ++i) {
if (key == array[i]) {
returnvalue = i;
break;
}
}
return returnvalue;
}
If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.
If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this
NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Use This for MAC users
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Using inline handlers is incompatible with Content Security Policy so the addEventListener
approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline
but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.
To populate the column during insert, use a DEFAULT
value:
CREATE TABLE users (
id serial not null,
firstname varchar(100),
middlename varchar(100),
lastname varchar(100),
email varchar(200),
timestamp timestamp default current_timestamp
)
Note that the value for that column can explicitly be overwritten by supplying a value in the INSERT
statement. If you want to prevent that you do need a trigger.
You also need a trigger if you need to update that column whenever the row is updated (as mentioned by E.J. Brennan)
Note that using reserved words for column names is usually not a good idea. You should find a different name than timestamp
The steps to remove the newline character in the perhaps most obvious way:
NAME
by using strlen()
, header string.h
. Note that strlen()
does not count the terminating \0
.size_t sl = strlen(NAME);
\0
character (empty string). In this case sl
would be 0
since strlen()
as I said above doesn´t count the \0
and stops at the first occurrence of it: if(sl == 0)
{
// Skip the newline replacement process.
}
'\n'
. If this is the case, replace \n
with a \0
. Note that index counts start at 0
so we will need to do NAME[sl - 1]
:if(NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
Note if you only pressed Enter at the fgets()
string request (the string content was only consisted of a newline character) the string in NAME
will be an empty string thereafter.
if
-statement by using the logic operator &&
:if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
size_t sl = strlen(NAME);
if(sl > 0 && NAME[sl - 1] == '\n')
{
NAME[sl - 1] = '\0';
}
If you rather like a function for use this technique by handling fgets
output strings in general without retyping each and every time, here is fgets_newline_kill
:
void fgets_newline_kill(char a[])
{
size_t sl = strlen(a);
if(sl > 0 && a[sl - 1] == '\n')
{
a[sl - 1] = '\0';
}
}
In your provided example, it would be:
printf("Enter your Name: ");
if (fgets(Name, sizeof Name, stdin) == NULL) {
fprintf(stderr, "Error reading Name.\n");
exit(1);
}
else {
fgets_newline_kill(NAME);
}
Note that this method does not work if the input string has embedded \0
s in it. If that would be the case strlen()
would only return the amount of characters until the first \0
. But this isn´t quite a common approach, since the most string-reading functions usually stop at the first \0
and take the string until that null character.
Aside from the question on its own. Try to avoid double negations that make your code unclearer: if (!(fgets(Name, sizeof Name, stdin) != NULL) {}
. You can simply do if (fgets(Name, sizeof Name, stdin) == NULL) {}
.
You can remove the BOM using:
//Create a character to compare BOM
char byteOrderMark = (char)65279;
if (sourceString.ToCharArray()[0].Equals(byteOrderMark))
{
targetString = sourceString.Remove(0, 1);
}
Compile constants can only be primitives and Strings:
15.28. Constant Expressions
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- Literals of primitive type and literals of type
String
- Casts to primitive types and casts to type
String
- [...] operators [...]
- Parenthesized expressions whose contained expression is a constant expression.
- Simple names that refer to constant variables.
- Qualified names of the form TypeName . Identifier that refer to constant variables.
Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3"
, therefore the array cannot be really constant if we look deeper.
Keep in mind that what you're getting in a POST on the server-side is a key-value pair. You have values, but where is your key? In this case, you'll want to set the name
attribute of the buttons so that there's a key by which to access the value.
Additionally, in keeping with conventions, you'll want to change the type
of these input
s (buttons) to submit
so that they post their values to the form properly.
Also, what is your onclick
doing?
It contains the allocated size, 10. The remaining indexes will contain the default value which is 0.
This can help too
td[style] {height: 50px !important;}
This will override any inline style
For Kotlin devs this is the version with comparing formatted strings approach:
val sdf = SimpleDateFormat("yyMMdd")
if (sdf.format(date1) == sdf.format(date2)) {
// same day
}
It's not the best way, but it's short and working.
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
Disclaimer: shapeless plug by package author. :)
The trotter package is different from most implementations in that it generates pseudo lists that don't actually contain permutations but rather describe mappings between permutations and respective positions in an ordering, making it possible to work with very large 'lists' of permutations, as shown in this demo which performs pretty instantaneous operations and look-ups in a pseudo-list 'containing' all the permutations of the letters in the alphabet, without using more memory or processing than a typical web page.
In any case, to generate a list of permutations, we can do the following.
import trotter
my_permutations = trotter.Permutations(3, [1, 2, 3])
print(my_permutations)
for p in my_permutations:
print(p)
Output:
A pseudo-list containing 6 3-permutations of [1, 2, 3]. [1, 2, 3] [1, 3, 2] [3, 1, 2] [3, 2, 1] [2, 3, 1] [2, 1, 3]
To setup GruntJS build here is the steps:
Make sure you have setup your package.json
or setup new one:
npm init
Install Grunt CLI as global:
npm install -g grunt-cli
Install Grunt in your local project:
npm install grunt --save-dev
Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:
npm install grunt-contrib-concat --save-dev
Now you need to setup your Gruntfile.js
which will describe your build process. For this sample I just combine two JS files file1.js
and file2.js
in the js
folder and generate app.js
:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
"options": { "separator": ";" },
"build": {
"src": ["js/file1.js", "js/file2.js"],
"dest": "js/app.js"
}
}
});
// Load required modules
grunt.loadNpmTasks('grunt-contrib-concat');
// Task definitions
grunt.registerTask('default', ['concat']);
};
Now you'll be ready to run your build process by following command:
grunt
I hope this give you an idea how to work with GruntJS build.
NOTE:
You can use grunt-init
for creating Gruntfile.js
if you want wizard-based creation instead of raw coding for step 5.
To do so, please follow these steps:
npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile
For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile
to %USERPROFILE%\.grunt-init\
. PowerShell will recognize the ~
correctly.
string.IsNullOrEmpty(str) - if you'd like to check string value has been provided
string.IsNullOrWhiteSpace(str) - basically this is already a sort of business logic implementation (i.e. why " " is bad, but something like "~~" is good).
My advice - do not mix business logic with technical checks. So, for example, string.IsNullOrEmpty is the best to use at the beginning of methods to check their input parameters.
If empName is a VARCHAR(50) column:
ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;
EDIT
Per the comments, you can also do this:
ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;
Note that the repetition of empName
is deliberate. You have to tell MySQL that you want to keep the same column name.
You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.
Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER
modifier. The above examples just have VARCHAR(50)
, but if you need other characteristics (such as NOT NULL
or a default value) you need to include those as well. Consult the docs on ALTER TABLE
for more info.
ping -n 11 -w 1000 127.0.0.1 > nul
Update
Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.
Use font-awesome stacked icons (alternative to bootstrap badges). Here are more examples: http://fontawesome.io/examples/
.no-border {_x000D_
border: none;_x000D_
background-color: white;_x000D_
outline: none;_x000D_
cursor: pointer;_x000D_
}_x000D_
.color-no-focus {_x000D_
color: grey;_x000D_
}_x000D_
.hover:hover {_x000D_
color: blue;_x000D_
}_x000D_
.white {_x000D_
color: white;_x000D_
}
_x000D_
<button type="button" (click)="doSomething()" _x000D_
class="hover color-no-focus no-border fa-stack fa-lg">_x000D_
<i class="color-focus fa fa-circle fa-stack-2x"></i>_x000D_
<span class="white fa-stack-1x">1</span>_x000D_
</button>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
_x000D_
give the td padding
At university we were taught 'best practice' was to use != when working for employers, though all the operators above have the same functionality.
I used lobos answer and it works. But I had a problem with the conversion of doubles because of the culture settings. So I added
return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);
I have a situation where I need a function from bash script which must not be executed before (e.g. by source
) and the problem with @$
is that myScript.sh is then run twice, it seems... So I've come up with the idea to get the function out with sed:
sed -n "/^func ()/,/^}/p" myScript.sh
And to execute it at the time I need it, I put it in a file and use source
:
sed -n "/^func ()/,/^}/p" myScript.sh > func.sh; source func.sh; rm func.sh
/^([a-zA-Z0-9 _-]+)$/
the above regex allows spaces in side a string and restrict special characters.It Only allows a-z, A-Z, 0-9, Space, Underscore and dash.
I used a combination of other peoples' answers to come up with this solution:
svn revert -R .
svn status --no-ignore | grep -E '(^\?)|(^\I)' | sed -e 's/^. *//' | sed -e 's/\(.*\)/"\1"/' | xargs rm -rf
svn update --force
Answers provided here as which camera api to use are wrong. Or better to say they are insufficient.
Some phones (for example Samsung Galaxy S6) could be above api level 21 but still may not support Camera2 api.
CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraId);
Integer level = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
return false;
}
CameraManager class in Camera2Api has a method to read camera characteristics. You should check if hardware wise device is supporting Camera2 Api or not.
But there are more issues to handle if you really want to make it work for a serious application: Like, auto-flash option may not work for some devices or battery level of the phone might create a RuntimeException on Camera or phone could return an invalid camera id and etc.
So best approach is to have a fallback mechanism as for some reason Camera2 fails to start you can try Camera1 and if this fails as well you can make a call to Android to open default Camera for you.
Also if you use SymPy you can use sympy.oo
>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan
etc.
There is some voodoo-talk in the answers around here among good ideas. Let's try to be a bit more real about what's happening and sum up the good stuff to check:
Basically, when that happens, it is a good idea to enable verbose mode for AVRDUDE, to get a better idea of what's happening. To do so, you only need to go in the preferences and check the verbose mode box. It's also a good idea to move away from the Arduino IDE, and launch a console to be more comfortable on reading AVRDUDE's output, that you'll get on clicking on the upload
button.
What's important here to put 3 or 4 -v
to the command call. Here's how looks like such AVRDUDE commands, with made up parameters as they are totally dependent on how the Arduino has been installed:
avrdude -v -v -v -v -C /path/to/avrdude.conf -patmega328 -P/dev/usbport -U flash:w:/path/to/firmware.hex
A good way to get the correct command line to use is to copy it from the verbose output of the Arduino IDE output log when verbosity has been enabled.
When you get avrdude: stk500_recv(): programmer is not responding
, it basically means that something wrong is happening, before the flashing actually begins.
Basically you have to check (from hardware to software, low level to high level):
Rx
and Tx
(usually pins 1
and 0
);1
and 0
pins of the Arduino are not being used by some shield or custom design (/!\
does not apply to the Leonardo as it has independent USB handling);FTDI
on older Duemilanove or ATmega16U2 on newer Arduino Unos);Usually the avrdude -v -v -v -v
can help a lot find at which stage it is failing. Whether it can't make a USB connection at all (cable failing, USB/UART, PCB…), or it is a bootloader problem.
Update: I tried turning the onboard ATmega and fitting it in the other direction. Now, I encounter no problems uploading, but nothing happens afterwards. The onboard LED also does not seem to be blinking.
I'm afraid that if you reversed the position of the ATmega, and then it does not work, the fact that you placed the power source on digital pins may have burnt your chip.
Have you tried just "TYPE1"? I suppose Spring uses reflection to determine the type of "type" anyway, so the fully qualified name is redundant. Spring generally doesn't subscribe to redundancy!
The package setuptools/distribute is listed in requirements.txt. Please remove the same.
I'm not a 100% sure, but won't
$(data)
produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.
EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)
$("img", data).attr ("src")
if you want to access the src-attribute. If your data is just text, it would probably work to do
$("img", $(data)).attr ("src")
Try adding the script element just before the /body tag like that
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>
<div id="divid">Next</div>
<script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>
you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.
To catch the names array, i use that:
$("input[name*='task']")
Maybe I'm missing something, but wouldn't this suffice:
if (view instanceof B) {
// this view is an instance of B
}
Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.
By convention, any method that exists via InterruptedException have to clear interrupt status flag.
If using the following HTML:
<button id="submit-button"></button>
Style can be applied through JS using the style object available on an HTMLElement.
To set height and width to 200px of the above example button, this would be the JS:
var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';
I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.
I changed color programmatically in this way :
var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);
as alertTitle, you can change other data by this way (next example is for titleDivider):
int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);
this is in C#, but in java it is the same.
Create a method and call it to close the JFrame, for example:
public void CloseJframe(){
super.dispose();
}
Yes. In the javascript code:
window.location.href = "http://new.website.com/that/you/want_to_go_to.html";
Perhaps you misunderstood the difference between &
and &&
, |
and ||
The purpose of the shortcut operators &&
and ||
is that the value of the first operand can determine the result and so the second operand doesn't need to be evaluated.
This is especially useful if the second operand would results in an error. e.g.
if (set == null || set.isEmpty())
// or
if (list != null && list.size() > 0)
However with XOR, you always have to evaluate the second operand to get the result so the only meaningful operation is ^
.
The way I would handle it is to add an event handler in my ViewModel. When the user was successfully logged in I would fire the event. In my View I would attach to this event and when it fired I would close the window.
Some times this trouble may appear if you open this db in another sql server (as example, you launch sql managment studio(SMS) and add this db), and forget stop this server. As result - you app try to connect with user already connected in this db under another server. To fix that, try stop this server by Config. dispatcher sql server.
My apologies about bad english. Kind regards, Ignat.
I'm using Bootstrap 4 and Dennis Puzak's solution does not work for me.
The next solution works for me
.form-control::placeholder { color: white;} /* Chrome, Firefox, Opera*/
:-ms-input-placeholder.form-control { color: white; } /* Internet Explorer*/
.form-control::-ms-input-placeholder { color: white; } /* Microsoft Edge*/
Before applying WORKDIR. Here the WORKDIR is at the wrong place and is not used wisely.
FROM microsoft/aspnetcore:2
COPY --from=build-env /publish /publish
WORKDIR /publish
ENTRYPOINT ["dotnet", "/publish/api.dll"]
We corrected the above code to put WORKDIR at the right location and optimised the following statements by removing /Publish
FROM microsoft/aspnetcore:2
WORKDIR /publish
COPY --from=build-env /publish .
ENTRYPOINT ["dotnet", "api.dll"]
So it acts like a cd
and sets the tone for the upcoming statements.
This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!
public int Sum(params int[] customerssalary)
{
int result = 0;
for(int i = 0; i < customerssalary.Length; i++)
{
result += customerssalary[i];
}
return result;
}
with this Sum
function, you can use this to calculate the average too...
public decimal Average(params int[] customerssalary)
{
int sum = Sum(customerssalary);
decimal result = (decimal)sum / customerssalary.Length;
return result;
}
the reason for using a decimal
type in the second function is because the division can easily return a non-integer result
Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.
After enabling Two Factor Authentication (2FA), you may see something like this when attempting to use git clone
, git fetch
, git pull
or git push
:
$ git push origin master
Username for 'https://github.com': your_user_name
Password for 'https://[email protected]':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/your_user_name/repo_name.git/'
From the GitHub Help documentation:
After 2FA is enabled you will need to enter a personal access token instead of a 2FA code and your GitHub password.
...
For example, when you access a repository using Git on the command line using commands like
git clone
,git fetch
,git pull
orgit push
with HTTPS URLs, you must provide your GitHub username and your personal access token when prompted for a username and password. The command line prompt won't specify that you should enter your personal access token when it asks for your password.
Related question: https://stackoverflow.com/a/21374369/101662
If you are using atomic, it means the thread will be safe and read-only. If you are using nonatomic, it means the multiple threads access the variable and is thread unsafe, but it is executed fast, done a read and write operations; this is a dynamic type.
ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.
In terms of how len()
actually works, this is its C implementation:
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
}
Py_ssize_t
is the maximum length that the object can have. PyObject_Size()
is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
And an exception is raised as a result. Otherwise, this code block will be executed:
return PyLong_FromSsize_t(res);
res
which is a C
integer, is converted into a Python int
(which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
...
[ValidateModel]
public HttpResponseMessage Post([FromBody]AnyModel model)
{
Javascript
$.ajax({
type: "POST",
url: "/api/xxxxx",
async: 'false',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
To check if the javascript in nonexistant.js
returned no error you have to add a variable inside http://fail.org/nonexistant.js
like var isExecuted = true;
and then check if it exists when the script tag is loaded.
However if you only want to check that the nonexistant.js
returned without a 404 (meaning it exists), you can try with a isLoaded
variable ...
var isExecuted = false;
var isLoaded = false;
script_tag.onload = script_tag.onreadystatechange = function() {
if(!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") {
// script successfully loaded
isLoaded = true;
if(isExecuted) // no error
}
}
This will cover both cases.
For kotlin, isDigitsOnly()
(Also for Java's TextUtils.isDigitsOnly()
) of String
always returns false it has a negative sign in front though the rest of the character is digit only. For example -
/** For kotlin*/
var str = "-123"
str.isDigitsOnly() //Result will be false
/** For Java */
String str = "-123"
TextUtils.isDigitsOnly(str) //Result will be also false
So I made a quick fix by this -
var isDigit=str.matches("-?\\d+(\\.\\d+)?".toRegex())
/** Result will be true for now*/
Your code isn't working, because the hidden attibute is not supported in versions of IE before v11
If you need to support IE before version 11, add a CSS style to hide when the hidden attribute is present:
*[hidden] { display: none; }
@DRapp is a genius. I never understood how he coded his SQL,so I tried coding it in my own understanding.
SELECT
f.username,
f.point,
f.avg_time
FROM
(
SELECT
userscores.username,
userscores.point,
userscores.avg_time
FROM
(
SELECT
users.username,
scores.point,
scores.avg_time
FROM
scores
JOIN users
ON scores.user_id = users.id
ORDER BY scores.point DESC
) userscores
ORDER BY
point DESC,
avg_time
) f
GROUP BY f.username
ORDER BY point DESC
It yields the same result by using GROUP BY instead of the user @variables.
Here is an example of showing the line number of where exception takes place.
import sys
try:
print(5/0)
except Exception as e:
print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
print('And the rest of program continues')
For me save_queries
option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
I guess you may have already found the answer, but if not (and for other developers), you can do it like this:
btnMybutton.getBackground().setAlpha(45);
Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)
A shorter syntax for SWIFT 3
func listFilesFromDocumentsFolder() -> [String]?
{
let fileMngr = FileManager.default;
// Full path to documents directory
let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path
// List all contents of directory and return as [String] OR nil if failed
return try? fileMngr.contentsOfDirectory(atPath:docs)
}
Usage example:
override func viewDidLoad()
{
print(listFilesFromDocumentsFolder())
}
Tested on xCode 8.2.3 for iPhone 7 with iOS 10.2 & iPad with iOS 9.3
What are you trying to accomplish? You can access characters in a string just like an array:
$s = 'abcd';
echo $s[0];
prints 'a'
In order to see the changes that have been staged already, you can pass the -–staged
option to git diff
(in pre-1.6 versions of Git, use –-cached
).
git diff --staged
git diff --cached
As you would like to get argument (United
) for which value is given (5
) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).
Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:
git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"
then
sudo apt-get install gawk
sudo yum install gawk
brew install hello
you can follow this link for more information.
maybe this method is not what you mean, but who knows it can help
const arg = process.argv.splice(2);
function printToCli(text){
console.log(text)
}
switch(arg[0]){
case "--run":
printToCli("how are you")
break;
default: console.log("use --run flag");
}
and run command node . --run
probuss-MacBook-Air:fb_v8 probus$ node . --run
how are you
probuss-MacBook-Air:fb_v8 probus$
and you can add more arg[0] , arg[1], arg[2] ... and more
for node . --run -myarg1 -myarg2
This requires jQuery to be installed as well, but works perfectly for a dev environment. It looks through each element to get the instances of the scopes then returns them labelled with there controller names. Its also removing any property start with a $ which is what angularjs generally uses for its configuration.
let controllers = (extensive = false) => {
let result = {};
$('*').each((i, e) => {
let scope = angular.element(e).scope();
if(Object.prototype.toString.call(scope) === '[object Object]' && e.hasAttribute('ng-controller')) {
let slimScope = {};
for(let key in scope) {
if(key.indexOf('$') !== 0 && key !== 'constructor' || extensive) {
slimScope[key] = scope[key];
}
}
result[$(e).attr('ng-controller')] = slimScope;
}
});
return result;
}
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know:
Here are the Brute-force iterative
method and Sieve of Eratosthenes
method to find prime numbers upto n. The performance of the second method is better than first in terms of time complexity
Brute-force iterative
function findPrime(n) {
var res = [2],
isNotPrime;
for (var i = 3; i < n; i++) {
isNotPrime = res.some(checkDivisorExist);
if ( !isNotPrime ) {
res.push(i);
}
}
function checkDivisorExist (j) {
return i % j === 0;
}
return res;
}
Sieve of Eratosthenes method
function seiveOfErasthones (n) {
var listOfNum =range(n),
i = 2;
// CHeck only until the square of the prime is less than number
while (i*i < n && i < n) {
listOfNum = filterMultiples(listOfNum, i);
i++;
}
return listOfNum;
function range (num) {
var res = [];
for (var i = 2; i <= num; i++) {
res.push(i);
}
return res;
}
function filterMultiples (list, x) {
return list.filter(function (item) {
// Include numbers smaller than x as they are already prime
return (item <= x) || (item > x && item % x !== 0);
});
}
}
If you have a large data frame and need to divide into a variable number of sub data frames rows, like for example each sub dataframe has a max of 4500 rows, this script could help:
max_rows = 4500
dataframes = []
while len(df) > max_rows:
top = df[:max_rows]
dataframes.append(top)
df = df[max_rows:]
else:
dataframes.append(df)
You could then save out these data frames:
for _, frame in enumerate(dataframes):
frame.to_csv(str(_)+'.csv', index=False)
Hope this helps someone!
Try using fake sendmail to send emails in a WAMP enviroment.
public Bitmap resizeBitmap(String photoPath, int targetW, int targetH) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true; //Deprecated API 21
return BitmapFactory.decodeFile(photoPath, bmOptions);
}
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"
Here is example of taking XML file from raw folder:
InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML
Then you can:
String sxml = readTextFile(XmlFileInputStream);
when:
public String readTextFile(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
irb(main):005:0> a = Date.parse("12/1/2010")
=> #<Date: 4911063/2,0,2299161>
irb(main):007:0> b = Date.parse("12/21/2010")
=> #<Date: 4911103/2,0,2299161>
irb(main):016:0> c = b.mjd - a.mjd
=> 20
This uses a Modified Julian Day Number.
From wikipedia:
The Julian date (JD) is the interval of time in days and fractions of a day since January 1, 4713 BC Greenwich noon, Julian proleptic calendar.
Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---
var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent(purl) + '&callback=?',
function (data) {
$('#viewer').html(data.contents);
});
Use cl scr
on the Sql* command line tool to clear all the matter on the screen.
Here's what I've done:
.resize {
width: 400px;
height: auto;
}
.resize {
width: 300px;
height: auto;
}
<img class="resize" src="example.jpg"/>
This will keep the image aspect ratio the same.
Or add styles inline:
<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>
You can call a stored procedure from another stored procedure by using the EXECUTE command.
Say your procedure is X. Then in X you can use
EXECUTE PROCEDURE Y () RETURNING_VALUES RESULT;"
In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.
Often a volatile boolean
field is used which the thread periodically checks and terminates when it is set to the corresponding value.
I would not use a boolean
to check whether the thread should terminate. If you use volatile
as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while
loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.
Certain blocking library methods support interruption.
Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:
public void run() {
try {
while (!interrupted()) {
// ...
}
} catch (InterruptedException consumed)
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
Source code adapted from Java Concurrency in Practice. Since the cancel()
method is public you can let another thread invoke this method as you wanted.
In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.
-Ed
I had this problem along with mismatch in ITERATOR_DEBUG_LEVEL. As a sunday-evening problem after all seemed ok and good to go, I was put out for some time. Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - at source file level, not project level - I noticed that in a Release configuration _DEBUG was specified instead of NDEBUG for this source file. Which was all the change needed to get rid of the problem.
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
Why don't you run TOP and use the options to sort by other metrics, other than PID? Like, highest used PID from the CPU/MEM?
top -o cpu <---sorts all processes by CPU Usage
I don't believe Windows (as opposed to .NET) provides a direct way to get that.
The only way I know of is to enumerate all the top level windows with EnumWindows()
and then find what process each belongs to GetWindowThreadProcessID()
. This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...
call chooseImage method like-
public void chooseImage(ImageView v)
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(imageReturnedIntent != null)
{
Uri selectedImage = imageReturnedIntent.getData();
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Bitmap datifoto = null;
temp.setImageBitmap(null);
Uri picUri = null;
picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
if(picUri !=null){
try {
datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri);
temp.setImageBitmap(datifoto);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (OutOfMemoryError e) {
Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
}
}
}
break;
}
}
else
{
//Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
}
}
this may work for you :
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
or if your comfort with jquery,
$(document).ready(function(){
// your code
});
$(document).ready()
fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).
as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout
function, before firing the function like below :
setTimeout(function(){
//your code here
}, 3000);
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/
I had the same problem. Using 'sudo python3 -m pip install selenium' may work.
You are close, but the parameter you pass to SecureStringToBSTR
must be a SecureString
. You appear to be passing the result of ConvertFrom-SecureString
, which is an encrypted standard string. So call ConvertTo-SecureString
on this before passing to SecureStringToBSTR
.
$SecurePassword = ConvertTo-SecureString $PlainPassword -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
From the standpoint of a method which receives a parameter, the difference between ref
and out
is that C# requires that methods must write to every out
parameter before returning, and must not do anything with such a parameter, other than passing it as an out
parameter or writing to it, until it has been either passed as an out
parameter to another method or written directly. Note that some other languages do not impose such requirements; a virtual or interface method which is declared in C# with an out
parameter may be overridden in another language which does not impose any special restrictions on such parameters.
From the standpoint of the caller, C# will in many circumstances assume when calling a method with an out
parameter will cause the passed variable to be written without having been read first. This assumption may not be correct when calling methods written in other languages. For example:
struct MyStruct
{
...
myStruct(IDictionary<int, MyStruct> d)
{
d.TryGetValue(23, out this);
}
}
If myDictionary
identifies an IDictionary<TKey,TValue>
implementation written in a language other than C#, even though MyStruct s = new MyStruct(myDictionary);
looks like an assignment, it could potentially leave s
unmodified.
Note that constructors written in VB.NET, unlike those in C#, make no assumptions about whether called methods will modify any out
parameters, and clear out all fields unconditionally. The odd behavior alluded to above won't occur with code written entirely in VB or entirely in C#, but can occur when code written in C# calls a method written in VB.NET.
To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.
To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.
try
{
// code causing TargetInvocationException
}
catch (Exception e)
{
if (e.InnerException != null)
{
string err = e.InnerException.Message;
}
}
If your dictionary is not nested, you could make a frozenset with the dict's items and use hash()
:
hash(frozenset(my_dict.items()))
This is much less computationally intensive than generating the JSON string or representation of the dictionary.
UPDATE: Please see the comments below, why this approach might not produce a stable result.
This solution is from Beginning Hibernate book:
Query<User> query = session.createQuery("from User u where u.scn=:scn", User.class);
query.setParameter("scn", scn);
User user = query.uniqueResult();
Small sample test.cmd
<# :
@echo off
powershell /nologo /noprofile /command ^
"&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
Currently, MySQL doesn't allow to set multiple values in one method call. So you have to have it under your own control. I usually create one prepared statement for predefined number of parameters, then I add as many batches as I need.
int paramSizeInClause = 10; // required to be greater than 0!
String color = "FF0000"; // red
String name = "Nathan";
Date now = new Date();
String[] ids = "15,21,45,48,77,145,158,321,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,358,1284,1587".split(",");
// Build sql query
StringBuilder sql = new StringBuilder();
sql.append("UPDATE book SET color=? update_by=?, update_date=? WHERE book_id in (");
// number of max params in IN clause can be modified
// to get most efficient combination of number of batches
// and number of parameters in each batch
for (int n = 0; n < paramSizeInClause; n++) {
sql.append("?,");
}
if (sql.length() > 0) {
sql.deleteCharAt(sql.lastIndexOf(","));
}
sql.append(")");
PreparedStatement pstm = null;
try {
pstm = connection.prepareStatement(sql.toString());
int totalIdsToProcess = ids.length;
int batchLoops = totalIdsToProcess / paramSizeInClause + (totalIdsToProcess % paramSizeInClause > 0 ? 1 : 0);
for (int l = 0; l < batchLoops; l++) {
int i = 1;
pstm.setString(i++, color);
pstm.setString(i++, name);
pstm.setTimestamp(i++, new Timestamp(now.getTime()));
for (int count = 0; count < paramSizeInClause; count++) {
int param = (l * paramSizeInClause + count);
if (param < totalIdsToProcess) {
pstm.setString(i++, ids[param]);
} else {
pstm.setNull(i++, Types.VARCHAR);
}
}
pstm.addBatch();
}
} catch (SQLException e) {
} finally {
//close statement(s)
}
If you don't like to set NULL when no more parameters left, you can modify code to build two queries and two prepared statements. First one is the same, but second statement for the remainder (modulus). In this particular example that would be one query for 10 params and one for 8 params. You will have to add 3 batches for the first query (first 30 params) then one batch for the second query (8 params).
Note that HasValue
will return true for an empty Guid
.
bool validGuid = SomeProperty.HasValue && SomeProperty != Guid.Empty;
Don't use String.prototype.toCamelCase() because String.prototypes are read-only, most of the js compilers will give you this warning.
Like me, those who know that the string will always contains only one space can use a simpler approach:
let name = 'test string';
let pieces = name.split(' ');
pieces = pieces.map((word, index) => word.charAt(0)[index===0 ? 'toLowerCase' :'toUpperCase']() + word.toLowerCase().slice(1));
return pieces.join('');
Have a good day. :)
If I want to exit a for-to loop, I just set the index beyond the limit:
For i = 1 To max
some code
if this(i) = 25 Then i = max + 1
some more code...
Next`
Poppa.
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
If you are using PHP 5.6, the command is:
sudo apt-get install php5.6-pgsql
Their names should help you:
android:gravity
sets the gravity of the contents (i.e. its subviews) of the View
it's used on. android:layout_gravity
sets the gravity of the View
or Layout
relative to its parent. And an example is here.
You can try deleting the Team Server credentials, most likely those will include some kind of port in the server column. Like https://wathever.visualstudio.com:443
Go to Windows/Preferences expand Team then Team Foundation Server go to Credentials and remove whichever is there.
The first allocates an object with automatic storage duration, which means it will be destructed automatically upon exit from the scope in which it is defined.
The second allocated an object with dynamic storage duration, which means it will not be destructed until you explicitly use delete
to do so.
The following simple test:
C++ Array vs Vector performance test explanation
contradicts the conclusions from "Comparison of assembly code generated for basic indexing, dereferencing, and increment operations on vectors and arrays/pointers."
There must be a difference between the arrays and vectors. The test says so... just try it, the code is there...
Some useful extensions:
extension String {
func substring(from: Int, to: Int) -> String {
let start = index(startIndex, offsetBy: from)
let end = index(start, offsetBy: to - from)
return String(self[start ..< end])
}
func substring(range: NSRange) -> String {
return substring(from: range.lowerBound, to: range.upperBound)
}
}
You can run these two commands:
# Revert changes to modified files.
git reset --hard
# Remove all untracked files and directories.
# '-f' is force, '-d' is remove directories.
git clean -fd
i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:
RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
to your .htaccess file
Till this date I also used to think that we need to create that /data/db folder for starting mongod command.
But recently I tried to start mongod with service command and it worked for me and there was no need to create /data/db directory.
service mongod start
As to check the status of mongod you can run the following command.
service mongod status
\d{1,2}[,.]\d{1,2}
\d means a digit, the {1,2} part means 1 or 2 of the previous character (\d in this case) and the [,.] part means either a comma or dot.
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
You need to use the reserve function to set an initial allocated size or do it in the initial constructor.
vector<CustomClass *> content(20000);
or
vector<CustomClass *> content;
...
content.reserve(20000);
When you reserve()
elements, the vector
will allocate enough space for (at least?) that many elements. The elements do not exist in the vector
, but the memory is ready to be used. This will then possibly speed up push_back()
because the memory is already allocated.
With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:
Check it out here.
Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.
I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.
UPDATE:
Some people are having problems with iOS 8.4, here is how to fix it.
I use the CONCATENATE
method to take the values of a column and wrap quotes around them with columns in between in order to quickly populate the WHERE IN ()
clause of a SQL statement.
I always just type =CONCATENATE("'",B2,"'",",")
and then select that and drag it down, which creates =CONCATENATE("'",B3,"'",",")
, =CONCATENATE("'",B4,"'",",")
, etc. then highlight that whole column, copy paste to a plain text editor and paste back if needed, thus stripping the row separation. It works, but again, just as a one time deal, this is not a good solution for someone who needs this all the time.
3 characters before and 4 characters after
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
Add step="0.01"
to the <input type="number" />
parameters:
<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />
Demo: http://jsfiddle.net/uzbjve2u/
But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.
Otherwise you could use a classic textbox, like described here.
You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:
import httplib2 as http
import json
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
uri = 'http://yourservice.com'
path = '/path/to/resource/'
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
# If you need authentication some example:
if auth:
h.add_credentials(auth.user, auth.password)
response, content = h.request(
target.geturl(),
method,
body,
headers)
# assume that content is a json reply
# parse content with the json module
data = json.loads(content)
You are plotting all your images on one axis. What you want ist to get a handle for each axis individually and plot your images there. Like so:
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.imshow(...)
ax2 = fig.add_subplot(2,2,2)
ax2.imshow(...)
ax3 = fig.add_subplot(2,2,3)
ax3.imshow(...)
ax4 = fig.add_subplot(2,2,4)
ax4.imshow(...)
For more info have a look here: http://matplotlib.org/examples/pylab_examples/subplots_demo.html
For complex layouts, you should consider using gridspec: http://matplotlib.org/users/gridspec.html
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
Example:
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log("height: " + rect.height);
}
UPDATE: Here is the same code written in 2020:
const elem = document.querySelector("#myDiv");
if(elem) {
const rect = elem.getBoundingClientRect();
console.log(`height: ${rect.height}`);
}
You can copy your div like this
$(".package").html($(".button").html())
alternative solution for this with using many infowindows: save prev opened infowindow in a variable and then close it when new window opened
var prev_infowindow =false;
...
base.attachInfo = function(marker, i){
var infowindow = new google.maps.InfoWindow({
content: 'yourmarkerinfocontent'
});
google.maps.event.addListener(marker, 'click', function(){
if( prev_infowindow ) {
prev_infowindow.close();
}
prev_infowindow = infowindow;
infowindow.open(base.map, marker);
});
}
I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df)
for displaying the DataFrame df
:
from IPython.core.display import display, HTML
def force_show_all(df):
with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
display(HTML(df.to_html()))
# ... now when you're ready to fully display df:
force_show_all(df)
As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.
You should probably use pymysql - Pure Python MySQL client instead.
It works with Python 3.x, and doesn't have any dependencies.
This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol.
Example:
import pymysql conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql') cur = conn.cursor() cur.execute("SELECT Host,User FROM user") for r in cur: print(r) cur.close() conn.close()
If none of the above works (Setting Main class, Clean and Build, deleting the cache) and you have a Maven project, try:
mvn clean install
on the command line.
DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.
This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.
For reference, these are very similar questions.
These seem to work the best for me. They also work with spaces, and don't re-add ignored files. I didn't see them listed on any of the other answers I saw.
adding:
svn st | grep ^? | sed 's/? //' | xargs svn add
removing:
svn st | grep ^! | sed 's/! //' | xargs svn rm
Edit: It's important to NOT use "add *" if you want to keep your ignored files, otherwise everything that was ignored will be re-added.