While the top-rated answer is correct, here is an alternate use case i.e if you are iterating over an object and want to create an array in the end. Use .map
instead of forEach
const newObj = Object.keys(obj).map(el => {
//ell will hold keys
// Getting the value of the keys should be as simple as obj[el]
})
Adding the following to my .bash_profile worked for me:
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
I ran into a problem with this as well as my JUnit assertEquals were failing comparing Dates to Hibernate emitted 'java.util.Date' types (which as described in the question are really Timestamps). It turns out that by changing the mapping to 'date' rather than 'java.util.Date' Hibernate generates java.util.Date members. I am using an XML mapping file with Hibernate version 4.1.12.
This version emits 'java.util.Timestamp':
<property name="date" column="DAY" type="java.util.Date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
This version emits 'java.util.Date':
<property name="date" column="DAY" type="date" unique-key="KONSTRAINT_DATE_IDX" unique="false" not-null="true" />
Note, however, if Hibernate is used to generate the DDL, then these will generate different SQL types (Date for 'date' and Timestamp for 'java.util.Date').
You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):
<div id="printOption">
<a href="javascript:void();"
onclick="document.getElementById('printOption').style.visibility = 'hidden';
document.print();
return true;">
Print
</a>
</div>
The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).
The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption
ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.
Time. .Now
includes the 09:23:12 or whatever; .Today
is the date-part only (at 00:00:00 on that day).
So use .Now
if you want to include the time, and .Today
if you just want the date!
.Today
is essentially the same as .Now.Date
I ended up writing a small script that adds the certificates to the keystores, so it is much easier to use.
You can get the latest version from https://github.com/ssbarnea/keytool-trust
#!/bin/bash
# version 1.0
# https://github.com/ssbarnea/keytool-trust
REMHOST=$1
REMPORT=${2:-443}
KEYSTORE_PASS=changeit
KEYTOOL="sudo keytool"
# /etc/java-6-sun/security/cacerts
for CACERTS in /usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts \
/usr/lib/jvm/java-7-oracle/jre/lib/security/cacerts \
"/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/cacerts" \
"/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/lib/security/cacerts"
do
if [ -e "$CACERTS" ]
then
echo --- Adding certs to $CACERTS
# FYI: the default keystore is located in ~/.keystore
if [ -z "$REMHOST" ]
then
echo "ERROR: Please specify the server name to import the certificatin from, eventually followed by the port number, if other than 443."
exit 1
fi
set -e
rm -f $REMHOST:$REMPORT.pem
if openssl s_client -connect $REMHOST:$REMPORT 1>/tmp/keytool_stdout 2>/tmp/output </dev/null
then
:
else
cat /tmp/keytool_stdout
cat /tmp/output
exit 1
fi
if sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' </tmp/keytool_stdout > /tmp/$REMHOST:$REMPORT.pem
then
:
else
echo "ERROR: Unable to extract the certificate from $REMHOST:$REMPORT ($?)"
cat /tmp/output
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT >/dev/null
then
echo "Key of $REMHOST already found, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
fi
if $KEYTOOL -list -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -keystore "$CACERTS" >/dev/null
then
echo "Key of $REMHOST already found in cacerts, skipping it."
else
$KEYTOOL -import -trustcacerts -noprompt -keystore "$CACERTS" -storepass ${KEYSTORE_PASS} -alias $REMHOST:$REMPORT -file /tmp/$REMHOST:$REMPORT.pem
fi
fi
done
```
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
./
refers to the current working directory, except in the require()
function. When using require()
, it translates ./
to the directory of the current file called. __dirname
is always the directory of the current file.
For example, with the following file structure
/home/user/dir/files/config.json
{
"hello": "world"
}
/home/user/dir/files/somefile.txt
text file
/home/user/dir/dir.js
var fs = require('fs');
console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));
If I cd
into /home/user/dir
and run node dir.js
I will get
{ hello: 'world' }
text file
But when I run the same script from /home/user/
I get
{ hello: 'world' }
Error: ENOENT, no such file or directory './files/somefile.txt'
at Object.openSync (fs.js:228:18)
at Object.readFileSync (fs.js:119:15)
at Object.<anonymous> (/home/user/dir/dir.js:4:16)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
at EventEmitter._tickCallback (node.js:192:40)
Using ./
worked with require
but not for fs.readFileSync
. That's because for fs.readFileSync
, ./
translates into the cwd (in this case /home/user/
). And /home/user/files/somefile.txt
does not exist.
In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.
Look carefully at your output:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^
I've highlighted the "5", "9", "5" of your original string. The Python join()
method is a string method, and takes a list of things to join with the string. A simpler example might help explain:
>>> ",".join(["a", "b", "c"])
'a,b,c'
The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].
It appears that you're looking for +
instead:
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
The Div that has to take the remaining space has to be a class.. The other divs can be id(s) but they must have width..
CSS:
#main_center {
width:1000px;
height:100px;
padding:0px 0px;
margin:0px auto;
display:block;
}
#left {
width:200px;
height:100px;
padding:0px 0px;
margin:0px auto;
background:#c6f5c6;
float:left;
}
.right {
height:100px;
padding:0px 0px;
margin:0px auto;
overflow:hidden;
background:#000fff;
}
.clear {
clear:both;
}
HTML:
<body>
<div id="main_center">
<div id="left"></div>
<div class="right"></div>
<div class="clear"></div>
</div>
</body>
The following link has the code in action, which should solve the remaining area coverage issue.
Inline version, works for Outlook Desktop:
<ul style="list-style:square;">
<li style="color:red;"><span style="color:black;">Lorem.</span></li>
<li style="color:red;"><span style="color:black;">Lorem.</span></li>
</ul>
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
The Java 8 streams API lacks the features of getting the index of a stream element as well as the ability to zip streams together. This is unfortunate, as it makes certain applications (like the LINQ challenges) more difficult than they would be otherwise.
There are often workarounds, however. Usually this can be done by "driving" the stream with an integer range, and taking advantage of the fact that the original elements are often in an array or in a collection accessible by index. For example, the Challenge 2 problem can be solved this way:
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
List<String> nameList =
IntStream.range(0, names.length)
.filter(i -> names[i].length() <= i)
.mapToObj(i -> names[i])
.collect(toList());
As I mentioned above, this takes advantage of the fact that the data source (the names array) is directly indexable. If it weren't, this technique wouldn't work.
I'll admit that this doesn't satisfy the intent of Challenge 2. Nonetheless it does solve the problem reasonably effectively.
EDIT
My previous code example used flatMap
to fuse the filter and map operations, but this was cumbersome and provided no advantage. I've updated the example per the comment from Holger.
For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.
Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.
With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.
Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .
You have to use the viewWithTag
function to find the view with the given tag
.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let point = touch.locationInView(self.view)
if let viewWithTag = self.view.viewWithTag(100) {
print("Tag 100")
viewWithTag.removeFromSuperview()
} else {
print("tag not found")
}
}
I created JS performance test for it http://jsperf.com/split-and-join-vs-replace2
the printf() function is used to print both strings and variables to the screen while the puts() function only permits you to print a string only to your screen.
Nice article explaining the basics (does not cover line breaks, however).
A Whole Bunch of Amazing Stuff Pseudo Elements Can Do
If you need to have two inline elements where one breaks into the next line within another element, you can accomplish this by adding a pseudo-element :after with content:'\A' and white-space: pre
HTML
<h3>
<span class="label">This is the main label</span>
<span class="secondary-label">secondary label</span>
</h3>
CSS
.label:after {
content: '\A';
white-space: pre;
}
For something reusable:
template<template <typename> class P = std::less >
struct compare_pair_second {
template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {
return P<T2>()(left.second, right.second);
}
};
You can use it as
std::sort(foo.begin(), foo.end(), compare_pair_second<>());
or
std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());
You can add like this as well, if you want the date 5 days from a specific date :
You have a variable with a date like this (gotten from an input or DB or just hard coded):
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
echo $fiveDays; // Will output 2015-06-20
Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.
Note that whenever you change the default ports, your browser will not know about that. 80
and 443
seem to be standard in some way, so for example, if you changed 80
to 8080
, you'll have to access your websites this way then:
localhost:8080/path_to_your_website.php
It's an old post but I none of this solution worked for me so I'm posting my solution if anyone find this helpful.
I just had the same problem.
In my case the control I needed to disable was a user control with child dropdowns which I could disable in IE but not in chrome.
my solution was to disable each child object, not just the usercontrol, with that code:
$('#controlName').find('*').each(function () { $(this).attr("disabled", true); })
It's working for me in chrome now.
Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.
Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2);
So, Func
is a built-in delegate which brings some functional programming features and helps reduce code verbosity.
The easiest solution is to simply style the element you're inserting the text into with the following CSS property:
white-space: pre-wrap;
This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>
. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).
Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML
) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.append(postText);_x000D_
var card = document.createElement('div');_x000D_
card.append(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Note that, like your original code, the snippet above uses append()
and prepend()
. As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:
element.append(otherElement)
can be replaced with element.appendChild(otherElement)
;element.prepend(otherElement)
can be replaced with element.insertBefore(otherElement, element.firstChild)
;element.append(stringOfText)
can be replaced with element.appendChild(document.createTextNode(stringOfText))
;element.prepend(stringOfText)
can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild)
;element
is empty, both element.append(stringOfText)
and element.prepend(stringOfText)
can simply be replaced with element.textContent = stringOfText
.Here's the same snippet as above, but without using append()
or prepend()
:
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.textContent = postText;_x000D_
var card = document.createElement('div');_x000D_
card.appendChild(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
white-space: pre-wrap; /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Ps. If you really want to do this without using the CSS white-space
property, an alternative solution would be to explicitly replace any newline characters in the text with <br>
HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, &
and <
) in the text before you do this replacement.
Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:
var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');
document.getElementById('post-button').addEventListener('click', function () {_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.textContent = postText;_x000D_
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n'); // <-- THIS FIXES THE LINE BREAKS_x000D_
var card = document.createElement('div');_x000D_
card.appendChild(post);_x000D_
var cardStack = document.getElementById('card-stack');_x000D_
cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.
The then()
method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:
getFeed().then(function(data) { vm.feed = data;});
The then()
function returns the promise with a resolved value of the previous then()
callback, allowing you the pass the value to subsequent callbacks:
promiseB = promiseA.then(function(result) {
return result + 1;
});
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1
What about combining coalesce
and nullif
?
SET @PreviousStartDate = coalesce(nullif(@PreviousStartDate, ''), '01/01/2010')
In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.
Further explanation in this article.
The min sdk version is the minimum version of the Android operating system required to run your application.
The target sdk version is the version of Android that your app was created to run on.
The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.
Usually the compile sdk version and the target sdk version are the same.
Well, I think this code is working. It will not delete the folder and you can use this code to delete files having the particular extension.
import os
import glob
files = glob.glob(r'path/*')
for items in files:
os.remove(items)
This line looks suspicious:
invaders[i] = inv;
You're never incrementing i
, so you keep assigning to invaders[0]
. If this is just an error you made when reducing your code to the example, check how you calculate i
in the real code; you could be exceeding the size of invaders
.
If as your comment suggests, you're creating 55 invaders
, then check that invaders
has been initialised correctly to handle this number.
The commands dict.items()
, dict.keys()
and dict.values()
return a copy of the dictionary's list of (k, v)
pair, keys and values.
This could take a lot of memory if the copied list is very large.
The commands dict.iteritems()
, dict.iterkeys()
and dict.itervalues()
return an iterator over the dictionary’s (k, v)
pair, keys and values.
The commands dict.viewitems()
, dict.viewkeys()
and dict.viewvalues()
return the view objects, which can reflect the dictionary's changes.
(I.e. if you del
an item or add a (k,v)
pair in the dictionary, the view object can automatically change at the same time.)
$ python2.7
>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>>
>>>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>>
>>>
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>
In Py3.x, things are more clean, since there are only dict.items()
, dict.keys()
and dict.values()
available, which return the view objects just as dict.viewitems()
in Py2.x did.
Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview)
:
$ python3.3
>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>
This message has been E_STRICT
for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING
. Since E_WARNING
messages are useful, you don't want to disable them completely.
To get rid of this warning, you must use this code:
if (!isset($res))
$res = new stdClass();
$res->success = false;
This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing - unfortunatelly with warning now - implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn't. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.
select TABLE_NAME from user_tables;
Above query will give you the names of all tables present in that user;
sys.path
is only searched for Python modules. For dynamic linked libraries, the paths searched must be in LD_LIBRARY_PATH
. Check if your LD_LIBRARY_PATH
includes /usr/local/lib
, and if it doesn't, add it and try again.
Some more information (source):
In Linux, the environment variable LD_LIBRARY_PATH is a colon-separated set of directories where libraries should be searched for first, before the standard set of directories; this is useful when debugging a new library or using a nonstandard library for special purposes. The environment variable LD_PRELOAD lists shared libraries with functions that override the standard set, just as /etc/ld.so.preload does. These are implemented by the loader /lib/ld-linux.so. I should note that, while LD_LIBRARY_PATH works on many Unix-like systems, it doesn't work on all; for example, this functionality is available on HP-UX but as the environment variable SHLIB_PATH, and on AIX this functionality is through the variable LIBPATH (with the same syntax, a colon-separated list).
Update: to set LD_LIBRARY_PATH
, use one of the following, ideally in your ~/.bashrc
or equivalent file:
export LD_LIBRARY_PATH=/usr/local/lib
or
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of export.
I would also add:
Err
object is the closest you have to an exception objectErr.Raise
And just for fun:
On Error Resume Next
is the devil incarnate and to be avoided, as it silently hides errorsI know this post is old, but if any of you still looking for a simpler solution.
#container .left,
#container .right {
display: inline-block;
}
#container .left {
width: 20%;
float: left;
}
#container .right {
width: 80%;
float: right;
}
There is also the date versioning scheme, eg: YYYY.MM
, YY.MM
, YYYYMMDD
It is quite informative because a first look gives an impression about the release date. But i prefer the x.y.z scheme, because i always want to know a product's exact point in its life cycle (Major.minor.release)
1) Right Click on **Solution Explorer**
2) Go to the **Properties**
3) Expand **Common Properties**
4) Select **Start Up Project**
5) click the radio button (**Single Start_up Project**)
6) select your Project name
7) Then Debug Your project
Inline items cannot have a width. You have to use display: block
or display:inline-block
, but the latter is not supported everywhere.
Just select range row from df like this
row_count = df.shape[0]
split_point = int(row_count*1/5)
test_data, train_data = df[:split_point], df[split_point:]
try following to see all instances of python
whereis python
which python
Then remove all instances using:
sudo apt autoremove python
repeat sudo apt autoremove python(for all versions) that should do it, then install Anaconda and manage Pythons however you like if you need to reinstall it.
Here's my solution if you created the repository with some default readme file
or license
git init
git add -A
git commit -m "initial commit"
git remote add origin https://<git-userName>@github.com/xyz.git //Add your username so it will avoid asking username each time before you push your code
git fetch
git pull https://github.com/xyz.git <branch>
git push origin <branch>
I expanded the code, because it's not told me the 'record number
', and I must to refind it.
CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)
CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
,@TableShortName nvarchar(256)
,@TableKeys nvarchar(512)
,@SQL nvarchar(3830)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
-- Scan Tables
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
Set @TableShortName=PARSENAME(@TableName, 1)
-- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***
-- LOOK Key Fields, Set Key Columns
SET @TableKeys=''
SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
FROM syscolumns
WHERE [id] IN (
SELECT [id]
FROM sysobjects
WHERE [name] = @TableShortName)
AND colid IN (
SELECT SIK.colid
FROM sysindexkeys SIK
JOIN sysobjects SO ON
SIK.[id] = SO.[id]
WHERE
SIK.indid = 1
AND SO.[name] = @TableShortName)
If @TableKeys<>''
SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
-- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***
-- Search in Columns
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
) -- Set ColumnName
IF @ColumnName IS NOT NULL
BEGIN
SET @SQL='
SELECT
''' + @TableName + '''
,'+@TableKeys+'
,''' + @ColumnName + '''
,LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
--Print @SQL -- *** DEBUG LINE ***
INSERT INTO #Results
Exec (@SQL)
END -- IF ColumnName
END -- While Table and Column
END --While Table
SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
END
int mid = 10;
for (double j = 2 * mid; j >= 0; j = j - 0.1) {
if (j == mid) {
System.out.println("Never happens"); // is NOT printed
}
if (Double.compare(j, mid) == 0) {
System.out.println("No way!"); // is NOT printed
}
if (Math.abs(j - mid) < 1e-6) {
System.out.println("Ha!"); // printed
}
}
System.out.println("Gotcha!");
I Had the same problem.
The solution for me is:
You must have the same version of: Microsoft.ReportViewer.ProcessingObjectModel registred in C:\Windows\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel, like you have registraded in web.config in developer server:
In my case i was only registred the 13. version in my prodution server and i have the 12. version in developer server.
the solution is install the version 12. in the prodution server too
the version 12. :
Then now i have the version 12. in the prodution and the report work fine.
*** Remember to reset your IIS after instalation
Ensure the fields named in the table adapter query match those in the query you have defined. The DAL does not seem to like mismatches. This will typically happen to your sprocs and queries after you add a new field to a table.
If you have changed the length of a varchar field in the database and the XML contained in the XSS file has not picked it up, find the field name and attribute definition in the XML and change it manually.
Remove primary keys from select lists in table adapters if they are not related to the data being returned.
Run your query in SQL Management Studio and ensure there are not duplicate records being returned. Duplicate records can generate duplicate primary keys which will cause this error.
SQL unions can spell trouble. I modified one table adapter by adding a ‘please select an employee’ record preceding the others. For the other fields I provided dummy data including, for example, strings of length one. The DAL inferred the schema from that initial record. Records following with strings of length 12 failed.
Here's a LESS mixin for transitioning two properties at once:
.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
-webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}
How about something like:
<script src='http://code.jquery.com/jquery-latest.js'></script>
function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,' '); }
I would say use an RDBMS if you need complex transactions. Otherwise I would go with MongoDB - more flexible to work with and you know it can scale when you need to. (I'm biased though - I work on the MongoDB project)
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
String is a reference type, so you don't need to (and cannot) use Nullable<T>
here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.
slate
is a project that makes it very simple to use PDFMiner from a library:
>>> with open('example.pdf') as f:
... doc = slate.PDF(f)
...
>>> doc
[..., ..., ...]
>>> doc[1]
'Text from page 2...'
ooxml for dealing the .xlsx files and the ooxml refers to the xml, hence we will be needed to refer the below three dependedncies in the pom.xml for the
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
<exclusions>
<exclusion>
<artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId>
</exclusion>
</exclusions>
</dependency>
Taking Shiraz's idea and running with it...
In your application, are you explicitly defining a domain User Account and Password to access AD?
When you are executing the application explicitly it may be inherently using your credentials (your currently logged in domain account) to interrogate AD. However, when calling the application from the script, I'm not sure if the application is in the System context.
A VBScript example would be as follows:
Dim objConnection As ADODB.Connection
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Properties("User ID") = "MyDomain\MyAccount"
objConnection.Properties("Password") = "MyPassword"
objConnection.Open "Active Directory Provider"
If this works, of course it would be best practice to create and use a service account specifically for this task, and to deny interactive login to that account.
You can do this in your code:
final ListView lv = (ListView) convertView.findViewById(R.id.list_view);
for (int i = 0; i < lv.getChildCount(); i++) {
((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}
I have found a solution by myself. I use the PDANet tool to find the driver automatically.
UPDATE: This answer is in response to the original question, Does Java SE 8 have Pairs or Tuples? (And implicitly, if not, why not?) The OP has updated the question with a more complete example, but it seems like it can be solved without using any kind of Pair structure. [Note from OP: here is the other correct answer.]
The short answer is no. You either have to roll your own or bring in one of the several libraries that implements it.
Having a Pair
class in Java SE was proposed and rejected at least once. See this discussion thread on one of the OpenJDK mailing lists. The tradeoffs are not obvious. On the one hand, there are many Pair implementations in other libraries and in application code. That demonstrates a need, and adding such a class to Java SE will increase reuse and sharing. On the other hand, having a Pair class adds to the temptation of creating complicated data structures out of Pairs and collections without creating the necessary types and abstractions. (That's a paraphrase of Kevin Bourillion's message from that thread.)
I recommend everybody read that entire email thread. It's remarkably insightful and has no flamage. It's quite convincing. When it started I thought, "Yeah, there should be a Pair class in Java SE" but by the time the thread reached its end I had changed my mind.
Note however that JavaFX has the javafx.util.Pair class. JavaFX's APIs evolved separately from the Java SE APIs.
As one can see from the linked question What is the equivalent of the C++ Pair in Java? there is quite a large design space surrounding what is apparently such a simple API. Should the objects be immutable? Should they be serializable? Should they be comparable? Should the class be final or not? Should the two elements be ordered? Should it be an interface or a class? Why stop at pairs? Why not triples, quads, or N-tuples?
And of course there is the inevitable naming bikeshed for the elements:
One big issue that has hardly been mentioned is the relationship of Pairs to primitives. If you have an (int x, int y)
datum that represents a point in 2D space, representing this as Pair<Integer, Integer>
consumes three objects instead of two 32-bit words. Furthermore, these objects must reside on the heap and will incur GC overhead.
It would seem clear that, like Streams, it would be essential for there to be primitive specializations for Pairs. Do we want to see:
Pair
ObjIntPair
ObjLongPair
ObjDoublePair
IntObjPair
IntIntPair
IntLongPair
IntDoublePair
LongObjPair
LongIntPair
LongLongPair
LongDoublePair
DoubleObjPair
DoubleIntPair
DoubleLongPair
DoubleDoublePair
Even an IntIntPair
would still require one object on the heap.
These are, of course, reminiscent of the proliferation of functional interfaces in the java.util.function
package in Java SE 8. If you don't want a bloated API, which ones would you leave out? You could also argue that this isn't enough, and that specializations for, say, Boolean
should be added as well.
My feeling is that if Java had added a Pair class long ago, it would have been simple, or even simplistic, and it wouldn't have satisfied many of the use cases we are envisioning now. Consider that if Pair had been added in the JDK 1.0 time frame, it probably would have been mutable! (Look at java.util.Date.) Would people have been happy with that? My guess is that if there were a Pair class in Java, it would be kinda-sort-not-really-useful and everybody will still be rolling their own to satisfy their needs, there would be various Pair and Tuple implementations in external libraries, and people would still be arguing/discussing about how to fix Java's Pair class. In other words, kind of in the same place we're at today.
Meanwhile, some work is going on to address the fundamental issue, which is better support in the JVM (and eventually the Java language) for value types. See this State of the Values document. This is preliminary, speculative work, and it covers only issues from the JVM perspective, but it already has a fair amount of thought behind it. Of course there are no guarantees that this will get into Java 9, or ever get in anywhere, but it does show the current direction of thinking on this topic.
I don't think there's a native trim()
method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
private JLabel label;
private JTextField field;
public Test()
{
super("The title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 90));
((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
setLayout(new FlowLayout());
JButton btn = new JButton("Change");
btn.setActionCommand("myButton");
btn.addActionListener(this);
label = new JLabel("flag");
field = new JTextField(5);
add(field);
add(btn);
add(label);
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("myButton"))
{
label.setText(field.getText());
}
}
public static void main(String[] args)
{
new Test();
}
}
Here's a simple circle_background.xml for pre-material:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="@color/color_accent_dark" />
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="@color/color_accent" />
</shape>
</item>
</selector>
You can use with the attribute 'android:background="@drawable/circle_background"
in your button's layout definition
Reasons of the warning are already described, but how would you fix the warning? You have to seal either class or virtual member.
class B
{
protected virtual void Foo() { }
}
class A : B
{
public A()
{
Foo(); // warning here
}
}
You can seal class A:
sealed class A : B
{
public A()
{
Foo(); // no warning
}
}
Or you can seal method Foo:
class A : B
{
public A()
{
Foo(); // no warning
}
protected sealed override void Foo()
{
base.Foo();
}
}
number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)
output: 0.55
You can also name your foreign key constraint by using:
CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)
My preferred way to make Raise button with match parent is that wrap it with Container. below is sample code.
Container(
width: double.infinity,
child: RaisedButton(
onPressed: () {},
color: Colors.deepPurpleAccent[100],
child: Text(
"Continue",
style: TextStyle(color: Colors.white),
),
),
)
The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.
Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray()
will tell you.
There are a number of ways to look at a date difference, and more when comparing date/times. Here's what I use to get the difference between two dates formatted as "HH:MM:SS":
ElapsedTime AS
RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
I used this for a calculated column, but you could trivially rewrite it as a UDF or query calculation. Note that this logic rounds down fractional seconds; 00:00.00 to 00:00.999 is considered zero seconds, and displayed as "00:00:00".
If you anticipate that periods may be more than a few days long, this code switches to D:HH:MM:SS format when needed:
ElapsedTime AS
CASE WHEN DATEDIFF(S, StartDate, EndDate) >= 359999
THEN
CAST(DATEDIFF(S, StartDate, EndDate) / 86400 AS VARCHAR(7)) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 86400 / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
ELSE
RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) / 3600 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 3600 / 60 AS VARCHAR(2)), 2) + ':'
+ RIGHT('0' + CAST(DATEDIFF(S, StartDate, EndDate) % 60 AS VARCHAR(2)), 2)
END
the aim of balanced tree is to reach the leaf in a minimum of traversal (min height). The degree of the tree is the number of branches minus 1. A Balanced tree may be not Binary.
If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?
Yes.
Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?
Sure:
var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();
will give you the expected result:
foo=bar%3c%3e%26-baz&bar=bazinga
You might also find the UriBuilder
class useful:
var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();
will give you the expected result:
http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga
that you could more than safely feed to your HttpClient.GetAsync
method.
Basic HTML
<input type="number" />
Basic bootstrap
<input class="form-control" type="number" value="42" id="my-id">
I have found that this works:
$(document).ready(function(){
$('textarea').bind('input propertychange', function() {
//do your update here
}
})
You can also face this situation if your upstream server uses a domain name, and its IP address changes (e.g.: your upstream points to an AWS Elastic Load Balancer)
The problem is that nginx will resolve the IP address once, and keep it cached for subsequent requests until the configuration is reloaded.
You can tell nginx to use a name server to re-resolve the domain once the cached entry expires:
location /mylocation {
# use google dns to resolve host after IP cached expires
resolver 8.8.8.8;
set $upstream_endpoint http://your.backend.server/;
proxy_pass $upstream_endpoint;
}
The docs on proxy_pass explain why this trick works:
Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.
Kudos to "Nginx with dynamic upstreams" (tenzer.dk) for the detailed explanation, which also contains some relevant information on a caveat of this approach regarding forwarded URIs.
Just specify it in shared.loader
or common.loader
property of /conf/catalina.properties
.
The issue with the conversion (the reason it's giving you a ffffff at the end) is because your hex integer (that you are using the & binary operator with) is interpreted as being signed. Cast it to an unsigned integer, and you'll be fine.
By changing a code of Francisco Cabezas, I got the following:
private int selectedRow = -1;
...
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
parent.getChildAt(position).setBackgroundResource(R.color.orange);
if (selectedRow != -1 && selectedRow != position) {
parent.getChildAt(selectedRow).setBackgroundResource(R.color.black);
}
selectedRow = position;
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
select propety
Row Source Type => Value List
Code :
ListbName.ColumnCount=2
ListbName.AddItem "value column1;value column2"
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function f is a call to a function g (Note: g can be f). The key here is that f no longer needs stack space - it simply calls g and then returns whatever g would return. In this case the optimization can be made that g just runs and returns whatever value it would have to the thing that called f.
This optimization can make recursive calls take constant stack space, rather than explode.
Example: this factorial function is not TCOptimizable:
def fact(n):
if n == 0:
return 1
return n * fact(n-1)
This function does things besides call another function in its return statement.
This below function is TCOptimizable:
def fact_h(n, acc):
if n == 0:
return acc
return fact_h(n-1, acc*n)
def fact(n):
return fact_h(n, 1)
This is because the last thing to happen in any of these functions is to call another function.
There's also a DataSetExtension method called "AsEnumerable()" (in System.Data) that takes a DataTable and returns an Enumerable. See the MSDN doc for more details, but it's basically as easy as:
dataTable.AsEnumerable()
The downside is that it's enumerating DataRow, not your custom class. A "Select()" LINQ call could convert the row data, however:
private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
return dataTable.AsEnumerable().Select(row => new TankReading
{
TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
TankID = Convert.ToInt32(row["TankID"]),
ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
ReadingInches = Convert.ToInt32(row["ReadingInches"]),
MaterialNumber = row["MaterialNumber"].ToString(),
EnteredBy = row["EnteredBy"].ToString(),
ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
MaterialID = Convert.ToInt32(row["MaterialID"]),
Submitted = Convert.ToBoolean(row["Submitted"]),
});
}
update 2 ::slotted
::slotted
is now supported by all new browsers and can be used with ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
update 1 ::ng-deep
/deep/
was deprecated and replaced by ::ng-deep
.
::ng-deep
is also already marked deprecated, but there is no replacement available yet.
When ViewEncapsulation.Native
is properly supported by all browsers and supports styling accross shadow DOM boundaries, ::ng-deep
will probably be discontinued.
original
Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using [innerHTML]
these classes are not added and the rewritten CSS doesn't match.
As a workaround try
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector {
background-color: blue;
}
index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
background-color: green;
}
>>>
(and the equivalent/deep/
but /deep/
works better with SASS) and ::shadow
were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated
which is the default in Angular2. They probably also work with ViewEncapsulation.None
but are then only ignored because they are not necessary.
These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.
Another approach is to use
@Component({
...
encapsulation: ViewEncapsulation.None,
})
for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be all components in your application)
Update
Note: The command in the question uses Start-Process
, which prevents direct capturing of the target program's output. Generally, do not use Start-Process
to execute console applications synchronously - just invoke them directly, as in any shell. Doing so keeps the application connected to the calling console's standard streams, allowing its output to be captured by simple assignment $output = netdom ...
, as detailed below.
Fundamentally, capturing output from external programs works the same as with PowerShell-native commands (you may want a refresher on how to execute external programs; <command>
is a placeholder for any valid command below):
$cmdOutput = <command> # captures the command's success stream / stdout output
Note that $cmdOutput
receives an array of objects if <command>
produces more than 1 output object, which in the case of an external program means a string[1] array containing the program's output lines.
If you want to make sure that the result is always an array - even if only one object is output, type-constrain the variable as an array, or wrap the command in @()
, the array-subexpression operator):
[array] $cmdOutput = <command> # or: $cmdOutput = @(<command>)
By contrast, if you want $cmdOutput
to always receive a single - potentially multi-line - string, use Out-String
, though note that a trailing newline is invariably added:
# Note: Adds a trailing newline.
$cmdOutput = <command> | Out-String
With calls to external programs - which by definition only ever return strings in PowerShell[1] - you can avoid that by using the -join
operator instead:
# NO trailing newline.
$cmdOutput = (<command>) -join "`n"
Note: For simplicity, the above uses "`n"
to create Unix-style LF-only newlines, which PowerShell happily accepts on all platforms; if you need platform-appropriate newlines (CRLF on Windows, LF on Unix), use [Environment]::NewLine
instead.
To capture output in a variable and print to the screen:
<command> | Tee-Object -Variable cmdOutput # Note how the var name is NOT $-prefixed
Or, if <command>
is a cmdlet or advanced function, you can use common parameter
-OutVariable
/ -ov
:
<command> -OutVariable cmdOutput # cmdlets and advanced functions only
Note that with -OutVariable
, unlike in the other scenarios, $cmdOutput
is always a collection, even if only one object is output. Specifically, an instance of the array-like [System.Collections.ArrayList]
type is returned.
See this GitHub issue for a discussion of this discrepancy.
To capture the output from multiple commands, use either a subexpression ($(...)
) or call a script block ({ ... }
) with &
or .
:
$cmdOutput = $(<command>; ...) # subexpression
$cmdOutput = & {<command>; ...} # script block with & - creates child scope for vars.
$cmdOutput = . {<command>; ...} # script block with . - no child scope
Note that the general need to prefix with &
(the call operator) an individual command whose name/path is quoted - e.g., $cmdOutput = & 'netdom.exe' ...
- is not related to external programs per se (it equally applies to PowerShell scripts), but is a syntax requirement: PowerShell parses a statement that starts with a quoted string in expression mode by default, whereas argument mode is needed to invoke commands (cmdlets, external programs, functions, aliases), which is what &
ensures.
The key difference between $(...)
and & { ... }
/ . { ... }
is that the former collects all input in memory before returning it as a whole, whereas the latter stream the output, suitable for one-by-one pipeline processing.
Redirections also work the same, fundamentally (but see caveats below):
$cmdOutput = <command> 2>&1 # redirect error stream (2) to success stream (1)
However, for external commands the following is more likely to work as expected:
$cmdOutput = cmd /c <command> '2>&1' # Let cmd.exe handle redirection - see below.
Considerations specific to external programs:
External programs, because they operate outside PowerShell's type system, only ever return strings via their success stream (stdout); similarly, PowerShell only ever sends strings to external programs via the pipeline.[1]
On sending data via the pipeline to external programs, PowerShell uses the encoding stored in the $OutVariable
preference variable; which in Windows PowerShell defaults to ASCII(!) and in PowerShell [Core] to UTF-8.
On receiving data from an external program, PowerShell uses the encoding stored in [Console]::OutputEncoding
to decode the data, which in both PowerShell editions defaults to the system's active OEM code page.
See this answer for more information; this answer discusses the still-in-beta (as of this writing) Windows 10 feature that allows you to set UTF-8 as both the ANSI and the OEM code page system-wide.
If the output contains more than 1 line, PowerShell by default splits it into an array of strings. More accurately, the output lines are stored in an array of type [System.Object[]]
whose elements are strings ([System.String]
).
If you want the output to be a single, potentially multi-line string, use the -join
operator (you can alternatively pipe to Out-String
, but that invariably adds a trailing newline):
$cmdOutput = (<command>) -join [Environment]::NewLine
Merging stderr into stdout with 2>&1
, so as to also capture it as part of the success stream, comes with caveats:
To do this at the source, let cmd.exe
handle the redirection, using the following idioms (works analogously with sh
on Unix-like platforms):
$cmdOutput = cmd /c <command> '2>&1' # *array* of strings (typically)
$cmdOutput = (cmd /c <command> '2>&1') -join "`r`n" # single string
cmd /c
invokes cmd.exe
with command <command>
and exits after <command>
has finished.
Note the single quotes around 2>&1
, which ensures that the redirection is passed to cmd.exe
rather than being interpreted by PowerShell.
Note that involving cmd.exe
means that its rules for escaping characters and expanding environment variables come into play, by default in addition to PowerShell's own requirements; in PS v3+ you can use special parameter --%
(the so-called stop-parsing symbol) to turn off interpretation of the remaining parameters by PowerShell, except for cmd.exe
-style environment-variable references such as %PATH%
.
Note that since you're merging stdout and stderr at the source with this approach, you won't be able to distinguish between stdout-originated and stderr-originated lines in PowerShell; if you do need this distinction, use PowerShell's own 2>&1
redirection - see below.
Use PowerShell's 2>&1
redirection to know which lines came from what stream:
Stderr output is captured as error records ([System.Management.Automation.ErrorRecord]
), not strings, so the output array may contain a mix of strings (each string representing a stdout line) and error records (each record representing a stderr line). Note that, as requested by 2>&1
, both the strings and the error records are received through PowerShell's success output stream).
Note: The following only applies to Windows PowerShell - these problems have been corrected in PowerShell [Core] v6+, though the filtering technique by object type shown below ($_ -is [System.Management.Automation.ErrorRecord]
) can also be useful there.
In the console, the error records print in red, and the 1st one by default produces multi-line display, in the same format that a cmdlet's non-terminating error would display; subsequent error records print in red as well, but only print their error message, on a single line.
When outputting to the console, the strings typically come first in the output array, followed by the error records (at least among a batch of stdout/stderr lines output "at the same time"), but, fortunately, when you capture the output, it is properly interleaved, using the same output order you would get without 2>&1
; in other words: when outputting to the console, the captured output does NOT reflect the order in which stdout and stderr lines were generated by the external command.
If you capture the entire output in a single string with Out-String
, PowerShell will add extra lines, because the string representation of an error record contains extra information such as location (At line:...
) and category (+ CategoryInfo ...
); curiously, this only applies to the first error record.
To work around this problem, apply the .ToString()
method to each output object instead of piping to Out-String
:
$cmdOutput = <command> 2>&1 | % { $_.ToString() }
;
in PS v3+ you can simplify to:
$cmdOutput = <command> 2>&1 | % ToString
(As a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console.)
Alternatively, filter the error records out and send them to PowerShell's error stream with Write-Error
(as a bonus, if the output isn't captured, this produces properly interleaved output even when printing to the console):
$cmdOutput = <command> 2>&1 | ForEach-Object {
if ($_ -is [System.Management.Automation.ErrorRecord]) {
Write-Error $_
} else {
$_
}
}
[1] As of PowerShell 7.1, PowerShell knows only strings when communicating with external programs. There is generally no concept of raw byte data in a PowerShell pipeline. If you want raw byte data returned from an external program, you must shell out to cmd.exe /c
(Windows) or sh -c
(Unix), save to a file there, then read that file in PowerShell. See this answer for more information.
----FirstActivity.java-----
package com.mindscripts.eid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FirstActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button orderButton = (Button) findViewById(R.id.order);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,OrderScreen.class);
startActivity(intent);
}
});
}
}
---OrderScreen.java---
package com.mindscripts.eid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OrderScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_class);
Button orderButton = (Button) findViewById(R.id.end);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
---AndroidManifest.xml----
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mindscripts.eid"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrderScreen"></activity>
</application>
As @stevebot said, do this:
https://<bucket-name>.s3.amazonaws.com/<key>
The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.
If you use Drupal AND the module called "WYSIWYG" with the CKEditor library, then the following workaround could be a solution. For me it works like a charm. I use CKEditor 4.4.5 and WYSIWYG 2.2 in Drupal 7.33. I found this workaround here: https://www.drupal.org/node/1956778.
Here it is: I create a custom module and put the following code in the ".module" file:
<?php
/**
* Implements hook_wysiwyg_editor_settings_alter().
*/
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
if ($context['profile']->editor == 'ckeditor') {
$settings['allowedContent'] = TRUE;
}
}
?>
I hope this help other Drupal users.
I tried the following solution:
I created a shortcut of javaw.exe from path C:\Program Files\Java\jdk1.7.0_71\bin and pasted it into the path C:\ProgramData\Oracle\Java\javapath.
After that, I launched Eclipse, and it worked for me.
To validate base64 image we can use this regex
/^data:image/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}
private validBase64Image(base64Image: string): boolean {
const regex = /^data:image\/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}/;
return base64Image && regex.test(base64Image);
}
var date = new Date(date_string); var milliseconds = date.getTime();
This worked for me!
If you want to install apk from your aab to your device for testing purpose then you need to edit the configuration before running it on the connected device.
This will install an apk directly on the device connected from the aab.
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
I'm going to assume compiling the QuickFix package does not produce a setup.py
file, but rather only compiles the Python bindings and relies on make install
to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so
extension), and add that directory to your PYTHONPATH
environmental variable e.g., add
export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH
or similar line in your shell configuration file.
A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local
. Assuming QuickFix knows to put the Python files in the appropriate site-packages
, when you do make install
, it should install the files to ~/.local/lib/pythonX.Y/site-packages
, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.
If, on the other hand, it did provide a setup.py
file, simply run
python setup.py install --user
for Python 2.6+.
WHERE is applied as a limitation on the set returned by SQL; it uses SQL's built-in set oeprations and indexes and therefore is the fastest way to filter result sets. Always use WHERE whenever possible.
HAVING is necessary for some aggregate filters. It filters the query AFTER sql has retrieved, assembled, and sorted the results. Therefore, it is much slower than WHERE and should be avoided except in those situations that require it.
SQL Server will let you get away with using HAVING even when WHERE would be much faster. Don't do it.
Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793
Check out the Python tutorial on modules and how to use them.
As for the second part of your question, Python comes with batteries included, of course:
>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793
I had a situation of git status
showing changes, but git diff
printing nothing, although there were changes in several lines. However:
$ git diff data.txt > myfile
$ cat myfile
<prints diff>
Git 2.20.1 on raspbian. Other commands like git checkout
, git pull
are printing to stdout without problems.
It's case sensitive.
Wrong : SSH EC2-user@XXX.XX.XX.XX -i MyEC2KeyPair.pem
Correct : SSH ec2-user@XXX.XX.XX.XX -i MyEC2KeyPair.pem
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
select{
*zoom: 1.6;
*font-size: 9px;
}
If you change properties, size of select
will change also in IE7.
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
I can suggest two options.
Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.
void method() {
long endTimeMillis = System.currentTimeMillis() + 10000;
while (true) {
// method logic
if (System.currentTimeMillis() > endTimeMillis) {
// do some clean-up
return;
}
}
}
Run the method in a thread, and have the caller count to 10 seconds.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
method();
}
});
thread.start();
long endTimeMillis = System.currentTimeMillis() + 10000;
while (thread.isAlive()) {
if (System.currentTimeMillis() > endTimeMillis) {
// set an error flag
break;
}
try {
Thread.sleep(500);
}
catch (InterruptedException t) {}
}
The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.
As defined on Wikipedia, this should do it.
euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))
There's also the rdist
function in the fields
package that may be useful. See here.
EDIT: Changed **
operator to ^
. Thanks, Gavin.
The exact wording of the latest published standard (C++14) is:
An implementation shall allow both
a function of
()
returningint
anda function of
(int
, pointer to pointer tochar)
returningint
as the type of
main
.
This makes it clear that alternative spellings are permitted so long as the type of main
is the type int()
or int(int, char**)
. So the following are also permitted:
int main(void)
auto main() -> int
int main ( )
signed int main()
typedef char **a; typedef int b, e; e main(b d, a c)
check this answer out:
for me, these two lines had to be there for it to work and change the color:
android:indeterminateTint="@color/yourColor"
android:indeterminateTintMode="src_in"
PS: but its only available from android 21
In order for IIS Express answer on any IP address, just leave the address blank, i.e:
bindingInformation=":8080:"
Don't forget to restart the IIS express before the changes can take place.
I don't find any of the answers here useful, so I am providing my solution.
The problem is that you are using multipart/related
as the content type which is not good in this case. I am using multipart/mixed
and inside it multipart/alternative
(it works on most clients).
The message structure should be as follows:
[Headers]
Content-type:multipart/mixed; boundary="boundary1"
--boundary1
Content-type:multipart/alternative; boundary="boundary2"
--boundary2
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit
[HTML code with a href="cid:..."]
--boundary2
Content-Type: image/png;
name="moz-screenshot.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="moz-screenshot.png"
[base64 image data here]
--boundary2--
--boundary1--
Then it will work
I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync
. I tried both cygwin
and minGW
. It seems like rsync
is incompatible with git for windows
's version of ssh
.
Here is what worked for me: NFS.
Vagrant docs says:
NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.
This isn't true anymore. We can use vagrant-winnfsd
plugin nowadays. It's really simple to install:
vagrant plugin install vagrant-winnfsd
Vagrantfile
: config.vm.synced_folder ".", "/vagrant", type: "nfs"
Vagrantfile
: config.vm.network "private_network", type: "dhcp"
That's all I needed to make NFS
work. Laravel response time decreased from 500ms to 100ms for me.
I have a single checkbox named chkDueDate
and an HTML object with a click event as follows:
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
Clicking the HTML object (in this case a <span>
) toggles the checked property of the checkbox.
Set input type in XML as well as in JAVA file like this,
In XML,
android:inputType="textMultiLine|textCapSentences"
It will also allow multiline and in JAVA file,
edittext.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
make sure your keyboard's Auto-Capitalization setting is Enabled.
Xampp control panel v2.3.1 I got errors while using -h localhost
ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10060)
So, if you installed xampp as is and did not customize any documentroot, serverroot, etc. then the following works :-
start both the services on the xampp control panel click shell enter: # mysql -h 127.0.0.1 -u root
that works just fine. Below is the logtrail:-
# mysql -h 127.0.0.1 -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.21 MySQL Community Server (GPL)
Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
I won't try to give a complete answer here. My recommendation would be to focus on understanding what each one of them does and then it should be cleare to see that their effects are completely different and why sometimes they are used together.
static
is for members of a class (attributes and methods) and it has to be understood in contrast to instance (non static) members. I'd recommend reading "Understanding Instance and Class Members" in The Java Tutorials. I can also be used in static
blocks but I would not worry about it for a start.
final
has different meanings according if its applied to variables, methods, classes or some other cases. Here I like Wikipedia explanations better.
Try this:
SELECT CONVERT(DATE, STUFF(STUFF('01012020', 5, 0, '-'), 3, 0, '-'), 103);
It works with SQL Server 2016.
Very old stuff.
Got it solved fixing the localRepository in settings.xml
.
This file was copied from my other computer and the path of the .m2 repository wasn't the same.
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\Users\foo\.m2</localRepository>
</settings>
SQL Server
does not support CREATE TABLE AS SELECT
.
Use this:
SELECT *
INTO A
FROM myview
or
SELECT TOP 10
*
INTO A
FROM myview
ORDER BY
id
You can find more information about which services it affects on the Microsoft docs.
I know this MIGHT not be the cause of your issue, but I've spent a few hours hitting my head against the wall to solve this issue and this is my solution.
(running Windows 10 x32)
So I had installed XAMPP in a deeply nested directory and all the conf files make reference to root\xampp\apache
, whereas my files were some_dir\another_dir\whatthehelliswrongwithme\finally\xampp\apache
so my options were to either go through and edit all \xampp\apache
references and point them at the right place, OR, the much simpler option... reinstall XAMPP at the root, so the references all point to the right place.
A little annoying, but I guess that's what we get when Mac and Windows try to be friends..
Hope it helps a few of you.
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
Yes.
int minx, miny, maxx,maxy;
do {
printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);
The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).
Well, we're using Amazon Web Services and so we are looking to use scripts and programs to get through this problem. So I have been on the hunt for a command line tool. So first I tried the trick of running
c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
but because I'm running a cloud based Windows Server 2012 it complained
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
and I Googled and found the official Microsoft Support Page KB2736284. So there is a command line tool dism.exe
. So I tried the following
dism /online /enable-feature /featurename:IIS-ASPNET45
but it complained and gave a list of featurenames to try, so I tried them one by one and I tested my WebAPI webpage after each and it worked after the bottom one in the list.
dism /online /enable-feature /featurename:IIS-ApplicationDevelopment
dism /online /enable-feature /featurename:IIS-ISAPIFilter
dism /online /enable-feature /featurename:IIS-ISAPIExtensions
dism /online /enable-feature /featurename:IIS-NetFxExtensibility45
And so now I can browse to my WebAPI site and see the API information. That should help a few people. [However, I am not out of the woods totally myself yet and I cannot reach the website from outside the box. Still working on it.]
Also, I did some earlier steps following other people responses. I can confirm that the following Feature Delegation needs to be change (though I'd like to find a command line tool for these).
In Feature delegation
Change
'Handler Mappings' from Read Only to Read/Write
Change
'Modules' from Read Only to Read/Write
Change
'SSL Settings' from Read Only to Read/Write
Where the data returned is a string; you could cast to a different data type:
(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();
Here we go.. We will need two classes. I am posting a code which changes mobile audio profile after each 5 seconds (5000 mili seconds) ...
Our 1st Class
public class ChangeProfileActivityMain extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(ChangeProfileActivityMain.this);
timer.scheduleAtFixedRate(updateProfile, 0, 5000);
}
}
Our 2nd Class
public class CustomTimerTask extends TimerTask {
private AudioManager audioManager;
private Context context;
private Handler mHandler = new Handler();
// Write Custom Constructor to pass Context
public CustomTimerTask(Context con) {
this.context = con;
}
@Override
public void run() {
// TODO Auto-generated method stub
// your code starts here.
// I have used Thread and Handler as we can not show Toast without starting new thread when we are inside a thread.
// As TimePicker has run() thread running., So We must show Toast through Handler.post in a new Thread. Thats how it works in Android..
new Thread(new Runnable() {
@Override
public void run() {
audioManager = (AudioManager) context.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
mHandler.post(new Runnable() {
@Override
public void run() {
if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(context, "Ringer Mode set to Normal", Toast.LENGTH_SHORT).show();
} else {
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(context, "Ringer Mode set to Silent", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
}
To fix it simply take Set
in place of List
for your nested object.
@OneToMany
Set<Your_object> objectList;
and don't forget to use fetch=FetchType.EAGER
it will work.
There is one more concept CollectionId
in Hibernate if you want to stick with list only.
But remind that you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer!
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different DB or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyways, so I went this way)
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null ;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'] ;
echo $row['id_email'] ;
}
$db = null ;
if (count($this->id_email) > 0) {
echo 'not empty';
return true ;
}
echo 'empty';
return false ;
Proxies may send a HTTP_X_FORWARDED_FOR
header but even that is optional.
Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.
Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):
The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:
[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
Will output the following if it is over the character limit: "Address can have a max of 100 characters"
The placeholders I am aware of are:
Much thanks to bloudraak for initially pointing this out.
You can get back a commit after doing a reset --hard HEAD
.
Make use of "git reflog
" to check the history of the HEAD
in the branch.
You will see your commit and its id here.
Do a
git reset {commit Id of the commit you want to bring back}
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
According to my experience, in console apps the easiest way to read the last key pressed is as follows (Example with arrow keys):
ConsoleKey readKey = Console.ReadKey ().Key;
if (readKey == ConsoleKey.LeftArrow) {
<Method1> (); //Do something
} else if (readKey == ConsoleKey.RightArrow) {
<Method2> (); //Do something
}
I use to avoid loops, instead I write the code above within a method, and I call it at the end of both "Method1" and "Method2", so, after executing "Method1" or "Method2", Console.ReadKey().Key is ready to read the keys again.
You can browse Android SDK samples from your smartphone using "Code Search": https://market.android.com/details?id=sqwady.codesearch
How about that?
function internalHandler(e) {
e.preventDefault(); // required in some browsers
e.returnValue = ""; // required in some browsers
return "Custom message to show to the user"; // only works in old browsers
}
if (window.addEventListener) {
window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', internalHandler);
}
For Xamarin iOS
btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
You should supply the SqlParameter instances in the following way:
context.Database.SqlQuery<myEntityType>(
"mySpName @param1, @param2, @param3",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2),
new SqlParameter("param3", param3)
);
Look at the find command.
What you are looking for is something like
find . -name "*.xls" -type f -exec program
Post edit
find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;
will execute xls2csv file.xls file.xls.csv
Closer to what you want.
First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):
import static org.mockito.Mockito.*;
For partial mocking and still keeping original functionality on the rest mockito offers "Spy".
You can use it as follows:
private World world = spy(new World());
To eliminate a method from being executed you could use something like this:
doNothing().when(someObject).someMethod(anyObject());
to give some custom behaviour to a method use "when" with an "thenReturn":
doReturn("something").when(this.world).someMethod(anyObject());
For more examples please find the excellent mockito samples in the doc.
ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121
S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ;
RemoteServerName => abcd123 ;
2121 => port number ;
ftps => command is part of ftps client software ;
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
It should be like this :
<string name="game_settings_dragNDropMove_checkBox">Move by Drag&Drop</string>
C# 6 adds a new feature just for this: extension Add methods. This has always been possible for VB.net but is now available in C#.
Now you don't have to add Add()
methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add()
method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.
public static class TupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
T1 item1, T2 item2)
{
list.Add(Tuple.Create(item1, item2));
}
public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
T1 item1, T2 item2, T3 item3)
{
list.Add(Tuple.Create(item1, item2, item3));
}
// and so on...
}
This will allow you to do this on any class that implements IList<>
:
var numbers = new List<Tuple<int, string>>
{
{ 1, "one" },
{ 2, "two" },
{ 3, "three" },
{ 4, "four" },
{ 5, "five" },
};
var points = new ObservableCollection<Tuple<double, double, double>>
{
{ 0, 0, 0 },
{ 1, 2, 3 },
{ -4, -2, 42 },
};
Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.
public static class BigIntegerListExtensions
{
public static void Add(this IList<BigInteger> list,
params byte[] value)
{
list.Add(new BigInteger(value));
}
public static void Add(this IList<BigInteger> list,
string value)
{
list.Add(BigInteger.Parse(value));
}
}
var bigNumbers = new List<BigInteger>
{
new BigInteger(1), // constructor BigInteger(int)
2222222222L, // implicit operator BigInteger(long)
3333333333UL, // implicit operator BigInteger(ulong)
{ 4, 4, 4, 4, 4, 4, 4, 4 }, // extension Add(byte[])
"55555555555555555555555555555555555555", // extension Add(string)
};
C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple
instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.
public static class ValueTupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
ValueTuple<T1, T2> item) => list.Add(item.ToTuple());
}
This way the list initialization will look even nicer.
var points = new List<Tuple<int, int, int>>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
But instead of going through all this trouble, it might just be better to switch to using ValueTuple
exclusively.
var points = new List<(int, int, int)>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
In simple words, it is a LOOP condition that is true in every loop iteration:
for(int i=0; i<10; i++)
{ }
In this we can say state of i is i<10 and i>=0
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
You may think JDBC is a rich API and ResultSet has got so many methods then why not just a getCount() method? Well, For many databases e.g. Oracle, MySQL and SQL Server, ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.
Btw, if you have to there are a couple of ways to do it e.g. by using ResultSet.last() and ResultSet.getRow() method, that's not the best way to do it but it works if you absolutely need it.
Though, getting the column count from a ResultSet is easy in Java. The JDBC API provides a ResultSetMetaData class which contains methods to return the number of columns returned by a query and hold by ResultSet.
When you use recv
in connection with select
if the socket is ready to be read from but there is no data to read that means the client has closed the connection.
Here is some code that handles this, also note the exception that is thrown when recv
is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :
def listenToSockets(self):
while True:
changed_sockets = self.currentSockets
ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)
for s in ready_to_read:
if s == self.serverSocket:
self.acceptNewConnection(s)
else:
self.readDataFromSocket(s)
And the function that receives the data :
def readDataFromSocket(self, socket):
data = ''
buffer = ''
try:
while True:
data = socket.recv(4096)
if not data:
break
buffer += data
except error, (errorCode,message):
# error 10035 is no data available, it is non-fatal
if errorCode != 10035:
print 'socket.error - ('+str(errorCode)+') ' + message
if data:
print 'received '+ buffer
else:
print 'disconnected'
Below query works for me @Oracle 10G ----
select PHONE, CONTACT, (ADDR1 || '-' || ADDR2 || '-' || ADDR3) as Address
from CUSTOMER_DETAILS
where Code='341';
O/P -
1111 [email protected] 4th street-capetown-sa
Depends how much you like the linq query syntax, you can use the extension methods directly like:
var item = Items.First(i => i.Id == 123);
And if you don't want to throw an error if the list is empty, use FirstOrDefault
which returns the default value for the element type (null
for reference types):
var item = Items.FirstOrDefault(i => i.Id == 123);
if (item != null)
{
// found it
}
Single()
and SingleOrDefault()
can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First()
and FirstOrDefault()
stop on the first match, so they are more efficient.
Of the First()
and Single()
family, here's where they throw:
First()
- throws if empty/not found, does not throw if duplicateFirstOrDefault()
- returns default if empty/not found, does not throw if duplicateSingle()
- throws if empty/not found, throws if duplicate existsSingleOrDefault()
- returns default if empty/not found, throws if duplicate existsThis may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):
It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.
Here are the commands again for easier copy-pasting:
openssl rsa -in $FF -out $TF
openssl rsa -aes256 -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF
and
openssl rsa -check -in $FF
openssl rsa -text -in $FF
Without knowing what your data looks like, i.e. the complexity, size, etc...XML is easy to maintain and easily accessible. I would NOT use an Access database, and flat files are more difficult to maintain over the long haul, particularly if you are dealing with more than one data field/element in your file.
I deal with large flat-file data feeds in good quantities daily, and even though an extreme example, flat-file data is much more difficult to maintain than the XML data feeds I process.
A simple example of loading XML data into a dataset using C#:
DataSet reportData = new DataSet();
reportData.ReadXml(fi.FullName);
You can also check out LINQ to XML as an option for querying the XML data...
HTH...
New Table...
making a dynamycal width with mobile devices support
http://www.codeography.com/2011/06/14/dynamic-fixed-width-layout-with-css.html
You can also use Rsync
and find
. For find
:
find $FOLDER -type f | cut -d/ -f2- | sort > /tmp/file_list_$FOLDER
But files with the same names and in the same subfolders, but with different content, will not be shown in the lists.
If you are a fan of GUI, you may check Meld that @Alexander mentioned. It works fine in both windows and linux.
It's the special table in Oracle. I often use it for calculations or checking system variables. For example:
Select 2*4 from dual
prints out the result of the calculationSelect sysdate from dual
prints the server current date. What i have found in nearly all the variations and the regex from the bulk transfer pdf and what is on wikipedia site is this, specifically for the wikipedia regex is, there needs to be a ^ after the first |(vertical bar). I figured this out by testing for AA9A 9AA, because otherwise the format check for A9A 9AA will validate it. For Example checking for EC1D 1BB which should be invalid comes back valid because C1D 1BB is a valid format.
Here is what I've come up with for a good regex:
^([G][I][R] 0[A]{2})|^((([A-Z-[QVX]][0-9]{1,2})|([A-Z-[QVX]][A-HK-Y][0-9]{1,2})|([A-Z-[QVX]][0-9][ABCDEFGHJKPSTUW])|([A-Z-[QVX]][A-HK-Y][0-9][ABEHMNPRVWXY])) [0-9][A-Z-[CIKMOV]]{2})$
You can convert that time in Unix timestamp by using
select UNIX_TIMESTAMP('2013-11-26 01:24:34')
then convert it in the readable format in whatever format you need
select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");
For in detail you can visit link
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
Here is a very useful and lightweight javascript plugin to accomplish this: js-cookie
Cookies.set('cookieName', 'Value');
setTimeout(function(){
var cookieValue = Cookies.get('cookieName');
if(cookieValue){
console.log("Test Cookie is set!");
} else {
document.write('<p>Sorry, but cookies must be enabled</p>');
}
Cookies.remove('cookieName');
}, 1000);
Works in all browsers, accepts any character.
The submit()
function is there to make life easier. You can use it on any element inside of form tags to submit that form.
You can also search for the submit button and use click()
.
So the only difference is click()
has to be done on the submit button and submit()
can be done on any form element.
It's up to you.
http://docs.seleniumhq.org/docs/03_webdriver.jsp#user-input-filling-in-forms
for log file you may date to enter into text data. following code may help
# declaring variables
Logfile="logfile.txt"
MAIL_LOG="Message to print in log file"
Location="were is u want to store log file"
cd $Location
if [ -f $Logfile ]
then
echo "$MAIL_LOG " >> $Logfile
else
touch $Logfile
echo "$MAIL_LOG" >> $Logfile
fi
ouput: 2. Log file will be created in first run and keep on updating from next runs. In case log file missing in future run , script will create new log file.
Resolution fix: For me, the problem was related to active chrome sessions. I closed all of my chrome browser sessions and then tried building to chrome again. I am using Visual Studio Professional 2017 version 15.3.2. The VS application I was running into build errors with was a WebAPI project. When trying to click the green play button, I was getting dialog error stating "Unable to start the program 'http://localhost:18980/'. An operation is not legal in the current state. Hopefully this post helps someone.
Oftentimes there's a need to override existing rules, so appending new styles to the HEAD doesn't work in every case.
I came up with this simple function that summarizes all not valid "append to the BODY" approaches and is just more convenient to use and debug (IE8+).
window.injectCSS = (function(doc){
// wrapper for all injected styles and temp el to create them
var wrap = doc.createElement('div');
var temp = doc.createElement('div');
// rules like "a {color: red}" etc.
return function (cssRules) {
// append wrapper to the body on the first call
if (!wrap.id) {
wrap.id = 'injected-css';
wrap.style.display = 'none';
doc.body.appendChild(wrap);
}
// <br> for IE: http://goo.gl/vLY4x7
temp.innerHTML = '<br><style>'+ cssRules +'</style>';
wrap.appendChild( temp.children[1] );
};
})(document);
This can also be encountered while trying to open an ASP.Net MVC project while you don't have ASP.Net MVC installed with your Visual Studio 2010. In my case it was ASP.Net MVC 3.0
You can try this query to get stored procedures and functions:
SELECT name, type
FROM dbo.sysobjects
WHERE type IN (
'P', -- stored procedures
'FN', -- scalar functions
'IF', -- inline table-valued functions
'TF' -- table-valued functions
)
ORDER BY type, name
set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());
OK, here's the solution I settled on.
First you create a seed value using the "newseed()" function. Then you pass the seed value to the "srandom()" function. Lastly, the "srandom()" function returns a pseudo random value between 0 and 1.
The crucial bit is that the seed value is stored inside an array. If it were simply an integer or float, the value would get overwritten each time the function were called, since the values of integers, floats, strings and so forth are stored directly in the stack versus just the pointers as in the case of arrays and other objects. Thus, it's possible for the value of the seed to remain persistent.
Finally, it is possible to define the "srandom()" function such that it is a method of the "Math" object, but I'll leave that up to you to figure out. ;)
Good luck!
JavaScript:
// Global variables used for the seeded random functions, below.
var seedobja = 1103515245
var seedobjc = 12345
var seedobjm = 4294967295 //0x100000000
// Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
{
return [seednum]
}
// Works like Math.random(), except you provide your own seed as the first argument.
function srandom(seedobj)
{
seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm
return seedobj[0] / (seedobjm - 1)
}
// Store some test values in variables.
var my_seed_value = newseed(230951)
var my_random_value_1 = srandom(my_seed_value)
var my_random_value_2 = srandom(my_seed_value)
var my_random_value_3 = srandom(my_seed_value)
// Print the values to console. Replace "WScript.Echo()" with "alert()" if inside a Web browser.
WScript.Echo(my_random_value_1)
WScript.Echo(my_random_value_2)
WScript.Echo(my_random_value_3)
Lua 4 (my personal target environment):
-- Global variables used for the seeded random functions, below.
seedobja = 1103515.245
seedobjc = 12345
seedobjm = 4294967.295 --0x100000000
-- Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
return {seednum}
end
-- Works like random(), except you provide your own seed as the first argument.
function srandom(seedobj)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
return seedobj[1] / (seedobjm - 1)
end
-- Store some test values in variables.
my_seed_value = newseed(230951)
my_random_value_1 = srandom(my_seed_value)
my_random_value_2 = srandom(my_seed_value)
my_random_value_3 = srandom(my_seed_value)
-- Print the values to console.
print(my_random_value_1)
print(my_random_value_2)
print(my_random_value_3)
Your syntax is slightly wrong. Say:
*/15 * * * * command
|
|--> `*/15` would imply every 15 minutes.
*
indicates that the cron expression matches for all values of the field.
/
describes increments of ranges.
var orig = new Date();
var copy = new Date(+orig);
console.log(orig, copy);
_x000D_
SQL Server Script
declare @iDate datetime
set @iDate=GETDATE()
print year(@iDate) -- for Year
print month(@iDate) -- for Month
print day(@iDate) -- for Day
Your local branch doensn't know about the remote branch. If you don't tell git that your local branch (master) is supposed to compare itself to the remote counterpart (origin/master in this case); then git status won't tell you the difference between your branch and the remote one. So you should use:
git branch --set-upstream-to origin/master
or with the short option:
git branch -u origin/master
This options --set-upstream-to (or -u in short) was introduced in git 1.8.0.
Once you have set this option; git status
will show you something like:
# Your branch is ahead of 'origin/master' by 1 commit.
To convert int to char use:
int a=8;
char c=a+'0';
printf("%c",c); //prints 8
To Convert char to int use:
char c='5';
int a=c-'0';
printf("%d",a); //prints 5
All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.
In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).
This should work with all file names:
find $DIR -type f -printf "%T@ %p\n" | sort -n | sed -r 's/^[0-9.]+\s+//' | tail -n 1 | xargs -I{} ls -l "{}"
This sorts by mtime, see man find:
%Ak File's last access time in the format specified by k, which is either `@' or a directive for the C `strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.
@ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.
%Ck File's last status change time in the format specified by k, which is the same as for %A.
%Tk File's last modification time in the format specified by k, which is the same as for %A.
So just replace %T
with %C
to sort by ctime.
You can create category for the UiView and override the touchesBegan meathod as follows.
It is working fine for me.And it is centralize solution for this problem.
#import "UIView+Keyboard.h"
@implementation UIView(Keyboard)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.window endEditing:true];
[super touchesBegan:touches withEvent:event];
}
@end
Now, you don't need to use FormBuilder
and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
Example from repo :
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I test it and it works :) - here is my code:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
In html template I use separate tag (div/span/small etc.)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:
<small>
tag)Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword
field on registration is never send to server).
It also looks like if you just put the size
argument in the geom_line()
portion but without the aes()
it will scale appropriately. At least it works this way with geom_density
and I had the same problem.
Change the klik method as follows:
public void klik(object pea, EventArgs e)
{
Bitmap c = this.DrawMandel();
Button btn = pea as Button;
Graphics gr = btn.CreateGraphics();
gr.DrawImage(b, 150, 200);
}
While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).
Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.
The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.
It most likely means the hostname can't be resolved.
import socket
socket.getaddrinfo('localhost', 8080)
If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.
using flexbox:
h2 {
display: flex;
align-items: center;
}
h2 span {
content:"";
flex: 1 1 auto;
border-top: 1px solid #000;
}
html:
<h2>Title <span></span></h2>
Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!
If you need to be specific on into which folders to copy the file you can combine find with one or more greps. For example to replace any occurences of favicon.ico in any subfolder you can use:
find . | grep favicon\.ico | xargs -n 1 cp -f /root/favicon.ico
I've been dealing with this for awhile (frustrating). So much that I have instructions on my desktop consolidating all of these ideas. Here is my magic combination to the solution:
You don't have to do this every time but when it gets out of wack try these steps.
Bind-address XXX.XX.XX.XXX in /etc/my.cnf
comment line:
or
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
quit;
add firewall rule:
iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT
I've used this tool before- although it seems like there needs to be an issue open first, it is super useful and really streamlines workflow if you use github issue tracking. git open-pull and then a pull request is submitted from whatever branch you are on or select. https://github.com/jehiah/git-open-pull
EDIT: Looks like you can create issues on the fly, so this tool is a good solution.
 
,  
,  
or  
can be used.
W3 says...
The character entities   and   denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font.
Even more at Wikipedia
You could simply do:
Select Req_ID, (avg(R1)+avg(R2)+avg(R3)+avg(R4)+avg(R5))/5 as Average
from Request
Group by Req_ID
Right?
I'm assuming that you may have multiple rows with the same Req_ID and in these cases you want to calculate the average across all columns and rows for those rows with the same Req_ID
I had a similar issue where I had 3 consecutive fragments in the same Activity
[M1.F0]->[M1.F1]->[M1.F2] followed by a call to a new Activity
[M2]. If the user pressed a button in [M2] I wanted to return to [M1,F1] instead of [M1,F2] which is what back press behavior already did.
In order to accomplish this I remove [M1,F2], call show on [M1,F1], commit the transaction, and then add [M1,F2] back by calling it with hide. This removed the extra back press that would have otherwise been left behind.
// Remove [M1.F2] to avoid having an extra entry on back press when returning from M2
final FragmentTransaction ftA = fm.beginTransaction();
ftA.remove(M1F2Fragment);
ftA.show(M1F1Fragment);
ftA.commit();
final FragmentTransaction ftB = fm.beginTransaction();
ftB.hide(M1F2Fragment);
ftB.commit();
Hi After doing this code: I'm not able to see value of Fragment2 on pressing Back Key. My Code:
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.frame, f1);
ft.remove(f1);
ft.add(R.id.frame, f2);
ft.addToBackStack(null);
ft.remove(f2);
ft.add(R.id.frame, f3);
ft.commit();
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_BACK){
Fragment currentFrag = getFragmentManager().findFragmentById(R.id.frame);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
if(currentFrag != null){
String name = currentFrag.getClass().getName();
}
if(getFragmentManager().getBackStackEntryCount() == 0){
}
else{
getFragmentManager().popBackStack();
removeCurrentFragment();
}
}
return super.onKeyDown(keyCode, event);
}
public void removeCurrentFragment()
{
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment currentFrag = getFragmentManager().findFragmentById(R.id.frame);
if(currentFrag != null){
transaction.remove(currentFrag);
}
transaction.commit();
}
Solution can be done be this way:
Example:
public static final int cameraRequestCode = 999;
Hope this will help you.
<project name="Build" basedir="." default="clean">
<property name="default.build.type" value ="Release"/>
<target name="clean">
<echo>Value Buld is now ${PARAM_BUILD_TYPE} is set</echo>
<condition property="build.type" value="${PARAM_BUILD_TYPE}" else="${default.build.type}">
<isset property="PARAM_BUILD_TYPE"/>
</condition>
<echo>Value Buld is now ${PARAM_BUILD_TYPE} is set</echo>
<echo>Value Buld is now ${build.type} is set</echo>
</target>
</project>
In my Case DPARAM_BUILD_TYPE=Debug
if it is supplied than, I need to build for for Debug otherwise i need to go for building Release build.
I write like above condition it worked and i have tested as below it is working fine for me.
And property ${build.type}
we can pass this to other target or macrodef for processing which i am doing in my other ant macrodef.
D:\>ant -DPARAM_BUILD_TYPE=Debug
Buildfile: D:\build.xml
clean:
[echo] Value Buld is now Debug is set
[echo] Value Buld is now Debug is set
[echo] Value Buld is now Debug is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds
D:\>ant
Buildfile: D:\build.xml
clean:
[echo] Value Buld is now ${PARAM_BUILD_TYPE} is set
[echo] Value Buld is now ${PARAM_BUILD_TYPE} is set
[echo] Value Buld is now Release is set
main:
BUILD SUCCESSFUL
Total time: 0 seconds
It work for me to implement condition so posted hope it will helpful.
If you have to disable SSL checks for one git server hosting several repositories, you can run :
git config --bool --add http.https://my.bad.server.sslverify false
This will add it to your user's configuration.
Command to check:
git config --bool --get-urlmatch http.sslverify https://my.bad.server
(If you still use git < v1.8.5, run git config --global http.https://my.bad.server.sslVerify false
)
Explanation from the documentation where the command is at the end, show the
.gitconfig
content looking like:
[http "https://my.bad.server"]
sslVerify = false
It will ignore any certificate checks for this server, whatever the repository.
You also have some explanation in the code
Could you not use typeof(object) to compare against
On my mac:
info diff
then select: Output formats
-> Context
-> Unified format
-> Detailed Unified
:
Or online man diff on gnu following the same path to the same section:
File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format
Detailed Description of Unified Format ......................................
The unified output format starts with a two-line header, which looks like this:
--- FROM-FILE FROM-FILE-MODIFICATION-TIME +++ TO-FILE TO-FILE-MODIFICATION-TIME
The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.
You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.
Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:
@@ FROM-FILE-RANGE TO-FILE-RANGE @@ LINE-FROM-EITHER-FILE LINE-FROM-EITHER-FILE...
The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:
`+' A line was added here to the first file.
`-' A line was removed here from the first file.
You can achieve that with just one line code that simplify that:
$('#divs').get(0).outerHTML;
As simple as that.
For me, the main difference is that a script is interpreted, while a program is executed (i.e. the source is first compiled, and the result of that compilation is expected).
Wikipedia seems to agree with me on this :
Script :
"Scripts" are distinct from the core code of the application, which is usually written in a different language, and are often created or at least modified by the end-user.
Scripts are often interpreted from source code or bytecode, whereas the applications they control are traditionally compiled to native machine code.
Program :
The program has an executable form that the computer can use directly to execute the instructions.
The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled)
GIMP ( Graphic Image Manipulation Program) does a pretty good job... http://www.makeuseof.com/tag/create-image-map-gimp/
For LINQ -> SQL:
SingleOrDefault
FirstOrDefault
Underscore-java library has static method U.formatXml(xmlstring). I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
import com.github.underscore.lodash.Xml;
public class MyClass {
public static void main(String[] args) {
System.out.println(U.formatXml("<a>\n <b></b>\n <b></b>\n</a>",
Xml.XmlStringBuilder.Step.COMPACT));
}
}
// output: <a><b></b><b></b></a>
Alternatively, you could write a factory function which return a decorator which wraps the return value of the decorated function in a tag passed to the factory function. For example:
from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator():
return '<%(tag)s>%(rv)s</%(tag)s>' % (
{'tag': tag, 'rv': func()})
return decorator
return factory
This enables you to write:
@wrap_in_tag('b')
@wrap_in_tag('i')
def say():
return 'hello'
or
makebold = wrap_in_tag('b')
makeitalic = wrap_in_tag('i')
@makebold
@makeitalic
def say():
return 'hello'
Personally I would have written the decorator somewhat differently:
from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator(val):
return func('<%(tag)s>%(val)s</%(tag)s>' %
{'tag': tag, 'val': val})
return decorator
return factory
which would yield:
@wrap_in_tag('b')
@wrap_in_tag('i')
def say(val):
return val
say('hello')
Don't forget the construction for which decorator syntax is a shorthand:
say = wrap_in_tag('b')(wrap_in_tag('i')(say)))
To write a pandas DataFrame to a CSV file, you will need DataFrame.to_csv
. This function offers many arguments with reasonable defaults that you will more often than not need to override to suit your specific use case. For example, you might want to use a different separator, change the datetime format, or drop the index when writing. to_csv
has arguments you can pass to address these requirements.
Here's a table listing some common scenarios of writing to CSV files and the corresponding arguments you can use for them.
Footnotes
- The default separator is assumed to be a comma (
','
). Don't change this unless you know you need to.- By default, the index of
df
is written as the first column. If your DataFrame does not have an index (IOW, thedf.index
is the defaultRangeIndex
), then you will want to setindex=False
when writing. To explain this in a different way, if your data DOES have an index, you can (and should) useindex=True
or just leave it out completely (as the default isTrue
).- It would be wise to set this parameter if you are writing string data so that other applications know how to read your data. This will also avoid any potential
UnicodeEncodeError
s you might encounter while saving.- Compression is recommended if you are writing large DataFrames (>100K rows) to disk as it will result in much smaller output files. OTOH, it will mean the write time will increase (and consequently, the read time since the file will need to be decompressed).
var uniqueColors = (from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct();