None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.
What did work was specifying the user name (mike-wise
)in the url like this:
git clone https://[email protected]/someuser/somerepo.git
Is it possible to use a
.netrc
file on Windows?
Yes: You must:
%HOME%
(pre-Git 2.0, no longer needed with Git 2.0+)_netrc
file in %HOME%
If you are using Windows 7/10, in a CMD
session, type:
setx HOME %USERPROFILE%
and the %HOME%
will be set to 'C:\Users\"username"
'.
Go that that folder (cd %HOME%
) and make a file called '_netrc
'
Note: Again, for Windows, you need a '_netrc
' file, not a '.netrc
' file.
Its content is quite standard (Replace the <examples>
with your values):
machine <hostname1>
login <login1>
password <password1>
machine <hostname2>
login <login2>
password <password2>
Luke mentions in the comments:
Using the latest version of msysgit on Windows 7, I did not need to set the
HOME
environment variable. The_netrc
file alone did the trick.
This is indeed what I mentioned in "Trying to “install
” github, .ssh
dir not there":
git-cmd.bat
included in msysgit does set the %HOME%
environment variable:
@if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%
??? believes in the comments that "it seems that it won't work for http protocol"
However, I answered that netrc
is used by curl
, and works for HTTP protocol, as shown in this example (look for 'netrc
' in the page): . Also used with HTTP protocol here: "_netrc
/.netrc
alternative to cURL
".
A common trap with with netrc
support on Windows is that git will bypass using it if an origin https url specifies a user name.
For example, if your .git/config
file contains:
[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = https://[email protected]/p/my-project/
Git will not resolve your credentials via _netrc
, to fix this remove your username, like so:
[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = https://code.google.com/p/my-project/
Alternative solution: With git version 1.7.9+ (January 2012): This answer from Mark Longair details the credential cache mechanism which also allows you to not store your password in plain text as shown below.
With Git 1.8.3 (April 2013):
You now can use an encrypted .netrc (with gpg
).
On Windows: %HOME%/_netrc
(_
, not '.
')
A new read-only credential helper (in
contrib/
) to interact with the.netrc/.authinfo
files has been added.
That script would allow you to use gpg-encrypted netrc files, avoiding the issue of having your credentials stored in a plain text file.
Files with the
.gpg
extension will be decrypted by GPG before parsing.
Multiple-f
arguments are OK. They are processed in order, and the first matching entry found is returned via the credential helper protocol.When no
-f
option is given,.authinfo.gpg
,.netrc.gpg
,.authinfo
, and.netrc
files in your home directory are used in this order.
To enable this credential helper:
git config credential.helper '$shortname -f AUTHFILE1 -f AUTHFILE2'
(Note that Git will prepend "
git-credential-
" to the helper name and look for it in the path.)
# and if you want lots of debugging info:
git config credential.helper '$shortname -f AUTHFILE -d'
#or to see the files opened and data found:
git config credential.helper '$shortname -f AUTHFILE -v'
See a full example at "Is there a way to skip password typing when using https:// github
"
With Git 2.18+ (June 2018), you now can customize the GPG program used to decrypt the encrypted .netrc
file.
See commit 786ef50, commit f07eeed (12 May 2018) by Luis Marsano (``).
(Merged by Junio C Hamano -- gitster
-- in commit 017b7c5, 30 May 2018)
git-credential-netrc
: acceptgpg
option
git-credential-netrc
was hardcoded to decrypt with 'gpg
' regardless of the gpg.program option.
This is a problem on distributions like Debian that call modern GnuPG something else, like 'gpg2
'
Nice explanation and example above. I found this (JSON.stringify() array bizarreness with Prototype.js) to complete the answer. Some sites implements its own toJSON with JSONFilters, so delete it.
if(window.Prototype) {
delete Object.prototype.toJSON;
delete Array.prototype.toJSON;
delete Hash.prototype.toJSON;
delete String.prototype.toJSON;
}
it works fine and the output of the test:
console.log(json);
Result:
"{"a":"test","b":["item","item2","item3"]}"
This script works!
#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
echo this script requires a 1 or 0 as first parameter.
else
echo "first parameter is $1"
xinput set-prop 12 "Device Enabled" $0
fi
But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:
#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
echo "first parameter is $1"
xinput set-prop 12 "Device Enabled" $0
else
echo this script requires a 1 or 0 as first parameter.
fi
The output is the same1:
$ ./tmp.sh
this script requires a 1 or 0 as first parameter.
$ ./tmp.sh 0
first parameter is 0
$ ./tmp.sh 1
first parameter is 1
$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.
[1] the second fails if the first argument is a string
When I need to keep the order, I use a list and a companion dict:
color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
color[i]
The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:
fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)):
fruitcolor[i][1]
for f, c in fruitcolor:
c
Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.
To indicate a missing file/resource and serve a 404 page, you need not redirect. In the same request you must generate the response with the status code set to 404 and the content of your 404 HTML page as response body. Here is the sample code to demonstrate this in Node.js.
var http = require('http'),
fs = require('fs'),
util = require('util'),
url = require('url');
var server = http.createServer(function(req, res) {
if(url.parse(req.url).pathname == '/') {
res.writeHead(200, {'content-type': 'text/html'});
var rs = fs.createReadStream('index.html');
util.pump(rs, res);
} else {
res.writeHead(404, {'content-type': 'text/html'});
var rs = fs.createReadStream('404.html');
util.pump(rs, res);
}
});
server.listen(8080);
The following approach is valid for all cases (difference between dates less than 24 hours and difference greater than 24 hours):
// Defining start and end variables
let start = moment('04/09/2013 15:00:00', 'DD/MM/YYYY hh:mm:ss');
let end = moment('04/09/2013 14:20:30', 'DD/MM/YYYY hh:mm:ss');
// Getting the difference: hours (h), minutes (m) and seconds (s)
let h = end.diff(start, 'hours');
let m = end.diff(start, 'minutes') - (60 * h);
let s = end.diff(start, 'seconds') - (60 * 60 * h) - (60 * m);
// Formating in hh:mm:ss (appends a left zero when num < 10)
let hh = ('0' + h).slice(-2);
let mm = ('0' + m).slice(-2);
let ss = ('0' + s).slice(-2);
console.log(`${hh}:${mm}:${ss}`); // 00:39:30
whether you want to keep the aspect ratio of a video or stretch it to fill its parent area, using the right layout manager can get the job done.
Keep the aspect ratio :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView
android:id="@+id/videoView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"/>
</LinearLayout>
!!! To fill in the field:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="@+id/videoViewRelative"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
The server may need read permission for your home directory and .htaccess therein
When you download a package with setup.py
open your Terminal (Mac,Linux) or Command Prompt (Windows). Using cd
and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is setup.py
:
iMac:~ user $ cd path/pakagefolderwithsetupfile/
Press enter, you should see something like this:
iMac:pakagefolderwithsetupfile user$
Then type after this python setup.py install
:
iMac:pakagefolderwithsetupfile user$ python setup.py install
Press enter
. Done!
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
To filter for specific file extensions:
wget -A pdf,jpg -m -p -E -k -K -np http://site/path/
Or, if you prefer long option names:
wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/
This will mirror the site, but the files without jpg
or pdf
extension will be automatically removed.
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important
directive! But sometimes it's the only way to override the inline style
attribute. So it's a best practice trying to avoid both.
From the documentation:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
<script type="text/javascript" >
function aa()
{
var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
var ObjUl = $('<ul></ul>');
for (i = 0; i < YourArray.length; i++)
{
var Objli = $('<li></li>');
var Obja = $('<a></a>');
ObjUl.addClass("ui-menu-item");
ObjUl.attr("role", "menuitem");
Obja.addClass("ui-all");
Obja.attr("tabindex", "-1");
Obja.text(YourArray[i]);
Objli.append(Obja);
ObjUl.append(Objli);
}
$('.DivSai').append(ObjUl);
}
</script>
</head>
<body onload="aa()">
<form id="form1" runat="server">
<div class="DivSai" >
</div>
</form>
</body>
function parseIt(){
return new Promise(function(res){
try{
var fs = require('fs');
const dirPath = 'K:\\merge-xml-junit\\xml-results\\master.json';
fs.readFile(dirPath,'utf8',function(err,data){
if(err) throw err;
res(data);
})}
catch(err){
res(err);
}
});
}
async function test(){
jsonData = await parseIt();
var parsedJSON = JSON.parse(jsonData);
var testSuite = parsedJSON['testsuites']['testsuite'];
console.log(testSuite);
}
test();
Many problems for which no efficient algorithm to find an optimal solution is known have heuristic approaches that yield near-optimal results very quickly.
There are some overlaps: "genetic algorithms" is an accepted term, but strictly speaking, those are heuristics, not algorithms.
You can encode Rule 110 in CSS3, so it's Turing-complete so long as you consider an appropriate accompanying HTML file and user interactions to be part of the “execution” of CSS. A pretty good implementation is available, and another implementation is included here:
body {_x000D_
-webkit-animation: bugfix infinite 1s;_x000D_
margin: 0.5em 1em;_x000D_
}_x000D_
@-webkit-keyframes bugfix { from { padding: 0; } to { padding: 0; } }_x000D_
_x000D_
/*_x000D_
* 111 110 101 100 011 010 001 000_x000D_
* 0 1 1 0 1 1 1 0_x000D_
*/_x000D_
_x000D_
body > input {_x000D_
-webkit-appearance: none;_x000D_
display: block;_x000D_
float: left;_x000D_
border-right: 1px solid #ddd;_x000D_
border-bottom: 1px solid #ddd;_x000D_
padding: 0px 3px;_x000D_
margin: 0;_x000D_
font-family: Consolas, "Courier New", monospace;_x000D_
font-size: 7pt;_x000D_
}_x000D_
body > input::before {_x000D_
content: "0";_x000D_
}_x000D_
_x000D_
p {_x000D_
font-family: Verdana, sans-serif;_x000D_
font-size: 9pt;_x000D_
margin-bottom: 0.5em;_x000D_
}_x000D_
_x000D_
body > input:nth-of-type(-n+30) { border-top: 1px solid #ddd; }_x000D_
body > input:nth-of-type(30n+1) { border-left: 1px solid #ddd; clear: left; }_x000D_
_x000D_
body > input::before { content: "0"; }_x000D_
_x000D_
body > input:checked::before { content: "1"; }_x000D_
body > input:checked { background: #afa !important; }_x000D_
_x000D_
_x000D_
input:not(:checked) +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input::before {_x000D_
content: "1";_x000D_
}_x000D_
input:not(:checked) +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input {_x000D_
background: #fa0;_x000D_
}_x000D_
_x000D_
_x000D_
input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input::before {_x000D_
content: "1";_x000D_
}_x000D_
input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input {_x000D_
background: #fa0;_x000D_
}_x000D_
_x000D_
_x000D_
input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input::before {_x000D_
content: "1";_x000D_
}_x000D_
input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input {_x000D_
background: #fa0;_x000D_
}_x000D_
_x000D_
input:checked + input:checked + input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input::before {_x000D_
content: "0";_x000D_
}_x000D_
input:checked + input:checked + input:checked +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input {_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
input:not(:checked) + input:not(:checked) + input:not(:checked) +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input::before {_x000D_
content: "0";_x000D_
}_x000D_
input:not(:checked) + input:not(:checked) + input:not(:checked) +_x000D_
*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+_x000D_
input {_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
body > input:nth-child(30n) { display: none !important; }_x000D_
body > input:nth-child(30n) + label { display: none !important; }
_x000D_
<p><a href="http://en.wikipedia.org/wiki/Rule_110">Rule 110</a> in (webkit) CSS, proving Turing-completeness.</p>_x000D_
_x000D_
<!-- A total of 900 checkboxes required -->_x000D_
<input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/><input type="checkbox"/>
_x000D_
Above example is also correct, but i provide simple example:
var fs = require("fs");
var sampleObject = {
name: 'pankaj',
member: 'stack',
type: {
x: 11,
y: 22
}
};
fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
if (err) {
console.error(err);
return;
};
console.log("File has been created");
});
Maybe this help you. May this not covert many to many relantionship, but es pretty handy when you want to send your model in json format.
def serial_model(modelobj):
opts = modelobj._meta.fields
modeldict = model_to_dict(modelobj)
for m in opts:
if m.is_relation:
foreignkey = getattr(modelobj, m.name)
if foreignkey:
try:
modeldict[m.name] = serial_model(foreignkey)
except:
pass
return modeldict
For Mac users using Homebrew (Brew) to install and manage services:
List your Brew services:
brew services
Do something with a service:
brew services start elasticsearch-full
brew services restart elasticsearch-full
brew services stop elasticsearch-full
It is another type of layer, so you should add it as a layer in an appropriate place of your model
model.add(keras.layers.normalization.BatchNormalization())
See an example here: https://github.com/fchollet/keras/blob/master/examples/kaggle_otto_nn.py
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.
Typically these are development related libraries and the most common use of these tools is for developers working on osx.
They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.
xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).
macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.
One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.
homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.
macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects
Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in
/opt/local
Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.
Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:
We really don’t like dupes in Homebrew/homebrew
However, we do like dupes in the tap!
Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:
- Duplicate libraries regularly break builds
- Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
- We want you to try harder to make your formula work with what OS X comes with
You can optionally overwrite the macosx supplied versions of utilities with homebrew.
If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.
If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:
<?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?>
You should really check out the tutorial on building an SEO-friendly AngularJS site on the year of moo blog. He walks you through all the steps outlined on Angular's documentation. http://www.yearofmoo.com/2012/11/angularjs-and-seo.html
Using this technique, the search engine sees the expanded HTML instead of the custom tags.
try "configuration properties -> debugging -> environment" and set the PATH variable in run-time
The best way I found to do this was to use the same intent as the Android home screen uses - the app Launcher.
For example:
Intent i = new Intent(this, MyMainActivity.class);
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
This way, whatever activity in my package was most recently used by the user is brought back to the front again. I found this useful in using my service's PendingIntent to get the user back to my app.
there are two solution worked for me. 1) disconnect your device from the mac and reattach it. 2) disconnect your device from the mac and restart it and then connect it with mac it'll work
The solution is actually described here: http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/
AngularJS does not allow duplicates in a ng-repeat directive. This means if you are trying to do the following, you will get an error.
// This code throws the error "Duplicates in a repeater are not allowed.
// Repeater: row in [1,1,1] key: number:1"
<div ng-repeat="row in [1,1,1]">
However, changing the above code slightly to define an index to determine uniqueness as below will get it working again.
// This will work
<div ng-repeat="row in [1,1,1] track by $index">
Official docs are here: https://docs.angularjs.org/error/ngRepeat/dupes
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. Consider your mobile phone, you just need to know what buttons are to be pressed to send a message or make a call, What happens when you press a button, how your messages are sent, how your calls are connected is all abstracted away from the user.
Encapsulation is the process of combining data and functions into a single unit called class. In Encapsulation, the data is not accessed directly; it is accessed through the functions present inside the class. In simpler words, attributes of the class are kept private and public getter and setter methods are provided to manipulate these attributes. Thus, encapsulation makes the concept of data hiding possible.
One big difference that hasn't been mentioned is that process.stdout only takes strings as arguments (can also be piped streams), while console.log takes any Javascript data type.
e.g:
// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))
// any other data type passed as param will throw a TypeError
process.stdout.write('1')
// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)
In addition to @James Iry's solution, it is also possible to accomplish this using a fold. I suspect that this solution is slightly faster than the tuple method (fewer garbage objects are created):
val list = List("this", "maps", "string", "to", "length")
val map = list.foldLeft(Map[String, Int]()) { (m, s) => m(s) = s.length }
There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974
@variable: 2em;
body{ width: calc(~"100% - @{variable} * 2");}
By using the curly brackets you don't need to close and reopen the escaping quotes.
I achieved this by getting a result list then checking if it is empty
public boolean exist(String value) {
List<Object> options = getEntityManager().createNamedQuery("AppUsers.findByEmail").setParameter('email', value).getResultList();
return !options.isEmpty();
}
It is so annoying that getSingleResult()
throws exceptions
Throws:
Unfortunately, you can't change the font size or styling in a drop-down list that is created using data validation.
You can style the text in a combo box, however. Follow the instructions here: Excel Data Validation Combo Box
Using ints.sum()
has two problems:
customerssalary
, not ints
Sum()
, not sum()
.Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average()
which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double
:
double average = ((double) sum) / customerssalary.Length;
The only way I can think of doing this is by creating a method that gives you the property using Object.keys();
.
var obj = {
dog: "woof",
cat: "meow",
key: function(n) {
return this[Object.keys(this)[n]];
}
};
obj.key(1); // "meow"
Demo: http://jsfiddle.net/UmkVn/
It would be possible to extend this to all objects using Object.prototype;
but that isn't usually recommended.
Instead, use a function helper:
var object = {
key: function(n) {
return this[ Object.keys(this)[n] ];
}
};
function key(obj, idx) {
return object.key.call(obj, idx);
}
key({ a: 6 }, 0); // 6
You can copy the HTML code to the clipboard and paste special it back as Unicode text. Excel will render the HTML in the cell. Check out this post http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
The relevant macro code from the post:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim objData As DataObject
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
If LCase(Left(Target.Text, 6)) = "<html>" Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
sSelAdd = Selection.Address
Target.Select
Me.PasteSpecial "Unicode Text"
Me.Range(sSelAdd).Select
End If
End If
Application.EnableEvents = True
End Sub
As others have mentioned, this is a really tricky question. Solutions to this are not "one size fits all", not even remotely. The difficulty (or ease) is really going to depend on your situation.
I have come to this problem on several occasions, but most recently while creating a debugging function. I wanted the function to take some unknown objects as arguments and print their declared names and contents. Getting the contents is easy of course, but the declared name is another story.
What follows is some of what I have come up with.
Determining the name of a function is really easy as it has the __name__ attribute containing the function's declared name.
name_of_function = lambda x : x.__name__
def name_of_function(arg):
try:
return arg.__name__
except AttributeError:
pass`
Just as an example, if you create the function def test_function(): pass
, then copy_function = test_function
, then name_of_function(copy_function)
, it will return test_function.
Check whether the object has a __name__ attribute and return it if so (declared functions only). Note that you may remove this test as the name will still be in globals()
.
Compare the value of arg with the values of items in globals()
and return the name of the first match. Note that I am filtering out names starting with '_'.
The result will consist of the name of the first matching object otherwise None.
def name_of_object(arg):
# check __name__ attribute (functions)
try:
return arg.__name__
except AttributeError:
pass
for name, value in globals().items():
if value is arg and not name.startswith('_'):
return name
globals()
and store names in a list. Note that I am filtering out names starting with '_'.The result will consist of a list (for multiple matches), a string (for a single match), otherwise None. Of course you should adjust this behavior as needed.
def names_of_object(arg):
results = [n for n, v in globals().items() if v is arg and not n.startswith('_')]
return results[0] if len(results) is 1 else results if results else None
CREATE TABLE Persons (
Personid int IDENTITY(1,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature.
In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change it to IDENTITY(10,5).
To insert a new record into the "Persons" table, we will NOT have to specify a value for the "Personid" column (a unique value will be added automatically):
It sounds like you basically want to take an ASCII string, or more preferably, a byte[] (as you can encode your string to a byte[] using your preferred encoding mode) into a string of ones and zeros? i.e. 101010010010100100100101001010010100101001010010101000010111101101010
This will do that for you...
//Formats a byte[] into a binary string (010010010010100101010)
public string Format(byte[] data)
{
//storage for the resulting string
string result = string.Empty;
//iterate through the byte[]
foreach(byte value in data)
{
//storage for the individual byte
string binarybyte = Convert.ToString(value, 2);
//if the binarybyte is not 8 characters long, its not a proper result
while(binarybyte.Length < 8)
{
//prepend the value with a 0
binarybyte = "0" + binarybyte;
}
//append the binarybyte to the result
result += binarybyte;
}
//return the result
return result;
}
Do following steps
a) Change minSdkVersion and sync gradle
b) Revert back your minSdkVersion and sync gradle again
It will be resolved.
In reply to Is there a specific reason?
, here is one interesting application: breaking out of multiple levels of looping.
Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the outer break is never reached. This way, a break in the inner loop will break out of both loops, rather than just one.
for k in [2, 3, 5, 7, 11, 13, 17, 25]:
for m in range(2, 10):
if k == m:
continue
print 'trying %s %% %s' % (k, m)
if k % m == 0:
print 'found a divisor: %d %% %d; breaking out of loop' % (k, m)
break
else:
continue
print 'breaking another level of loop'
break
else:
print 'no divisor could be found!'
For both while
and for
loops, the else
statement is executed at the end, unless break
was used.
In most cases there are better ways to do this (wrapping it into a function or raising an exception), but this works!
Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.
<body>
<app-root></app-root>
<script>
myTest = 1;
</script>
</body>
..near the top right after imports:
declare const myTest: any;
...later:
console.warn(myTest); // outputs '1'
We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.
HTML
<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />
JS Code
//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");
//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)
if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
ajaxRequestVariable.abort();
$("#test").html("Ajax Request Cancelled.");
}
});
//Ajax Process Starts
ajaxRequestVariable = $.ajax({
method: "POST",
url: '/echo/json/',
contentType: "application/json",
cache: false,
dataType: "json",
data: {
json: JSON.encode({
data:
[
{"prop1":"prop1Value"},
{"prop1":"prop2Value"}
]
}),
delay: 11
},
success: function (response) {
$("#test").show();
$("#test").html("Request is completed");
},
error: function (error) {
},
complete: function () {
}
});
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
List<T>
equality does not check them element-by-element. You can use LINQ's SequenceEqual
method for that:
var a = ints1.SequenceEqual(ints2);
To ignore order, use SetEquals
:
var a = new HashSet<int>(ints1).SetEquals(ints2);
This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:
var counts = ints1
.GroupBy(v => v)
.ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
int c;
if (counts.TryGetValue(n, out c)) {
counts[n] = c-1;
} else {
ok = false;
break;
}
}
var res = ok && counts.Values.All(c => c == 0);
Finally, if you are fine with an O(N*LogN)
solution, you can sort the two sequences, and compare them for equality using SequenceEqual
.
If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster. Python Programming FAQ
d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
You also have JFileUpload with SFTP add-on (Java too): http://www.jfileupload.com/products/sftp/index.html
Check you have the line:
import org.json.JSONArray;
at the top of your source code
Use a view model that contains multiple view models:
namespace MyProject.Web.ViewModels
{
public class UserViewModel
{
public UserDto User { get; set; }
public ProductDto Product { get; set; }
public AddressDto Address { get; set; }
}
}
In your view:
@model MyProject.Web.ViewModels.UserViewModel
@Html.LabelFor(model => model.User.UserName)
@Html.LabelFor(model => model.Product.ProductName)
@Html.LabelFor(model => model.Address.StreetName)
https://docs.python.org/3/library/pprint.html
If you need the text (for using with curses for example):
import pprint
myObject = []
myText = pprint.pformat(myObject)
Then myText
variable will something alike php var_dump
or print_r
. Check the documentation for more options, arguments.
In windows 10 you can recover in this way, there is no .snt file
adb -d shell
(or adb -e shell
).
This command will help you in most of the cases, if you are too lazy to type the full ID.
From http://developer.android.com/tools/help/adb.html#commandsummary:
-d
- Direct an adb command to the only attached USB device. Returns an error when more than one USB device is attached.
-e
- Direct an adb command to the only running emulator. Returns an error when more than one emulator is running.
You could easily write a program to do that, I've got several that I've written, that display bytes copied as the file is being copied. If you're interested, comment and I'll post a link to one.
Below is an implementation I use to intercept each HTTP request before it goes out and the response which comes back. With this implementation, I also have a single point where I can pass any header value with the request.
public class HttpInterceptor implements ClientHttpRequestInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body,
ClientHttpRequestExecution execution
) throws IOException {
HttpHeaders headers = request.getHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
logger.info("===========================Request begin======================================");
logger.info("URI : {}", request.getURI());
logger.info("Method : {}", request.getMethod());
logger.info("Headers : {}", request.getHeaders() );
logger.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
logger.info("==========================Request end=========================================");
}
private void traceResponse(ClientHttpResponse response) throws IOException {
logger.info("============================Response begin====================================");
logger.info("Status code : {}", response.getStatusCode());
logger.info("Status text : {}", response.getStatusText());
logger.info("Headers : {}", response.getHeaders());
logger.info("=======================Response end===========================================");
}}
Below is the Rest Template Bean
@Bean
public RestTemplate restTemplate(HttpClient httpClient)
{
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate= new RestTemplate(requestFactory);
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors))
{
interceptors = new ArrayList<>();
}
interceptors.add(new HttpInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
In order to take a picture you have to determine a path where you would like the image saved and pass that as an extra in the intent, for example:
private void capture(){
String directoryPath = Environment.getExternalStorageDirectory() + "/" + IMAGE_DIRECTORY + "/";
String filePath = directoryPath+Long.toHexString(System.currentTimeMillis())+".jpg";
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
this.capturePath = filePath; // you will process the image from this path if the capture goes well
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra( MediaStore.EXTRA_OUTPUT, Uri.fromFile( new File(filePath) ) );
startActivityForResult(intent, REQUEST_CAPTURE);
}
I just copied the above portion from another answer I gave.
However to warn you there are a lot of inconsitencies with image capture behavior between devices that you should look out for.
Here is an issue I ran into on some HTC devices, where it would save in the location I passed and in it's default location resulting in duplicate images on the device: Deleting a gallery image after camera intent photo taken
my guess is the server is not correctly handling the chunked transfer-encoding. It needs to terminal a chunked files with a terminal chunk to indicate the entire file has been transferred.So the code below maybe work:
echo "\n";
flush();
ob_flush();
exit(0);
If you already have nodejs installed (check with which nodejs
) and don't want to install another package, you can, as root:
update-alternatives --install /usr/bin/node node /usr/bin/nodejs 99
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
if you dont push your changes to git yet
git reset --soft HEAD~1
It will reset all the changes and revert to one commit back
If this is the last commit you made and you want to delete the file from local and remote repository try this :
git rm <file>
git commit --amend
or even better :
reset first
git reset --soft HEAD~1
reset the unwanted file
git reset HEAD path/to/unwanted_file
commit again
git commit -c ORIG_HEAD
If you does not want to use an extra view just for underlines. Add this style on your textView
.
style="?android:listSeparatorTextViewStyle"
Just down side is it will add extra properties like
android:textStyle="bold"
android:textAllCaps="true"
which you can easily override.
To do this, you can use Microsoft's more advanced command-line shell called "Windows PowerShell." It should come standard on the latest versions of Windows, but you can download it from Microsoft if you don't already have it installed.
To get the last five lines in the text file simply read the file using Get-Content
, then have Select-Object
pick out the last five items/lines for you:
Get-Content c:\scripts\test.txt | Select-Object -last 5
Source: Using the Get-Content Cmdlet
In Mono For Android....
try
{
System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
string Content = string.Empty;
using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
{
try
{
Content = StrRead.ReadToEnd();
StrRead.Close();
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
}
StrIn.Close();
StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
I've recently had to use eval
to force multiple brace expansions to be evaluated in the order I needed. Bash does multiple brace expansions from left to right, so
xargs -I_ cat _/{11..15}/{8..5}.jpg
expands to
xargs -I_ cat _/11/8.jpg _/11/7.jpg _/11/6.jpg _/11/5.jpg _/12/8.jpg _/12/7.jpg _/12/6.jpg _/12/5.jpg _/13/8.jpg _/13/7.jpg _/13/6.jpg _/13/5.jpg _/14/8.jpg _/14/7.jpg _/14/6.jpg _/14/5.jpg _/15/8.jpg _/15/7.jpg _/15/6.jpg _/15/5.jpg
but I needed the second brace expansion done first, yielding
xargs -I_ cat _/11/8.jpg _/12/8.jpg _/13/8.jpg _/14/8.jpg _/15/8.jpg _/11/7.jpg _/12/7.jpg _/13/7.jpg _/14/7.jpg _/15/7.jpg _/11/6.jpg _/12/6.jpg _/13/6.jpg _/14/6.jpg _/15/6.jpg _/11/5.jpg _/12/5.jpg _/13/5.jpg _/14/5.jpg _/15/5.jpg
The best I could come up with to do that was
xargs -I_ cat $(eval echo _/'{11..15}'/{8..5}.jpg)
This works because the single quotes protect the first set of braces from expansion during the parsing of the eval
command line, leaving them to be expanded by the subshell invoked by eval
.
There may be some cunning scheme involving nested brace expansions that allows this to happen in one step, but if there is I'm too old and stupid to see it.
You can also override settings, particularly useful in tests:
from django.test import override_settings
with override_settings(USE_TZ=False):
# Insert your code that causes the warning here
pass
This will prevent you from seeing the warning, at the same time anything in your code that requires a timezone aware datetime may give you problems. If this is the case, see kravietz answer.
=>
is used in associative array key value assignment. Take a look at:
http://php.net/manual/en/language.types.array.php.
->
is used to access an object method or property. Example: $obj->method()
.
204 is more appropriate. Especially when you have a alert system to ensure you website is secure, 404 in this case would cause confusion because you don't know some 404 alerts is backend errors or normal requests but response empty.
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
/* cellpadding */
th, td { padding: 5px; }
/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; } /* cellspacing="0" */
/* valign */
th, td { vertical-align: top; }
/* align (center) */
table { margin: 0 auto; }
A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
c = i +'0';
The '0' is a character in the ASCll table.
Use MouseClick event instead of Click
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);
var client = new EchoServiceClient(address);
litResponse.Text = client.SendEcho("Hello World");
client.Close();
Actual working final version by valamas
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close();
I would try to make @ErichBSchulz's answer simpler for beginners:
public class XMLParser {
public static void main(String[] args){
try {
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = dBuilder.parse(new File("xml input"));
NodeList nl=doc.getDocumentElement().getChildNodes();
for(int k=0;k<nl.getLength();k++){
printTags((Node)nl.item(k));
}
} catch (Exception e) {/*err handling*/}
}
public static void printTags(Node nodes){
if(nodes.hasChildNodes() || nodes.getNodeType()!=3){
System.out.println(nodes.getNodeName()+" : "+nodes.getTextContent());
NodeList nl=nodes.getChildNodes();
for(int j=0;j<nl.getLength();j++)printTags(nl.item(j));
}
}
}
Recursively loop through and print out all the xml child tags in the document, in case you don't have to change the code to handle dynamic changes in xml, provided it's a well formed xml.
Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);
You can use the JDOM library in Java. Define your tags as Element objects, document your elements with Document Class, and build your xml file with SAXBuilder. Try this example:
//Root Element
Element root=new Element("CONFIGURATION");
Document doc=new Document();
//Element 1
Element child1=new Element("BROWSER");
//Element 1 Content
child1.addContent("chrome");
//Element 2
Element child2=new Element("BASE");
//Element 2 Content
child2.addContent("http:fut");
//Element 3
Element child3=new Element("EMPLOYEE");
//Element 3 --> In this case this element has another element with Content
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
//Add it in the root Element
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
//Define root element like root
doc.setRootElement(root);
//Create the XML
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
I use these properties and it works!
#header {
display: table-cell;
vertical-align: bottom;
}
Since jQuery is open-source, I would guess that you could tweak the css
function to call a function of your choice every time it is invoked (passing the jQuery object). Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties. Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.
Go to Your Build.gradle and add below dependencies for both Java 9 or Java 10.
sourceCompatibility = 10 // You can also decrease your souce compatibility to 1.8
//java 9+ does not have Jax B Dependents
compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0'
compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
compile group: 'javax.activation', name: 'activation', version: '1.1.1'
If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.
Yes to using read
- and there are a couple of tweaks that make it most useful in both cron
and in the terminal.
Example:
time rsync (options)
read -n 120 -p "Press 'Enter' to continue..." ; echo " "
The -n 120 makes the read statement time out after 2 minutes so it does not block in cron
.
In terminal it gives 2 minutes to see how long the rsync
command took to execute.
Then the subsequent echo
is so the subsequent bash prompt will appear on the next line.
Otherwise it will show on the same line directly after "continue..." when Enter is pressed in terminal.
You want to use os.path.expanduser.
This will ensure it works on all platforms:
from os.path import expanduser
home = expanduser("~")
If you're on Python 3.5+ you can use pathlib.Path.home():
from pathlib import Path
home = str(Path.home())
You can also simply increase the Minimum memory per query value in server properties. To edit this setting, right click on server name and select Properties > Memory tab.
I encountered this error trying to execute a 30MB SQL script in SSMS 2012. After increasing the value from 1024MB to 2048MB I was able to run the script.
(This is the same answer I provided here)
In Swift 3 something like this with @objc:
func startTimerForResendingCode() {
let timerIntervalForResendingCode = TimeInterval(60)
Timer.scheduledTimer(timeInterval: timerIntervalForResendingCode,
target: self,
selector: #selector(timerEndedUp),
userInfo: nil,
repeats: false)
}
@objc func timerEndedUp() {
output?.timerHasFinishedAndCodeMayBeResended()
}
None of the answers seemed to work for me or were too complicated. Luckily, it's not complicated with xargs
(Tested on Ubuntu 20.04).
This works with each arg on a separate line in the file as the OP mentions and was what I needed as well.
cat foo.txt | xargs my_command
One thing to note is that it doesn't seem to work with aliased commands.
The accepted answer works if the command accepts multiple args wrapped in a string. In my case using (Neo)Vim it does not and the args are all stuck together.
xargs
does it probably and actually gives you separate arguments supplied to the command.
I too have been frustrated by the lack of good graphical http clients available for Windows. So over the past couple years I've been developing one myself: I'm Only Resting, "a feature-rich WinForms-based HTTP client." It's open source (Apache License, Version 2.0) with freely available downloads.
It currently has fairly complete coverage of HTTP features except for file uploads, and it provides a very good user interface with great request and response management.
Here's a screenshot:
(source: swensensoftware.com)
Primitive data types (such as byte) don't have methods in java, but you can directly do:
int i=rno[0];
This will make image shrink if it's too big for specified area (as downside, it will not enlarge image).
The solution by setec is fine for "Shrink to Fit" in auto mode. But, to optimally EXPAND to fit in 'auto' mode, you need to first put the received image into a temp id, Check if it can be expanded in height or in width (depending upon its aspect ration v/s the aspect ratio of your display block),
$(".temp_image").attr("src","str.jpg" ).load(function() {
// callback to get actual size of received image
// define to expand image in Height
if(($(".temp_image").height() / $(".temp_image").width()) > display_aspect_ratio ) {
$(".image").css('height', max_height_of_box);
$(".image").css('width',' auto');
} else {
// define to expand image in Width
$(".image").css('width' ,max_width_of_box);
$(".image").css('height','auto');
}
//Finally put the image to Completely Fill the display area while maintaining aspect ratio.
$(".image").attr("src","str.jpg");
});
This approach is useful when received images are smaller than display box. You must save them on your server in Original Small size rather than their expanded version to fill your Bigger display Box to save on size and bandwidth.
on Jupyter notebook, try this:
pwd #this shows the current directory
if this is not the directory you like and you would like to change, try this:
import os
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')
Then try pwd again to see if the directory is what you want.
It works for me.
In simple words:
innerText
will show the value as is and ignores any HTML
formatting which may
be included.innerHTML
will show the value and apply any HTML
formatting.What about trying the which
command?
If you were to run which psql
and Postgres is not installed there appears to be no output. You just get the terminal prompt ready to accept another command:
> which psql
>
But if Postgres is installed you'll get a response with the path to the location of the Postgres install:
> which psql
/opt/boxen/homebrew/bin/psql
Looking at man which
there also appears to be an option that could help you out:
-s No output, just return 0 if any of the executables are found, or
1 if none are found.
So it seems like as long as whatever scripting language you're using can can execute a terminal command you could send which -s psql
and use the return value to determine if Postgres is installed. From there you can print that result however you like.
I do have postgres installed on my machine so I run the following
> which -s psql
> echo $?
0
which tells me that the command returned 0, indicating that the Postgres executable was found on my machine.
It's an indication that connection pooling is being used (which is a good thing).
to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.
using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
sqlCon.Open();
var com = sqlCon.CreateCommand();
com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
using (var reader = com.ExecuteReader())
{
while(reader.read()){
//iterate code
}
int totalRow = 0 ;
reader.NextResult(); //
if(reader.read()){
totalRow = (int)reader[0];
}
}
sqlCon.Close();
}
A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.
!important
, and give the selector a higher specificity (adding an additional tag, id or class to the selector)Some examples with a higher specificity (first is highest/overrides, third is lowest):
table td {height: 50px !important;}
.myTable td {height: 50px !important;}
#myTable td {height: 50px !important;}
Or add the same selector after the existing one:
td {height: 50px !important;}
It's almost never a good idea to use !important
. This is bad engineering by the creators of the WordPress template. In viral fashion, it forces users of the template to add their own !important
modifiers to override it, and it limits the options for overriding it via JavaScript.
But, it's useful to know how to override it, if you sometimes have to.
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function() {
$('#viewSource').click(function() {
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
<a href="#" id="viewSource">Source file</a>
</body>
</html>
This will do what you want:
select *
from orders_products
INNER JOIN orders
ON orders_products.orders_id = orders.orders_id
where products_id in (180, 181);
Here's a simple function that lets you do what you are looking for:
- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
{
NSRange firstInstance = [value rangeOfString:separator];
NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);
return [value substringWithRange:finalRange];
}
Usage:
NSString *myName = [self getSubstring:@"This is my :name:, woo!!" betweenString:@":"];
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
The mistake I did was my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.
If you want to change the table default character set
and all character columns to a new character set, use a statement like this:
ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;
So query will be:
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});
If the problem is that you don't have access to SQL Server and now you are using mixed mode to enable sa or grant an account admin privileges, then it is far easier just to uninstall SQL Server and reinstall.
The syntax of if block is as below,
if(condition){
// Executes when condition evaluates to true.
}
else{
// Executes when condition evaluates to false.
}
In your case you are directly passing a boolean value so no evaluation is required.
Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:
Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).
The pattern I've put together (and written a code snippet for) follows:
#region IDisposable implementation
//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable
// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }
/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
Dispose( true );
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
// Always use SuppressFinalize() in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize( this );
}
/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
// TODO If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
try
{
if( !this.IsDisposed )
{
if( isDisposing )
{
// TODO Release all managed resources here
$end$
}
// TODO Release all unmanaged resources here
// TODO explicitly set root references to null to expressly tell the GarbageCollector
// that the resources have been disposed of and its ok to release the memory allocated for them.
}
}
finally
{
// explicitly call the base class Dispose implementation
base.Dispose( isDisposing );
this.IsDisposed = true;
}
}
//TODO Uncomment this code if this class will contain members which are UNmanaged
//
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
// ~$className$()
// {
// Dispose( false );
// }
#endregion IDisposable implementation
Here is the code for implementing IDisposable in a derived class. Note that you do not need to explicitly list inheritance from IDisposable in the definition of the derived class.
public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)
protected override void Dispose( bool isDisposing )
{
try
{
if ( !this.IsDisposed )
{
if ( isDisposing )
{
// Release all managed resources here
}
}
}
finally
{
// explicitly call the base class Dispose implementation
base.Dispose( isDisposing );
}
}
I've posted this implementation on my blog at: How to Properly Implement the Dispose Pattern
I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.
I use the stored procedure below to update the defaults on a column.
It automatically removes any prior defaults on the column, before adding the new default.
Examples of usage:
-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
Stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
(
-- Table name, including schema, e.g. '[dbo].[TableName]'
@TABLE_NAME VARCHAR(100),
-- Column name, e.g. 'ColumnName'.
@COLUMN_NAME VARCHAR(100),
-- New default, e.g. '''MyDefault''' or 'getdate()'
-- Note that if you want to set it to a string constant, the contents
-- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
@NEW_DEFAULT VARCHAR(100)
)
AS
BEGIN
-- Trim angle brackets so things work even if they are included.
set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')
print 'Table name: ' + @TABLE_NAME;
print 'Column name: ' + @COLUMN_NAME;
DECLARE @ObjectName NVARCHAR(100)
SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;
IF @ObjectName <> ''
begin
print 'Removed default: ' + @ObjectName;
--print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
end
EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
--print('ALTER TABLE ' + @TABLE_NAME + ' ADD DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
print 'Added default of: ' + @NEW_DEFAULT;
END
Errors this stored procedure eliminates
If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):
-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
but you should really do this
<?php
$param = "test";
?>
<a href="http://www.whatever.com/<?php echo $param; ?>">Click Here</a>
Only this worked for me:
#container:hover .cube { background-color: yellow; }
Where .cube
is CssClass of the #cube
.
Tested in Firefox, Chrome and Edge.
If you are making a large application with other developers in your team and intend to have everything well organized without scattered code or different SharedPreferences instances, you may do something like this:
//SharedPreferences manager class
public class SharedPrefs {
//SharedPreferences file name
private static String SHARED_PREFS_FILE_NAME = "my_app_shared_prefs";
//here you can centralize all your shared prefs keys
public static String KEY_MY_SHARED_BOOLEAN = "my_shared_boolean";
public static String KEY_MY_SHARED_FOO = "my_shared_foo";
//get the SharedPreferences object instance
//create SharedPreferences file if not present
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE);
}
//Save Booleans
public static void savePref(Context context, String key, boolean value) {
getPrefs(context).edit().putBoolean(key, value).commit();
}
//Get Booleans
public static boolean getBoolean(Context context, String key) {
return getPrefs(context).getBoolean(key, false);
}
//Get Booleans if not found return a predefined default value
public static boolean getBoolean(Context context, String key, boolean defaultValue) {
return getPrefs(context).getBoolean(key, defaultValue);
}
//Strings
public static void save(Context context, String key, String value) {
getPrefs(context).edit().putString(key, value).commit();
}
public static String getString(Context context, String key) {
return getPrefs(context).getString(key, "");
}
public static String getString(Context context, String key, String defaultValue) {
return getPrefs(context).getString(key, defaultValue);
}
//Integers
public static void save(Context context, String key, int value) {
getPrefs(context).edit().putInt(key, value).commit();
}
public static int getInt(Context context, String key) {
return getPrefs(context).getInt(key, 0);
}
public static int getInt(Context context, String key, int defaultValue) {
return getPrefs(context).getInt(key, defaultValue);
}
//Floats
public static void save(Context context, String key, float value) {
getPrefs(context).edit().putFloat(key, value).commit();
}
public static float getFloat(Context context, String key) {
return getPrefs(context).getFloat(key, 0);
}
public static float getFloat(Context context, String key, float defaultValue) {
return getPrefs(context).getFloat(key, defaultValue);
}
//Longs
public static void save(Context context, String key, long value) {
getPrefs(context).edit().putLong(key, value).commit();
}
public static long getLong(Context context, String key) {
return getPrefs(context).getLong(key, 0);
}
public static long getLong(Context context, String key, long defaultValue) {
return getPrefs(context).getLong(key, defaultValue);
}
//StringSets
public static void save(Context context, String key, Set<String> value) {
getPrefs(context).edit().putStringSet(key, value).commit();
}
public static Set<String> getStringSet(Context context, String key) {
return getPrefs(context).getStringSet(key, null);
}
public static Set<String> getStringSet(Context context, String key, Set<String> defaultValue) {
return getPrefs(context).getStringSet(key, defaultValue);
}
}
In your activity you may save SharedPreferences this way
//saving a boolean into prefs
SharedPrefs.savePref(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN, booleanVar);
and you may retrieve your SharedPreferences this way
//getting a boolean from prefs
booleanVar = SharedPrefs.getBoolean(this, SharedPrefs.KEY_MY_SHARED_BOOLEAN);
If the above solutions did not work for you so -
Could be that you did not install C++ compiler packages properly, flow this: (Instructions for Win7, 32bit/64bit)
Make sure you install properly one or more of the supporting C++ compiler packages:
(I installed MinGW (HowTo Install Videos can be found on YouTube))
In case you choose to install MinGW packages:
Run MinGW installer and make sure to choose the following packages:
- mingw-developer-toolkit
- mingw32-base
- mingw32-gcc-g++
- msys-base
Add MinGW and MSYS bin paths to your PATH environment variable , if you didn't change the default installation folders you should add:
C:\MinGW\msys\1.0\bin;C:\MinGW\bin;
Create a new C++ project in eclipse:
In you Hello World Project you shall see + src folder, and + Includes (If so you are probably good to go).
Yes, you will have no problems using:
if (BuildConfig.DEBUG) {
//It's not a release version.
}
Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.
Here are the steps to move a private Git repository:
Step 1: Create Github repository
First, create a new private repository on Github.com. It’s important to keep the repository empty, e.g. don’t check option Initialize this repository with a README when creating the repository.
Step 2: Move existing content
Next, we need to fill the Github repository with the content from our Bitbucket repository:
$ git clone https://[email protected]/USER/PROJECT.git
$ cd PROJECT
$ git remote add upstream https://github.com:USER/PROJECT.git
$ git push upstream master
$ git push --tags upstream
Step 3: Clean up old repository
Finally, we need to ensure that developers don’t get confused by having two repositories for the same project. Here is how to delete the Bitbucket repository:
Double-check that the Github repository has all content
Go to the web interface of the old Bitbucket repository
Select menu option Setting > Delete repository
Add the URL of the new Github repository as redirect URL
With that, the repository completely settled into its new home at Github. Let all the developers know!
In your example
return $cnf::getConfig($key)
Probably should be:
return $cnf->getConfig($key)
And make getConfig not static
Using Google Collections, assuming K is your key type:
Maps.filterKeys(treeMap, new Predicate<K>() {
@Override
public boolean apply(K key) {
return false; //return true here if you need the entry to be in your new map
}});
You can use filterEntries
instead if you need the value as well.
Same Issue.
Resolved by copying the missing files from
C:\Users\UserName\AppData\Roaming\npm\node_modules\npm\bin
to
C:\Users\UserName\node_modules\npm\bin
The missing files are
Move path\to\anaconda
in the PATH above path\to\python
also you can try the following.
find . -name '*.java' -exec grep "<yourword" /dev/null {} \;
It gets all the files with .java extension and searches 'yourword' in each file, if it presents, it lists the file.
Hope it helps :)
You can do that with the below code:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition
I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;
basically what I did was create a new server but flask if not python
I hope it helps you
If you are using Angular 1.3 or above, I recommend that you use "track by" in your ng-repeat. Angular doesn't add a "$$hashKey" property to the objects in your array if you use "track by". You also get performance benefits, if something in your array changes, angular doesn't recreate the entire DOM structure for your ng-repeat, it instead recreates the part of the DOM for the values in your array that have changed.
I assume I have import datetime
before running each of the lines of code below
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
prints "01/25/13"
.
If you can't live with the leading zero, try this:
dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)
This prints "1/25/13"
.
EDIT: This may not work on every platform:
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
There is a package called eclipse-cdt
in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++
already, you need to install that as well, so all you need is:
sudo apt-get install eclipse eclipse-cdt g++
Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudo
s blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get
and hope for the best.
Use the location header flag:
curl -L <URL>
The list of encodings that node supports natively is rather short:
If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:
Use iconv-lite to recode files:
var iconvlite = require('iconv-lite');
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
return iconvlite.decode(content, encoding);
}
Alternatively, use iconv:
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
var iconv = new Iconv(encoding, 'UTF-8');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
}
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("@Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
Jon, you have some syntax errors, see below, this worked for me.
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod(
"australianDate",
function (value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"
);
$('#testForm').validate({
rules: {
"myDate": {
australianDate: true
}
}
});
});
It's the remainder operator and is used to get the remainder after integer division. Lots of languages have it. For example:
10 % 3 // = 1 ; because 3 * 3 gets you 9, and 10 - 9 is 1.
Apparently it is not the same as the modulo operator entirely.
This is backwards from what Bootstrap is designed for, but you can do this:
<div class="row">
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>
This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.
JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/
I think you're looking for the visible-xs
and/or visible-sm
classes. These will let you make certain elements only visible to small screen devices.
For example, if you want a element to only be visible to small and extra-small devices, do this:
<div class="visible-xs visible-sm">You're using a fairly small device.</div>
To show it only for larger screens, use this:
<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>
See http://getbootstrap.com/css/#responsive-utilities-classes for more information.
Do you mean "A" (a string
) or 'A' (a char
)?
int unicode = 65;
char character = (char) unicode;
string text = character.ToString();
Note that I've referred to Unicode rather than ASCII as that's C#'s native character encoding; essentially each char
is a UTF-16 code point.
I solved a similar problem in a simple way:
git pull origin master
. Replace 'origin' with your Remote nameThat's all. I Solved the problem
STRING TO URI.
Uri uri=Uri.parse("YourString");
URI TO STRING
Uri uri;
String andro=uri.toString();
happy coding :)
So here's how to do that:
In the bottom bar of VSCode, you'll see the label
UTF-8
. Click it. A popup opens. ClickSave with encoding
. You can now pick a new encoding for that file.
Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8"
. If using the graphical settings page in VSCode, simply search for encoding
. Do note however that this only applies to newly created files.
Before using multidimensional arrays in Swift, consider their impact on performance. In my tests, the flattened array performed almost 2x better than the 2D version:
var table = [Int](repeating: 0, count: size * size)
let array = [Int](1...size)
for row in 0..<size {
for column in 0..<size {
let val = array[row] * array[column]
// assign
table[row * size + column] = val
}
}
Average execution time for filling up a 50x50 Array: 82.9ms
vs.
var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
let array = [Int](1...size)
for row in 0..<size {
for column in 0..<size {
// assign
table[row][column] = val
}
}
Average execution time for filling up a 50x50 2D Array: 135ms
Both algorithms are O(n^2), so the difference in execution times is caused by the way we initialize the table.
Finally, the worst you can do is using append()
to add new elements. That proved to be the slowest in my tests:
var table = [Int]()
let array = [Int](1...size)
for row in 0..<size {
for column in 0..<size {
table.append(val)
}
}
Average execution time for filling up a 50x50 Array using append(): 2.59s
Avoid multidimensional arrays and use access by index if execution speed matters. 1D arrays are more performant, but your code might be a bit harder to understand.
You can run the performance tests yourself after downloading the demo project from my GitHub repo: https://github.com/nyisztor/swift-algorithms/tree/master/big-o-src/Big-O.playground
If you use
std::vector<std::reference_wrapper<std::string>> names{ };
Do not forget, when you use auto in the for loop, to use also get, like this:
for (auto element in : names)
{
element.get()//do something
}
As Foo
is a class can you not create virtual overloaded Initialise()
methods? Then they would be available to sub-classes and still extensible?
public class Foo
{
...
public Foo() {...}
public virtual void Initialise(int i) {...}
public virtual void Initialise(int i, int i) {...}
public virtual void Initialise(int i, int i, int i) {...}
...
public virtual void Initialise(int i, int i, ..., int i) {...}
...
public virtual void SomethingElse() {...}
...
}
This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.
.hover()
function accepts two function arguments, one for mouseenter
event and one for mouseleave
event.
When we use lazy-init="default" as an attribute in element, the container picks up the value specified by default-lazy-init="true|false" attribute of element and uses it as lazy-init="true|false".
If default-lazy-init attribute is not present in element than lazy-init="default" in element will behave as if lazy-init-"false".
::-webkit-input-placeholder { /* WebKit browsers */
color: #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
color: #999;
}
This is because, in the constructor, you declared a local variable with the same name as an attribute.
To allocate an integer array which all elements are initialized to zero, write this in the constructor:
data = new int[3];
To allocate an integer array which has other initial values, put this code in the constructor:
int[] temp = {2, 3, 7};
data = temp;
or:
data = new int[] {2, 3, 7};
It can be as simple as:
default_data['item3'] = 3
As Chris' answer says, you can use update to add more than one item. An example:
default_data.update({'item4': 4, 'item5': 5})
Please see the documentation about dictionaries as data structures and dictionaries as built-in types.
Just for completeness' sake (sum
is usually preferable), I wanted to mention that we can also use filter
to get the truthy values. In the usual case, filter
accepts a function as the first argument, but if you pass it None
, it will filter for all "truthy" values. This feature is somewhat surprising, but is well documented and works in both Python 2 and 3.
The difference between the versions, is that in Python 2 filter
returns a list, so we can use len
:
>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
[True, True, True]
>>> len(filter(None, bool_list))
3
But in Python 3, filter
returns an iterator, so we can't use len
, and if we want to avoid using sum
(for any reason) we need to resort to converting the iterator to a list (which makes this much less pretty):
>>> bool_list = [True, True, False, False, False, True]
>>> filter(None, bool_list)
<builtins.filter at 0x7f64feba5710>
>>> list(filter(None, bool_list))
[True, True, True]
>>> len(list(filter(None, bool_list)))
3
You can use this BASH script:
#!/bin/bash
USER="YOUR_DATABASE_USER"
PASSWORD="YOUR_USER_PASSWORD"
DB_NAME="DATABASE_NAME"
CHARACTER_SET="utf8" # your default character set
COLLATE="utf8_general_ci" # your default collation
tables=`mysql -u $USER -p$PASSWORD -e "SELECT tbl.TABLE_NAME FROM information_schema.TABLES tbl WHERE tbl.TABLE_SCHEMA = '$DB_NAME' AND tbl.TABLE_TYPE='BASE TABLE'"`
for tableName in $tables; do
if [[ "$tableName" != "TABLE_NAME" ]] ; then
mysql -u $USER -p$PASSWORD -e "ALTER TABLE $DB_NAME.$tableName DEFAULT CHARACTER SET $CHARACTER_SET COLLATE $COLLATE;"
echo "$tableName - done"
fi
done
Update (2019, latest)
Since Jan 2019, GitHub allows private repositories for up to three collaborators.
Previous answer:
Here is the comparison for free plans listed by tree main Git Cloud based solutions:
Here is the comparison for paid plans listed by tree main Git Cloud based solutions:
I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.
GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.
Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.
GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.
I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try
adb shell ls -R /
You probably need the root permission though.
Edit:
As other answers suggest, use ls
with grep
like this:
adb shell ls -Ral yourDirectory | grep -i yourString
eg.
adb shell ls -Ral / | grep -i myfile
-i
is for ignore-case. and /
is the root directory.
This works for me for aligning the image to center of div.
.yourclass {
background-image: url(image.png);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
I use PV.exe from http://www.teamcti.com/pview/prcview.htm installed in Program Files\PV with a batch file like this:
@echo off
PATH=%PATH%;%PROGRAMFILES%\PV;%PROGRAMFILES%\YourProgram
PV.EXE YourProgram.exe >nul
if ERRORLEVEL 1 goto Process_NotFound
:Process_Found
echo YourProgram is running
goto END
:Process_NotFound
echo YourProgram is not running
YourProgram.exe
goto END
:END
We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args
and **kwargs
, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression
and keyword = expression
. So we split them up.
If you are using Asp.Net MVC, then take a look at:
public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes);
which is a static public method on the System.Web.Mvc.HtmlHelper class.
Simple code please check
SELECT * FROM table_name WHERE created <= (NOW() - INTERVAL 1 MONTH)
A simple method, which I use in C++ is:
double deltaOrientation = angle1 - angle2;
double delta = remainder(deltaOrientation, 2*M_PI);
Use:
git log --graph --abbrev-commit --decorate --first-parent <branch_name>
It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).
The key option is --first-parent
: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)
It prevents the commit forks from being displayed.
you can use the defer attribute to load the script at the really end.
<script type='text/javascript' src='myscript.js' defer='defer'></script>
but normally loading your script in correct order should do the trick, so be sure to place jquery inclusion before your own script
If your code is in the page and not in a separate js file so you have to execute your script only after the document is ready and encapsulating your code like this should work too:
$(function(){
//here goes your code
});
This is the hardware serial number. To access it on
Android Q (>= SDK 29)
android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE
is required. Only system apps can require this permission. If the calling package is the device or profile owner then the READ_PHONE_STATE
permission suffices.
Android 8 and later (>= SDK 26) use android.os.Build.getSerial()
which requires the dangerous permission READ_PHONE_STATE. Using android.os.Build.SERIAL
returns android.os.Build.UNKNOWN.
Android 7.1 and earlier (<= SDK 25) and earlier android.os.Build.SERIAL
does return a valid serial.
It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read here.
For a solution involving reflection without requiring a permission see this answer.
Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:
# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH
For me that's a very neat feature which can be propagated to other variables. Example:
typeset -T LD_LIBRARY_PATH ld_library_path :
For money: decimal
. It costs a little more memory, but doesn't have rounding troubles like double
sometimes has.
Sure. A function's type consists of the types of its argument and its return type. Here we specify that the callback
parameter's type must be "function that accepts a number and returns type any
":
class Foo {
save(callback: (n: number) => any) : void {
callback(42);
}
}
var foo = new Foo();
var strCallback = (result: string) : void => {
alert(result);
}
var numCallback = (result: number) : void => {
alert(result.toString());
}
foo.save(strCallback); // not OK
foo.save(numCallback); // OK
If you want, you can define a type alias to encapsulate this:
type NumberCallback = (n: number) => any;
class Foo {
// Equivalent
save(callback: NumberCallback) : void {
callback(42);
}
}
In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197
In SQL Server Management Studio 2016, perform the following:
Right click on database
Click delete
Check close existing connections
Perform delete operation
You can use XDocument.Parse(string)
instead of Load(string)
.
THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER
I had this same problem when using the Ruby Gem.
To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:
mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })
https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection
mongo_client = MongoClient.new # (optional host/port args)
Notice that 'args' is the third optional argument.
findAny
& orElse
By using findAny()
and orElse()
:
Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);
Stops looking after finding an occurrence.
findAny
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
Have your tried using the 'return' keyword?
def rps():
return True
From documentation: https://docs.djangoproject.com/en/1.10/ref/settings/
if DEBUG is False, you also need to properly set the ALLOWED_HOSTS setting. Failing to do so will result in all requests being returned as “Bad Request (400)”.
And from here: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS
I am using something like this:
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'www.mysite.com']
You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.
It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.
Why not rewrite it to be
for element in somelist:
do_action(element)
if check(element):
remove_element_from_list
See this question for how to remove from the list, though it looks like you've already seen that Remove items from a list while iterating
Another option is to do this if you really want to keep this the same
newlist = []
for element in somelist:
do_action(element)
if not check(element):
newlst.append(element)
extension Array where Element : Equatable {
public subscript(safe bounds: Range<Int>) -> ArraySlice<Element> {
if bounds.lowerBound > count { return [] }
let lower = Swift.max(0, bounds.lowerBound)
let upper = Swift.max(0, Swift.min(count, bounds.upperBound))
return self[lower..<upper]
}
public subscript(safe lower: Int?, _ upper: Int?) -> ArraySlice<Element> {
let lower = lower ?? 0
let upper = upper ?? count
if lower > upper { return [] }
return self[safe: lower..<upper]
}
}
returns a copy of this range clamped to the given limiting range.
var arr = [1, 2, 3]
arr[safe: 0..<1] // returns [1] assert(arr[safe: 0..<1] == [1])
arr[safe: 2..<100] // returns [3] assert(arr[safe: 2..<100] == [3])
arr[safe: -100..<0] // returns [] assert(arr[safe: -100..<0] == [])
arr[safe: 0, 1] // returns [1] assert(arr[safe: 0, 1] == [1])
arr[safe: 2, 100] // returns [3] assert(arr[safe: 2, 100] == [3])
arr[safe: -100, 0] // returns [] assert(arr[safe: -100, 0] == [])
Optimistic assumes that nothing's going to change while you're reading it.
Pessimistic assumes that something will and so locks it.
If it's not essential that the data is perfectly read use optimistic. You might get the odd 'dirty' read - but it's far less likely to result in deadlocks and the like.
Most web applications are fine with dirty reads - on the rare occasion the data doesn't exactly tally the next reload does.
For exact data operations (like in many financial transactions) use pessimistic. It's essential that the data is accurately read, with no un-shown changes - the extra locking overhead is worth it.
Oh, and Microsoft SQL server defaults to page locking - basically the row you're reading and a few either side. Row locking is more accurate but much slower. It's often worth setting your transactions to read-committed or no-lock to avoid deadlocks while reading.
This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
DataRow myRow = dtSpecificOrders.NewRow(); // <-- create a brand-new row
myRow[dcID] = int.Parse(dr["ID"]);
myRow[dcName] = dr["Name"].ToString();
dtSpecificOrders.Rows.Add(myRow); // <-- this will add the new row
}
The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.
From JavaScript, since the Github API is CORS enabled:
fetch('https://api.github.com/repos/webdev23/source_control_sentry')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
_x000D_
try this:
var xxx = window.open("","Printing...");
xxx.onload = function () {
setTimeout(function(){xxx.print();}, 500);
xxx.onfocus = function () {
xxx.close();
}
}
Just write
ProcessStartInfo psi= new ProcessStartInfo("cmd.exe");
......
psi.CreateNoWindow = true;
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
You can hold onto the percentage as decimal (value \ total)
and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:
var displayPercentage = $"{(decimal)value / total:P}";
or
//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";
So I have another approach, similar to everyone who used UriBuilder.
I did not want to split my BaseUrl (which can contain a part of the path - e.g. http://mybaseurl.com/dev/) as javajavajavajavajava did.
The following snippet shows the code + Tests.
Beware: This solution lowercases the host and appends a port. If this is not desired, one can write a string representation by e.g. leveraging the Uri
Property of UriBuilder
.
public class Tests
{
public static string CombineUrl (string baseUrl, string path)
{
var uriBuilder = new UriBuilder (baseUrl);
uriBuilder.Path = Path.Combine (uriBuilder.Path, path);
return uriBuilder.ToString();
}
[TestCase("http://MyUrl.com/", "/Images/Image.jpg", "http://myurl.com:80/Images/Image.jpg")]
[TestCase("http://MyUrl.com/basePath", "/Images/Image.jpg", "http://myurl.com:80/Images/Image.jpg")]
[TestCase("http://MyUrl.com/basePath", "Images/Image.jpg", "http://myurl.com:80/basePath/Images/Image.jpg")]
[TestCase("http://MyUrl.com/basePath/", "Images/Image.jpg", "http://myurl.com:80/basePath/Images/Image.jpg")]
public void Test1 (string baseUrl, string path, string expected)
{
var result = CombineUrl (baseUrl, path);
Assert.That (result, Is.EqualTo (expected));
}
}
Tested with .NET Core 2.1 on Windows 10.
Why does this work?
Even though Path.Combine
will return Backslashes (on Windows atleast), the UriBuilder handles this case in the Setter of Path
.
Taken from https://github.com/dotnet/corefx/blob/master/src/System.Private.Uri/src/System/UriBuilder.cs (mind the call to string.Replace
)
[AllowNull]
public string Path
{
get
{
return _path;
}
set
{
if ((value == null) || (value.Length == 0))
{
value = "/";
}
_path = Uri.InternalEscapeString(value.Replace('\\', '/'));
_changed = true;
}
}
Is this the best approach?
Certainly this solution is pretty self describing (at least in my opinion). But you are relying on undocumented (at least I found nothing with a quick google search) "feature" from the .NET API. This may change with a future release so please cover the Method with Tests.
There are tests in https://github.com/dotnet/corefx/blob/master/src/System.Private.Uri/tests/FunctionalTests/UriBuilderTests.cs (Path_Get_Set
) which check, if the \
is correctly transformed.
Side Note: One could also work with the UriBuilder.Uri
property directly, if the uri will be used for a System.Uri
ctor.
I thought I would update this post a bit and say that alot of the iOS community has moved over to AFNetworking after ASIHTTPRequest
was abandoned. I highly recommend it. It's a great wrapper around NSURLConnection
and allows for asynchronous calls, and basically anything you might need.
Using Subversion with either the Apache module or svnserve. I've been able to perform operations as multiple users using --username
.
Each time you invoke a Subversion command as a 'new' user, your $HOME/.subversion/auth/<authentication-method>/
directory will have a new entry cached for that user (assuming you are able to authenticate with the correct password or authentication method for the server you are contacting as that particular user).
Both C and C++ give you a lower level of abstraction that, with increased complexity, provides a breadth of access to underlying machine functionality that are not necessarily exposed with other languages. Compared to C, C++ adds the convenience of a fully object oriented language(reduced development time) which can, potentially, add an additional performance cost. In terms of real world applications, I see these languages applied in the following domains:
C
C,C++
C# provides a managed memory model that adds a higher level of abstraction again. This level of abstraction adds convenience and improves development times, but complicates access to lower level APIs and makes specialized performance requirements problematic.
It is certainly possible to implement extremely high performance software in a managed memory environment, but awareness of the implications is essential.
The syntax of C# is certainly less demanding (and error prone) than C/C++ and has, for the initiated programmer, a shallower learning curve.
C#
Johannes Rössel makes the valid point that the use C# Pointers, Unsafe and Unchecked keywords break through the layer of abstraction upon which C# is built. I would emphasize that type of programming is the exception to most C# development scenarios and not a fundamental part of the language (as is the case with C/C++).
os.path.realpath(__file__)
will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.
SOLVED! I register to stockoverflow just to share to you the only solution (at least in ASP.NET/IE/FF/Chrome) that works! The idea is to replace innerHTML value of a div by its current innerHTML value.
Here is the HTML snippet:
<div class="content-2" id="divGranite">
<h2>Granite Purchase</h2>
<IFRAME runat="server" id="frameGranite" src="Jobs-granite.aspx" width="820px" height="300px" frameborder="0" seamless ></IFRAME>
</div>
And my Javascript code:
function refreshGranite() {
var iframe = document.getElementById('divGranite')
iframe.innerHTML = iframe.innerHTML;
}
Hope this helps.
This can be done with something like this:
# foo.py
class Foo:
def method_1():
results = uses_some_other_method()
# testing.py
from mock import patch
@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
foo = Foo()
the_value = foo.method_1()
assert the_value == "specific_value"
Here's a source that you can read: Patching in the wrong place
With all due respect to the great answers provided already, there are times that I simply want a thread-safe IList. Nothing advanced or fancy. Performance is important in many cases but at times that just isn't a concern. Yes, there are always going to be challenges without methods like "TryGetValue" etc, but most cases I just want something that I can enumerate without needing to worry about putting locks around everything. And yes, somebody can probably find some "bug" in my implementation that might lead to a deadlock or something (I suppose) but lets be honest: When it comes to multi-threading, if you don't write your code correctly, it is going deadlock anyway. With that in mind I decided to make a simple ConcurrentList implementation that provides these basic needs.
And for what its worth: I did a basic test of adding 10,000,000 items to regular List and ConcurrentList and the results were:
List finished in: 7793 milliseconds. Concurrent finished in: 8064 milliseconds.
public class ConcurrentList<T> : IList<T>, IDisposable
{
#region Fields
private readonly List<T> _list;
private readonly ReaderWriterLockSlim _lock;
#endregion
#region Constructors
public ConcurrentList()
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>();
}
public ConcurrentList(int capacity)
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>(capacity);
}
public ConcurrentList(IEnumerable<T> items)
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>(items);
}
#endregion
#region Methods
public void Add(T item)
{
try
{
this._lock.EnterWriteLock();
this._list.Add(item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public void Insert(int index, T item)
{
try
{
this._lock.EnterWriteLock();
this._list.Insert(index, item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public bool Remove(T item)
{
try
{
this._lock.EnterWriteLock();
return this._list.Remove(item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public void RemoveAt(int index)
{
try
{
this._lock.EnterWriteLock();
this._list.RemoveAt(index);
}
finally
{
this._lock.ExitWriteLock();
}
}
public int IndexOf(T item)
{
try
{
this._lock.EnterReadLock();
return this._list.IndexOf(item);
}
finally
{
this._lock.ExitReadLock();
}
}
public void Clear()
{
try
{
this._lock.EnterWriteLock();
this._list.Clear();
}
finally
{
this._lock.ExitWriteLock();
}
}
public bool Contains(T item)
{
try
{
this._lock.EnterReadLock();
return this._list.Contains(item);
}
finally
{
this._lock.ExitReadLock();
}
}
public void CopyTo(T[] array, int arrayIndex)
{
try
{
this._lock.EnterReadLock();
this._list.CopyTo(array, arrayIndex);
}
finally
{
this._lock.ExitReadLock();
}
}
public IEnumerator<T> GetEnumerator()
{
return new ConcurrentEnumerator<T>(this._list, this._lock);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new ConcurrentEnumerator<T>(this._list, this._lock);
}
~ConcurrentList()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
GC.SuppressFinalize(this);
this._lock.Dispose();
}
#endregion
#region Properties
public T this[int index]
{
get
{
try
{
this._lock.EnterReadLock();
return this._list[index];
}
finally
{
this._lock.ExitReadLock();
}
}
set
{
try
{
this._lock.EnterWriteLock();
this._list[index] = value;
}
finally
{
this._lock.ExitWriteLock();
}
}
}
public int Count
{
get
{
try
{
this._lock.EnterReadLock();
return this._list.Count;
}
finally
{
this._lock.ExitReadLock();
}
}
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
}
public class ConcurrentEnumerator<T> : IEnumerator<T>
{
#region Fields
private readonly IEnumerator<T> _inner;
private readonly ReaderWriterLockSlim _lock;
#endregion
#region Constructor
public ConcurrentEnumerator(IEnumerable<T> inner, ReaderWriterLockSlim @lock)
{
this._lock = @lock;
this._lock.EnterReadLock();
this._inner = inner.GetEnumerator();
}
#endregion
#region Methods
public bool MoveNext()
{
return _inner.MoveNext();
}
public void Reset()
{
_inner.Reset();
}
public void Dispose()
{
this._lock.ExitReadLock();
}
#endregion
#region Properties
public T Current
{
get { return _inner.Current; }
}
object IEnumerator.Current
{
get { return _inner.Current; }
}
#endregion
}
If all images are of the same format:
import cv2
import glob
images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]
For reading images of different formats:
import cv2
import glob
imdir = 'path/to/files/'
ext = ['png', 'jpg', 'gif'] # Add image formats here
files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
images = [cv2.imread(file) for file in files]
This will do the trick:
rectangle.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/transparent" />
<padding android:bottom="-14dp" android:left="-14dp" android:right="-14dp" android:top="-14dp" />
</shape>
circle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="oval"
android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke
android:width="15dp"
android:color="@color/verification_contact_background" />
</shape>
profile_image.xml ( The layerlist )
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/rectangle" />
<item android:drawable="@drawable/circle"/>
</layer-list>
Your layout
<ImageView
android:id="@+id/profile_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/default_org"
android:src="@drawable/profile_image"/>
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
My builder class for create ColorStateList
private class ColorStateListBuilder {
List<Integer> colors = new ArrayList<>();
List<int[]> states = new ArrayList<>();
public ColorStateListBuilder addState(int[] state, int color) {
states.add(state);
colors.add(color);
return this;
}
public ColorStateList build() {
return new ColorStateList(convertToTwoDimensionalIntArray(states),
convertToIntArray(colors));
}
private int[][] convertToTwoDimensionalIntArray(List<int[]> integers) {
int[][] result = new int[integers.size()][1];
Iterator<int[]> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++) {
result[i] = iterator.next();
}
return result;
}
private int[] convertToIntArray(List<Integer> integers) {
int[] result = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; iterator.hasNext(); i++) {
result[i] = iterator.next();
}
return result;
}
}
Example Using
ColorStateListBuilder builder = new ColorStateListBuilder();
builder.addState(new int[] { android.R.attr.state_pressed }, ContextCompat.getColor(this, colorRes))
.addState(new int[] { android.R.attr.state_selected }, Color.GREEN)
.addState(..., some color);
if(// some condition){
builder.addState(..., some color);
}
builder.addState(new int[] {}, colorNormal); // must add default state at last of all state
ColorStateList stateList = builder.build(); // ColorStateList created here
// textView.setTextColor(stateList);
Using Html Agility Pack as suggested by SLaks, this becomes very easy:
string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");
Here's the quote on AssemblyInfo.cs from MSDN:
You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (). For example, [assembly:AssemblyVersion("2.3.25.1")] indicates 2 as the major version, 3 as the minor version, 25 as the build number, and 1 as the revision number. A version number such as [assembly:AssemblyVersion("1.2.")] specifies 1 as the major version, 2 as the minor version, and accepts the default build and revision numbers. A version number such as [assembly:AssemblyVersion("1.2.15.*")] specifies 1 as the major version, 2 as the minor version, 15 as the build number, and accepts the default revision number. The default build number increments daily. The default revision number is random
This effectively says, if you put a 1.1.* into assembly info, only build number will autoincrement, and it will happen not after every build, but daily. Revision number will change every build, but randomly, rather than in an incrementing fashion.
This is probably enough for most use cases. If that's not what you're looking for, you're stuck with having to write a script which will autoincrement version # on pre-build step
The first example nearly always wins in my book:
if(foo)
{
}
It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...
I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.
As shaishab roy says, in the cheat sheet you can find the answer.
But in his answer, the given response was :
{path: '/home/...', name: 'Home', component: HomeComponent} {path: '/', redirectTo: ['Home']}, {path: '/user/...', name: 'User', component: UserComponent}, {path: '/404', name: 'NotFound', component: NotFoundComponent}, {path: '/*path', redirectTo: ['NotFound']}
For some reasons, it doesn't works on my side, so I tried instead :
{path: '/**', redirectTo: ['NotFound']}
and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).
The following approach worked for me:
Create a new personal access token in GitHub and configure the connection in IntelliJ as per link: https://www.jetbrains.com/help/idea/github.html
Then, on IntelliJ, Settings-Version Control-Git screen, unclick the "Use credential helper" option.
Then do an restart with cache invalidation (File - Invalidate Caches / Restart - Invalidate and Restart)
View mView;
mView.getContext();
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)
and reading a bigint at
BigInteger n = new BigInteger(input.readLine());
so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);
Constructor used: BigInteger(String val)
Aslo change while((str=input.readLine())!=null && str.length()!=0)
to
while((str=input.readLine())!=null)
see related post string to bigint
readLine()
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
see javadocs
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo