This problem may also come up if you include different versions of jQuery.
Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;
Go to the directory where you have your Vagrantfile
Then, edit your Vagrantfile
and add the following:
config.vm.synced_folder ".", "/vagrant", :mount_options => ['dmode=774','fmode=775']
"." means the directory you are currently in on your host machine
"/vagrant" refers to "/home/vagrant" on the guest machine(Vagrant machine).
Copy the files you need to send to guest machine to the folder where you have your Vagrantfile
Then open Git Bash and cd
to the directory where you have your Vagrantfile
and type:
vagrant scp config.json XXXXXXX:/home/vagrant/
where XXXXXXX is your vm name. You can get your vm name by running
vagrant global-status
json_decode($jsondata, true);
true turns all properties to array (sequential or not)
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
'abcdefg' =~ /\Aabc/
What you're looking for is min-height
and max-height
.
img {
max-width: 100%;
height: auto;
}
.item {
width: 120px;
min-height: 120px;
max-height: auto;
float: left;
margin: 3px;
padding: 3px;
}
Use an extension method:
public static List<string> ColumnList(this IDataReader dataReader)
{
var columns = new List<string>();
for (int i = 0; i < dataReader.FieldCount; i++)
{
columns.Add(dataReader.GetName(i));
}
return columns;
}
<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox
<div id="div1" style="display:none;">NOTICE</div>
<script type="text/javascript">
<!--
function showMe (box) {
var chboxs = document.getElementById("div1").style.display;
var vis = "none";
if(chboxs=="none"){
vis = "block"; }
if(chboxs=="block"){
vis = "none"; }
document.getElementById(box).style.display = vis;
}
//-->
</script>
int[] oldArray = {1,2,3,4,5};
//new value
int newValue = 10;
//define the new array
int[] newArray = new int[oldArray.length + 1];
//copy values into new array
for(int i=0;i < oldArray.length;i++)
newArray[i] = oldArray[i];
//another solution is to use
//System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
//add new value to the new array
newArray[newArray.length-1] = newValue;
//copy the address to the old reference
//the old array values will be deleted by the Garbage Collector
oldArray = newArray;
There are many ways. You use RelativeLayout or AbsoluteLayout.
With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.
The idea of function extensions comes from functional paradigm, which is natively supported since ES6:
function init(){
doSomething();
}
// extend.js
init = (f => u => { f(u)
doSomethingHereToo();
})(init);
init();
As per @TJCrowder's concern about stack dump, the browsers handle the situation much better today. If you save this code into test.html and run it, you get
test.html:3 Uncaught ReferenceError: doSomething is not defined
at init (test.html:3)
at test.html:8
at test.html:12
Line 12: the init call, Line 8: the init extension, Line 3: the undefined doSomething()
call.
Note: Much respect to veteran T.J. Crowder, who kindly answered my question many years ago, when I was a newbie. After the years, I still remember the respectfull attitude and I try to follow the good example.
I did it in a simple way:
<a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>
It'll open runningrss in a new window and virtual-doctor in same window.
du -aS /PATH/TO/folder | sort -rn | head -2 | tail -1
or
du -aS /PATH/TO/folder | sort -rn | awk 'NR==2'
If you got white space in your branch then you will get this error.
Two answers I can think of... neither is particularly as pleasant as just having a concatenation operator.
First, use an NSMutableString
, which has an appendString
method, removing some of the need for extra temp strings.
Second, use an NSArray
to concatenate via the componentsJoinedByString
method.
If you read the docs (http://momentjs.com/docs/#/displaying/) you can find this format:
moment("2015-01-16T12:00:00").format("hh:mm:ss a")
See JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/
My Attempt ( JsFiddle)
Javascript
$(document).ready(function () {
$('#buttons input[type=button]').on('click', function () {
var qty = $(this).data('quantity');
var price = $('#totalPrice').text();
$('#count').val(price * qty);
});
});
Html
Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
<input id='qty2' type="button" data-quantity='2' value="2
Qty">
<input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4
Qty">
</div>
<br>Total
<input type="text" id="count" value="1">
Here's an extension method that casts Int32
to Enum
.
It honors bitwise flags even when the value is higher than the maximum possible. For example if you have an enum with possibilities 1, 2, and 4, but the int is 9, it understands that as 1 in absence of an 8. This lets you make data updates ahead of code updates.
public static TEnum ToEnum<TEnum>(this int val) where TEnum : struct, IComparable, IFormattable, IConvertible
{
if (!typeof(TEnum).IsEnum)
{
return default(TEnum);
}
if (Enum.IsDefined(typeof(TEnum), val))
{//if a straightforward single value, return that
return (TEnum)Enum.ToObject(typeof(TEnum), val);
}
var candidates = Enum
.GetValues(typeof(TEnum))
.Cast<int>()
.ToList();
var isBitwise = candidates
.Select((n, i) => {
if (i < 2) return n == 0 || n == 1;
return n / 2 == candidates[i - 1];
})
.All(y => y);
var maxPossible = candidates.Sum();
if (
Enum.TryParse(val.ToString(), out TEnum asEnum)
&& (val <= maxPossible || !isBitwise)
){//if it can be parsed as a bitwise enum with multiple flags,
//or is not bitwise, return the result of TryParse
return asEnum;
}
//If the value is higher than all possible combinations,
//remove the high imaginary values not accounted for in the enum
var excess = Enumerable
.Range(0, 32)
.Select(n => (int)Math.Pow(2, n))
.Where(n => n <= val && n > 0 && !candidates.Contains(n))
.Sum();
return Enum.TryParse((val - excess).ToString(), out asEnum) ? asEnum : default(TEnum);
}
int 0x80 is the assembly language instruction that is used to invoke system calls in Linux on x86 (i.e., Intel-compatible) processors.
In ES6/2015 you can loop through an object like this: (using arrow function)
Object.keys(myObj).forEach(key => {
console.log(key); // the name of the current key.
console.log(myObj[key]); // the value of the current key.
});
In ES7/2016 you can use Object.entries
instead of Object.keys
and loop through an object like this:
Object.entries(myObj).forEach(([key, val]) => {
console.log(key); // the name of the current key.
console.log(val); // the value of the current key.
});
The above would also work as a one-liner:
Object.entries(myObj).forEach(([key, val]) => console.log(key, val));
In case you want to loop through nested objects as well, you can use a recursive function (ES6):
const loopNestedObj = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
else console.log(key, obj[key]); // or do something with key and val.
});
};
Same as function above, but with ES7 Object.entries()
instead of Object.keys()
:
const loopNestedObj = obj => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === "object") loopNestedObj(val); // recurse.
else console.log(key, val); // or do something with key and val.
});
};
Here we loop through nested objects change values and return a new object in one go using Object.entries()
combined with Object.fromEntries()
(ES10/2019):
const loopNestedObj = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => {
if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
else [key, updateMyVal(val)]; // or do something with key and val.
})
);
Another way of looping through objects is by using for ... in and for ... of. See @vdegenne's nicely written answer.
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
The following is a concise (and updated) summation of the earlier solutions. Here's what to do:
Add these strings and their respective parent keys:
pwrshell\(Default) < Open PowerShell Here
pwrshell\command\(Default) < powershell -NoExit -Command Set-Location -LiteralPath '%V'
pwrshelladmin\(Default) < Open PowerShell (Admin)
pwrshelladmin\command\(Default) < powershell -Command Start-Process -verb runAs -ArgumentList '-NoExit','cd','%V' powershell
at these locations
HKCR\Directory\shell (for folders)
HKCR\Directory\Background\shell (Explorer window)
HKCR\Drive\shell (for root drives)
That's it. Add the "Extended" strings for the commands only to be visible if you hold the "Shift" key, everything else is superfluous.
As others have stated, you'll need to override the editor.tokenColorCustomizations
or the workbench.colorCustomizations
setting in the settings.json file. Here you can choose a base theme, like Abyss, and only override the things you want to change. You can either override very few things like the function, string colors etc. very easily.
E.g. for workbench.colorCustomizations
"workbench.colorCustomizations": {
"[Default Dark+]": {
"editor.background": "#130e293f",
}
}
E.g. for editor.tokenColorCustomizations
:
"editor.tokenColorCustomizations": {
"[Abyss]": {
"functions": "#FF0000",
"strings": "#FF0000"
}
}
// Don't do this, looks horrible.
However, deep customisations like change the colour of the var
keyword will require you to provide the override values under the textMateRules
key.
E.g. below:
"editor.tokenColorCustomizations": {
"[Abyss]": {
"textMateRules": [
{
"scope": "keyword.operator",
"settings": {
"foreground": "#FFFFFF"
}
},
{
"scope": "keyword.var",
"settings": {
"foreground": "#2871bb",
"fontStyle": "bold"
}
}
]
}
}
You can also override globally across themes:
"editor.tokenColorCustomizations": {
"textMateRules": [
{
"scope": [
//following will be in italics (=Pacifico)
"comment",
"entity.name.type.class", //class names
"keyword", //import, export, return…
//"support.class.builtin.js", //String, Number, Boolean…, this, super
"storage.modifier", //static keyword
"storage.type.class.js", //class keyword
"storage.type.function.js", // function keyword
"storage.type.js", // Variable declarations
"keyword.control.import.js", // Imports
"keyword.control.from.js", // From-Keyword
//"entity.name.type.js", // new … Expression
"keyword.control.flow.js", // await
"keyword.control.conditional.js", // if
"keyword.control.loop.js", // for
"keyword.operator.new.js", // new
],
"settings": {
"fontStyle": "italic"
}
}
]
}
More details here: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide
Can you use boost?
samm$ cat split.cc
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <string>
#include <vector>
int
main()
{
std::string split_me( "hello world how are you" );
typedef std::vector<std::string> Tokens;
Tokens tokens;
boost::split( tokens, split_me, boost::is_any_of(" ") );
std::cout << tokens.size() << " tokens" << std::endl;
BOOST_FOREACH( const std::string& i, tokens ) {
std::cout << "'" << i << "'" << std::endl;
}
}
sample execution:
samm$ ./a.out
8 tokens
'hello'
'world'
''
'how'
'are'
''
''
'you'
samm$
I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.
The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};
After lots of research, I solve this issue with hint from ofir_aghai answer about script load event.
Basically we need to use $
for jQuery code, but we can't use it till jQuery is loaded. I used document.createElement()
to add a script for jQuery, but the issue is that it takes time to load while the next statement in JavaScript using $
fails. So, I used the below solution.
myscript.js is having code which uses jQuery main.js is used to load both jquery.min.js and myscript.js files making sure that jQuery is loaded.
main.js code
window.load = loadJQueryFile();
var heads = document.getElementsByTagName('head');
function loadJQueryFile(){
var jqueryScript=document.createElement('script');
jqueryScript.setAttribute("type","text/javascript");
jqueryScript.setAttribute("src", "/js/jquery.min.js");
jqueryScript.onreadystatechange = handler;
jqueryScript.onload = handler;
heads[0].appendChild(jqueryScript);
}
function handler(){
var myScriptFile=document.createElement('script');
myScriptFile.setAttribute("type","text/javascript");
myScriptFile.setAttribute("src", "myscript.js");
heads[0].appendChild(myScriptFile);
}
This way it worked. Using loadJQueryFile()
from myscript.js didn't work. It immediately goes to the next statement which uses $
.
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
the modern answer for this should be using Kotlin's no-arg compiler plugin
which creates a non argument construct code for classic apies more about here
simply you have to add the plugin class path in build.gradle project level
dependencies {
....
classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"
....
}
then configure your annotation to generate the no-arg
constructor
apply plugin: "kotlin-noarg"
noArg {
annotation("your.path.to.annotaion.NoArg")
invokeInitializers = true
}
then define your annotation file NoArg.kt
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class NoArg
finally in any data class you can simply use your own annotation
@NoArg
data class SomeClass( val datafield:Type , ... )
I used to create my own no-arg
constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .
I think the confusion is caused by the fact that people don't know the real application of the Singleton pattern. I can't stress this enough. Singleton is not a pattern to wrap globals. Singleton pattern should only be used to guarantee that one and only one instance of a given class exists during run time.
People think Singleton is evil because they are using it for globals. It is because of this confusion that Singleton is looked down upon. Please, don't confuse Singletons and globals. If used for the purpose it was intended for, you will gain extreme benefits from the Singleton pattern.
Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.
Python tells me where it lives when it gives me an error message :)
>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>
I know of two ways to do it.
Method 1
The first method (which I prefer) is to use msbuild:
msbuild project.sln /Flags...
Method 2
You can also run:
vcexpress project.sln /build /Flags...
The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.
Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).
So, the end result might be:
os.system("msbuild project.sln /p:Configuration=Debug")
You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).
Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0
You may try
Android Studio top menu > File > Invalidate caches / restart...
Click on invalidate cache / restart button to restart your project
Resolve R.xxxx.xxx again if some of the fragment class R class didn't resolve properly
then rebuild your project
Hope it helps
SIMPLE WINDOWS SOLUTION FOR ANY KEYBOARD LAYOUT (may work for other OS but not tested)
I use a Finnish keyboard so none of the above worked but this should work for all keyboards.
As of Java 8 The use of lambda expressions have become available.
See this:
int[] nums = /** Your Array **/;
Compact:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.
/[a-zA-Z]+/
Super simple example. Regular expressions are extremely easy to find online.
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
I have tried using Xcode Devices window's Connect via network options. but I am unable to see the "Connected over the network" icon next to the device name. also as soon as remove the USB the "Connect via network" option disappeared. also, the device name appears under the disconnected device list.
But using the "Connect via IP Address..." option, I am able to connect.
Use a CipherOutputStream
or CipherInputStream
with a Cipher
and your FileInputStream
/ FileOutputStream
.
I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding")
for creating the Cipher
class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.
Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.
If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.
Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes()
but use String.getBytes(StandardCharsets.UTF_8)
.
To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.
Be warned that CipherInputStream
may not report BadPaddingException
, this includes BadPaddingException
generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.
If you care about the speed use ujson (UltraJSON), which has the same API as json:
import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]
ES6 solution with Koa.
async recent() {
data = await ReadSchema.find({}, { sort: 'created_at' });
ctx.body = data;
}
const person = { name: 'Prince', age: 22, id: 1 };_x000D_
_x000D_
let {name, age, id} = person;_x000D_
_x000D_
console.log(name);_x000D_
console.log(age);_x000D_
console.log(id);
_x000D_
* Your variable name and object index need be same
Close the nodejs terminal and Rebuild.
Originally from this blog post. We can achieve if else by using below code
<xsl:choose>
<xsl:when test="something to test">
</xsl:when>
<xsl:otherwise>
</xsl:otherwise>
</xsl:choose>
So here is what I did
<h3>System</h3>
<xsl:choose>
<xsl:when test="autoIncludeSystem/autoincludesystem_info/@mdate"> <!-- if attribute exists-->
<p>
<dd><table border="1">
<tbody>
<tr>
<th>File Name</th>
<th>File Size</th>
<th>Date</th>
<th>Time</th>
<th>AM/PM</th>
</tr>
<xsl:for-each select="autoIncludeSystem/autoincludesystem_info">
<tr>
<td valign="top" ><xsl:value-of select="@filename"/></td>
<td valign="top" ><xsl:value-of select="@filesize"/></td>
<td valign="top" ><xsl:value-of select="@mdate"/></td>
<td valign="top" ><xsl:value-of select="@mtime"/></td>
<td valign="top" ><xsl:value-of select="@ampm"/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</dd>
</p>
</xsl:when>
<xsl:otherwise> <!-- if attribute does not exists -->
<dd><pre>
<xsl:value-of select="autoIncludeSystem"/><br/>
</pre></dd> <br/>
</xsl:otherwise>
</xsl:choose>
My Output
Boost's signals2 allows you to subscribe generic member functions (without templates!) and in a threadsafe way.
Example: Document-View Signals can be used to implement flexible Document-View architectures. The document will contain a signal to which each of the views can connect. The following Document class defines a simple text document that supports mulitple views. Note that it stores a single signal to which all of the views will be connected.
class Document
{
public:
typedef boost::signals2::signal<void ()> signal_t;
public:
Document()
{}
/* Connect a slot to the signal which will be emitted whenever
text is appended to the document. */
boost::signals2::connection connect(const signal_t::slot_type &subscriber)
{
return m_sig.connect(subscriber);
}
void append(const char* s)
{
m_text += s;
m_sig();
}
const std::string& getText() const
{
return m_text;
}
private:
signal_t m_sig;
std::string m_text;
};
Next, we can begin to define views. The following TextView class provides a simple view of the document text.
class TextView
{
public:
TextView(Document& doc): m_document(doc)
{
m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
}
~TextView()
{
m_connection.disconnect();
}
void refresh() const
{
std::cout << "TextView: " << m_document.getText() << std::endl;
}
private:
Document& m_document;
boost::signals2::connection m_connection;
};
you can also use cellspacing and cellpadding properties if repeat layout is table.
<asp:RadioButtonList ID="rblMyRadioButtonList" runat="server" CellPadding="3" CellSpacing="2">
This error can appear even if you load your script after the html render is finished. In this given example your code
<div id="hello"></div>
has no value inside the div. So the error is raised, because there is no value to change inside. It should have been
<div id="hello">Some random text to change</div>
then.
You can use a fieldset tag.
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<form>_x000D_
<fieldset>_x000D_
<legend>Personalia:</legend>_x000D_
Name: <input type="text"><br>_x000D_
Email: <input type="text"><br>_x000D_
Date of birth: <input type="text">_x000D_
</fieldset>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Check this link: HTML Tag
You can use a substring
String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
You should use the flex
or flex-basis
property rather than width
. Read more on MDN.
.flexbox .red {
flex: 0 0 25em;
}
The flex
CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:
flex-grow: 0; /* do not grow - initial value: 0 */
flex-shrink: 0; /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height - initial value: auto */
A simple demo shows how to set the first column to 50px
fixed width.
.flexbox {_x000D_
display: flex;_x000D_
}_x000D_
.red {_x000D_
background: red;_x000D_
flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
background: green;_x000D_
flex: 1;_x000D_
}_x000D_
.blue {_x000D_
background: blue;_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
<div class="red">1</div>_x000D_
<div class="green">2</div>_x000D_
<div class="blue">3</div>_x000D_
</div>
_x000D_
See the updated codepen based on your code.
Note: Do not forget column's order while reading constraint columns!
SELECT conname, attname
FROM pg_catalog.pg_constraint c
JOIN pg_catalog.pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY (c.conkey)
WHERE attrelid = 'schema.table_name'::regclass
ORDER BY conname, array_position(c.conkey, a.attnum)
For those like me who were looking for an ellipse attributes to path conversion:
const ellipseAttrsToPath = (rx,cx,ry,cy) =>
`M${cx-rx},${cy}a${rx},${ry} 0 1,0 ${rx*2},0a${rx},${ry} 0 1,0 -${rx*2},0`
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
Use RegEx.Replace, something like this:
string input = "This is text with far too much " +
"whitespace.";
string pattern = "[;,]";
string replacement = "\n";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Here's more info on this MSDN documentation for RegEx.Replace
This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict
built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.
In this way it's possible to avoid key errors.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
... def __missing__(self, key):
... return ''
...
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
The same thing can be done more simply in the following way. The use of the 'default' argument for the get
method of a dict object makes it unnecessary to subclass a dict.
>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
ID Surname
0 101 Mohanty
1 201
2 301 Drake
3 401
I hope it also useful
window.addEventListener("load", function()
{
if(!window.pageYOffset)
{
hideAddressBar();
}
window.addEventListener("orientationchange", hideAddressBar);
});
In simple words:
innerText
will show the value as is and ignores any HTML
formatting which may
be included.innerHTML
will show the value and apply any HTML
formatting.This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
Put an alert()
in your success
callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert()
in the complete
callback, which should definitely be invoked.
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
With the above answer, you cannot set the speed or have flexibility for customizing the text view functionality. To have your own scroll speed and flexibility to customize marquee properties, use the following:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:lines="1"
android:id="@+id/myTextView"
android:padding="4dp"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Simple application that shows how to use marquee, with a long text" />
Within your activity:
private void setTranslation() {
TranslateAnimation tanim = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 1.0f * screenWidth,
TranslateAnimation.ABSOLUTE, -1.0f * screenWidth,
TranslateAnimation.ABSOLUTE, 0.0f,
TranslateAnimation.ABSOLUTE, 0.0f);
tanim.setDuration(1000);//set the duration
tanim.setInterpolator(new LinearInterpolator());
tanim.setRepeatCount(Animation.INFINITE);
tanim.setRepeatMode(Animation.ABSOLUTE);
textView.startAnimation(tanim);
}
I assume the C string is in a fixed memory, so if you replace spaces you have to shift all characters.
The easiest seems to be to create new string and iterate over the original one and copy only non space characters.
UML Studio does this quite well in my experience, and will run in "freeware mode" for small projects.
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
If you start the scripts you are executing through cron with:
#!/bin/bash -l
They should pick up your ~/.bash_profile
environment variables
If you get an error when at the ./configure stage that says
configure: error: in `/home//Downloads/Python-2.7.14': configure: error: no acceptable C compiler found in $PATH
then try this.
no acceptable C compiler found in $PATH when installing python
Did you try
"
or \x22
instead of
\"
?
What kind of document library information do you want in the view? How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?
Note that there are at least two bug reports for ssh-add -d/-D
not removing keys:
ssh-add -D
does not remove SSH key from gnome-keyring-daemon
memory"ssh-add -D
deleting all identities does not work. Also, why are all identities auto-added?"The exact issue is:
ssh-add -d/-D
deletes only manually added keys from gnome-keyring.
There is no way to delete automatically added keys.
This is the original bug, and it's still definitely present.
So, for example, if you have two different automatically-loaded ssh identities associated with two different GitHub accounts -- say for work and for home -- there's no way to switch between them. GitHubtakes the first one which matches, so you always appear as your 'home' user to GitHub, with no way to upload things to work projects.
Allowing
ssh-add -d
to apply to automatically-loaded keys (andssh-add -t X
to change the lifetime of automatically-loaded keys), would restore the behavior most users expect.
More precisely, about the issue:
The culprit is
gpg-keyring-daemon
:
- It subverts the normal operation of ssh-agent, mostly just so that it can pop up a pretty box into which you can type the passphrase for an encrypted ssh key.
.ssh
directory, and automatically adds any keys it finds to your agent.How do we hate this? Let's not count the ways -- life's too short.
The failure is compounded because newer ssh clients automatically try all the keys in your ssh-agent when connecting to a host.
If there are too many, the server will reject the connection.
And since gnome-keyring-daemon has decided for itself how many keys you want your ssh-agent to have, and has autoloaded them, AND WON'T LET YOU DELETE THEM, you're toast.
This bug is still confirmed in Ubuntu 14.04.4, as recently as two days ago (August 21st, 2014)
A possible workaround:
- Do
ssh-add -D
to delete all your manually added keys. This also locks the automatically added keys, but is not much use sincegnome-keyring
will ask you to unlock them anyways when you try doing agit push
.
~/.ssh
folder and move all your key files except the one you want to identify with into a separate folder called backup. If necessary you can also open seahorse and delete the keys from there.git push
without a problem.Another workaround:
What you really want to do is to turn off
gpg-keyring-daemon
altogether.
Go toSystem --> Preferences --> Startup Applications
, and unselect the "SSH Key Agent (Gnome Keyring SSH Agent)
" box -- you'll need to scroll down to find it.
You'll still get an
ssh-agent
, only now it will behave sanely: no keys autoloaded, you run ssh-add to add them, and if you want to delete keys, you can. Imagine that.
This comments actually suggests:
The solution is to keep
gnome-keyring-manager
from ever starting up, which was strangely difficult by finally achieved by removing the program file's execute permission.
Ryan Lue adds another interesting corner case in the comments:
In case this helps anyone: I even tried deleting the
id_rsa
andid_rsa.pub
files altogether, and the key was still showing up.
Turns out
gpg-agent
was caching them in a~/.gnupg/sshcontrol
file; I had to manually delete them from there.
That is the case when the keygrip
has been added as in here.
You can use:ls -lh
, then you will get a list of file information
grep -insr "pattern" *
i
: Ignore case distinctions in both the PATTERN and the input files.n
: Prefix each line of output with the 1-based line number within its input file.s
: Suppress error messages about nonexistent or unreadable files.r
: Read all files under each directory, recursively.Chosen API has changed a lot.
If non of the solution given works for you, you can try this one: https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify
Here is the function:
// USAGE:
// $('#some_input_id').chosen();
// chosen_ajaxify('some_input_id', 'http://some_url.com/contain/');
// REQUEST WILL BE SENT TO THIS URL: http://some_url.com/contain/some_term
// AND THE EXPECTED RESULT (WHICH IS GOING TO BE POPULATED IN CHOSEN) IS IN JSON FORMAT
// CONTAINING AN ARRAY WHICH EACH ELEMENT HAS "value" AND "caption" KEY. EX:
// [{"value":"1", "caption":"Go Frendi Gunawan"}, {"value":"2", "caption":"Kira Yamato"}]
function chosen_ajaxify(id, ajax_url){
console.log($('.chosen-search input').autocomplete);
$('div#' + id + '_chosen .chosen-search input').keyup(function(){
var keyword = $(this).val();
var keyword_pattern = new RegExp(keyword, 'gi');
$('div#' + id + '_chosen ul.chosen-results').empty();
$("#"+id).empty();
$.ajax({
url: ajax_url + keyword,
dataType: "json",
success: function(response){
// map, just as in functional programming :). Other way to say "foreach"
$.map(response, function(item){
$('#'+id).append('<option value="' + item.value + '">' + item.caption + '</option>');
});
$("#"+id).trigger("chosen:updated");
$('div#' + id + '_chosen').removeClass('chosen-container-single-nosearch');
$('div#' + id + '_chosen .chosen-search input').val(keyword);
$('div#' + id + '_chosen .chosen-search input').removeAttr('readonly');
$('div#' + id + '_chosen .chosen-search input').focus();
// put that underscores
$('div#' + id + '_chosen .active-result').each(function(){
var html = $(this).html();
$(this).html(html.replace(keyword_pattern, function(matched){
return '<em>' + matched + '</em>';
}));
});
}
});
});
}
Here is your HTML:
<select id="ajax_select"></select>
And here is your javasscript:
// This is also how you usually use chosen
$('#ajax_select').chosen({allow_single_deselect:true, width:"200px", search_contains: true});
// And this one is how you add AJAX capability
chosen_ajaxify('ajax_select', 'server.php?keyword=');
For more information, please refer to https://github.com/goFrendiAsgard/gofrendi.chosen.ajaxify#how-to-use
Brute force code to answer your question:
DataTable dt = new DataTable();
//for each of your properties
dt.Columns.Add("PropertyOne", typeof(string));
foreach(Entity entity in entities)
{
DataRow row = dt.NewRow();
//foreach of your properties
row["PropertyOne"] = entity.PropertyOne;
dt.Rows.Add(row);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
Now for the actual question. Why would you want to do this? As mentioned earlier, you can bind directly to an object list. Maybe a reporting tool that only takes datasets?
Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one:
SELECT balance FROM people WHERE email = '[email protected]'
COLLATE SQL_Latin1_General_CP1_CI_AS
The most compatible command I've found for gcc and clang on Linux (thanks to armando.sano):
$ gcc -m64 -Xlinker --verbose 2>/dev/null | grep SEARCH | sed 's/SEARCH_DIR("=\?\([^"]\+\)"); */\1\n/g' | grep -vE '^$'
if you give -m32
, it will output the correct library directories.
Examples on my machine:
for g++ -m64
:
/usr/x86_64-linux-gnu/lib64
/usr/i686-linux-gnu/lib64
/usr/local/lib/x86_64-linux-gnu
/usr/local/lib64
/lib/x86_64-linux-gnu
/lib64
/usr/lib/x86_64-linux-gnu
/usr/lib64
/usr/local/lib
/lib
/usr/lib
for g++ -m32
:
/usr/i686-linux-gnu/lib32
/usr/local/lib32
/lib32
/usr/lib32
/usr/local/lib/i386-linux-gnu
/usr/local/lib
/lib/i386-linux-gnu
/lib
/usr/lib/i386-linux-gnu
/usr/lib
Click the Start
menu and choose Run
or use the keyboard shortcut of Win+R.
In the dialog box, type lusrmgr.msc
. When this application opens, click Users in the left-hand panel and then right click Administrator
in the right-hand panel. Click Properties
in the menu.
In the Administrator Properties
dialog, choose the Member Of
tab, then click the Add... button at the lower right. From the next dialog, choose Advanced...
Another dialog will appear. From there click Find Now
on the right. A list of search results will appear at the bottom of the dialog. Select Network Services
from this list and click OK
on each of the open dialogs.
Here is what worked for me.
To set the server anonymous to inherit from the app pool identity do the following..
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
PHP's inbuilt functions may not work for checking URL if allow_url_fopen setting is set to off for security reasons. Curl is a better option as we would not need to change our code at later stage. Below is the code I used to verify a valid URL:
$url = str_replace(' ', '%20', $url);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){ return true; } else { return false; }
Kindly note the CURLOPT_SSL_VERIFYPEER option which also verify the URL's starting with HTTPS.
Solution below:
SELECT GROUP_CONCAT(field_attr_best_weekday_value)as RAVI
FROM content_field_attr_best_weekday LEFT JOIN content_type_attraction
on content_field_attr_best_weekday.nid = content_type_attraction.nid
GROUP BY content_field_attr_best_weekday.nid
Use this, you also can change the Joins
Check out the node.js module list
node-mysql looks simple enough:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
Queries:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
The best method would be to take the code the sqlite3 db dump would do, excluding schema parts.
Example pseudo code:
SELECT 'INSERT INTO ' || tableName || ' VALUES( ' ||
{for each value} ' quote(' || value || ')' (+ commas until final)
|| ')' FROM 'tableName' ORDER BY rowid DESC
See: src/shell.c:838
(for sqlite-3.5.9) for actual code
You might even just take that shell and comment out the schema parts and use that.
IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/
I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.
Static memory allocation. Memory allocated will be in stack.
int a[10];
Dynamic memory allocation. Memory allocated will be in heap.
int *a = malloc(sizeof(int) * 10);
and the latter should be freed since there is no Garbage Collector(GC) in C.
free(a);
Don't use normal
android:drawableLeft
etc... with vector drawables, else it will crash in lower API versions. (I have faced it in live app)
If you are using vector drawable, then you must
It was released in version 1.1.0-alpha01
, so appcompat version should be at least 1.1.0-alpha01
. Current latest version is 1.1.0-alpha02
, use latest versions for better reliability, see release notes - link.
implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
Use AppCompatTextView
/AppCompatButton
/AppCompatEditText
app:drawableLeftCompat
, app:drawableTopCompat
, app:drawableRightCompat
, app:drawableBottomCompat
, app:drawableStartCompat
and app:drawableEndCompat
If you don't need vector drawable, then you can
android:drawableLeft
, android:drawableRight
, android:drawableBottom
, android:drawableTop
TextView
, Button
& EditText
or AppCompat
classes.You can achieve Output like below -
You can also add prompt option like this.
<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>
This technique worked for me:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
I hope this helps
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
You can use nested.
There are tow function one is openTab()
and another is closeMobileMenue()
, Firstly we call openTab()
and call another function inside closeMobileMenue()
.
function openTab() {
window.open('https://play.google.com/store/apps/details?id=com.drishya');
closeMobileMenue() //After open new tab, Nav Menue will close.
}
onClick={openTab}
You can use the $.ajax()
, and if you don't want to put the parameters directly into the URL, use the data:
. That's appended to the URL
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');_x000D_
var total_timers = seconds_inputs.length;_x000D_
for ( var i = 0; i < total_timers; i++){_x000D_
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
}_x000D_
function timer() {_x000D_
for ( var i = 0; i < total_timers; i++) {_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
var hours = Math.floor(hoursLeft / 3600);_x000D_
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
var minutes = Math.floor(minutesLeft / 60);_x000D_
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
function pad(n) {_x000D_
return (n < 10 ? "0" + n : n);_x000D_
}_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
clearInterval(countdownTimer);_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
} else {_x000D_
var value = eval('seconds_'+seconds_prod_id);_x000D_
value--;_x000D_
eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
With me in the end helped In the emulator to run applications manager and setting permissions for storage.
'vb.net
'Extended file stributes
'visual basic .net sample
Dim sFile As Object
Dim oShell = CreateObject("Shell.Application")
Dim oDir = oShell.Namespace("c:\temp")
For i = 0 To 34
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
For Each sFile In oDir.Items
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
Next
TextBox1.Text = TextBox1.Text & vbCrLf
Next
I don't believe Java natively provides this feature, although it would be nice. I write Perl code occasionally and the x
operator in Perl comes in really handy for repeating strings!
However StringUtils
in commons-lang
provides this feature. The method is called repeat()
. Your only other option is to build it manually using a loop.
int rgb = new Color(r, g, b).getRGB();
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I think you want Any
:
if (myList.Any(str => str.Contains("Mdd LH")))
It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll
) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)
My simple one line code works for me :)
string random = string.Join("", Guid.NewGuid().ToString("n").Take(8).Select(o => o));
Response.Write(random.ToUpper());
Response.Write(random.ToLower());
To expand on this for any length string
public static string RandomString(int length)
{
//length = length < 0 ? length * -1 : length;
var str = "";
do
{
str += Guid.NewGuid().ToString().Replace("-", "");
}
while (length > str.Length);
return str.Substring(0, length);
}
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...)
tries to get myProperty
from myObj
while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...)
returns obviously "null" because myProperty
exists, but it has the value null
assigned to it.
In order to be able to query this difference, JavaScript has null
and undefined
: While null
is - just like in other languages an object, undefined
cannot be an object because there is no instance (even not a null
instance) available.
For synchronous renaming use fs.renameSync
fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
The margins vary depending on the printer. In Windows GDI, you call the following functions to get the built-in margins, the "no-print zone":
GetDeviceCaps(hdc, PHYSICALWIDTH);
GetDeviceCaps(hdc, PHYSICALHEIGHT);
GetDeviceCaps(hdc, PHYSICALOFFSETX);
GetDeviceCaps(hdc, PHYSICALOFFSETY);
Printing right to the edge is called a "bleed" in the printing industry. The only laser printer I ever knew to print right to the edge was the Xerox 9700: 120 ppm, $500K in 1980.
Vertically aligning has always been tricky.
Here I have covered up some method of vertically aligning a div.
<div style="display:flex;">
<div class="container table">
<div class="tableCell">
<div class="content"><em>Table</em> method</div>
</div>
</div>
<div class="container flex">
<div class="content new"><em>Flex</em> method<br></div>
</div>
<div class="container relative">
<div class="content"><em>Position</em> method</div>
</div>
<div class="container margin">
<div class="content"><em>Margin</em> method</div>
</div>
</div>
em{font-style: normal;font-weight: bold;}
.container {
width:200px;height:200px;background:#ccc;
margin: 5px; text-align: center;
}
.content{
width:100px; height: 100px;background:#37a;margin:auto;color: #fff;
}
.table{display: table;}
.table > div{display: table-cell;height: 100%;width: 100%;vertical-align: middle;}
.flex{display: flex;}
.relative{position: relative;}
.relative > div {position: absolute;top: 0;left: 0;right: 0;bottom: 0;}
.margin > div {position:relative; margin-top: 50%;top: -50px;}
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">
Please! check below simple step by step tutorial to understand how Delegates works in iOS.
I have created two ViewControllers (for sending data from one to another)
i using laravel 5.* i figure i have a file call .env
in the root of the project that look something like this:
APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
And that was over writing the bd configuration so you can wheather deleted those config vars so laravel take the configuration under /config or set up your configuration here.
I did the second and it works for me :)
It works for me:
Delete folder node_modules
Run command: npm install
( If it does not work for the first time, repeat this 2 or 3 times, Its funny but it works for me. )
A thread is an independent set of values for the processor registers (for a single core). Since this includes the Instruction Pointer (aka Program Counter), it controls what executes in what order. It also includes the Stack Pointer, which had better point to a unique area of memory for each thread or else they will interfere with each other.
Threads are the software unit affected by control flow (function call, loop, goto), because those instructions operate on the Instruction Pointer, and that belongs to a particular thread. Threads are often scheduled according to some prioritization scheme (although it's possible to design a system with one thread per processor core, in which case every thread is always running and no scheduling is needed).
In fact the value of the Instruction Pointer and the instruction stored at that location is sufficient to determine a new value for the Instruction Pointer. For most instructions, this simply advances the IP by the size of the instruction, but control flow instructions change the IP in other, predictable ways. The sequence of values the IP takes on forms a path of execution weaving through the program code, giving rise to the name "thread".
The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.
Yes, it should be overridden. If you think you need to override equals()
, then you need to override hashCode()
and vice versa. The general contract of hashCode() is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
This is my implementation to convert any kind of encoding to UTF-8 without BOM and replacing windows enlines by universal format:
def utf8_converter(file_path, universal_endline=True):
'''
Convert any type of file to UTF-8 without BOM
and using universal endline by default.
Parameters
----------
file_path : string, file path.
universal_endline : boolean (True),
by default convert endlines to universal format.
'''
# Fix file path
file_path = os.path.realpath(os.path.expanduser(file_path))
# Read from file
file_open = open(file_path)
raw = file_open.read()
file_open.close()
# Decode
raw = raw.decode(chardet.detect(raw)['encoding'])
# Remove windows end line
if universal_endline:
raw = raw.replace('\r\n', '\n')
# Encode to UTF-8
raw = raw.encode('utf8')
# Remove BOM
if raw.startswith(codecs.BOM_UTF8):
raw = raw.replace(codecs.BOM_UTF8, '', 1)
# Write to file
file_open = open(file_path, 'w')
file_open.write(raw)
file_open.close()
return 0
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
In Windows 10 I had that problem because My C Drive was getting full and I had needed free Space, AVD folder had 14 gig space so I needed move that folder to another driver,first answer not work for Me so I tested another way to fix this problem, I make a picture for you if you have the same problem, you dont need to move all of files in .android folder to another drive (this way not work) just move avd folders in ....android\avd to another drive and open .ini files and change avd folder path from that file to new path. Like this image:
I Hope this works for you.
select top 10 * from
sys.procedures
where object_definition(object_id) like '%\[ABD\]%'
On a related note, if you only have the filename or relative path, dirname
on its own won't help. For me, the answer ended up being readlink
.
fname='txtfile'
echo $(dirname "$fname") # output: .
echo $(readlink -f "$fname") # output: /home/me/work/txtfile
You can then combine the two to get just the directory.
echo $(dirname $(readlink -f "$fname")) # output: /home/me/work
It's as simple as:
if (value.compareTo(BigDecimal.ZERO) > 0)
The documentation for compareTo
actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo
method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
I also suggest using contourf(Z)
. For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted
of pcolor()
is more suitable.
However, pcolor()
does not use the last row and column of the plotted matrix. For this, I used the padarray()
function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post
Long story short, it probably doesn't matter. Use whichever you think looks nicest.
Longer answer, using Oracle's Java 7 JDK specifically, since this isn't defined at the JLS:
String.valueOf
or Character.toString
work the same way, so use whichever you feel looks nicer. In fact, Character.toString
simply calls String.valueOf
(source).
So the question is, should you use one of those or String.substring
. Here again it doesn't matter much. String.substring
uses the original string's char[]
and so allocates one object fewer than String.valueOf
. This also prevents the original string from being GC'ed until the one-character string is available for GC (which can be a memory leak), but in your example, they'll both be available for GC after each iteration, so that doesn't matter. The allocation you save also doesn't matter -- a char[1]
is cheap to allocate, and short-lived objects (as the one-char string will be) are cheap to GC, too.
If you have a large enough data set that the three are even measurable, substring
will probably give a slight edge. Like, really slight. But that "if... measurable" contains the real key to this answer: why don't you just try all three and measure which one is fastest?
If you want a good format the next statement is the best:
dataframe_prediction.to_csv('filename.csv', sep=',', encoding='utf-8', index=False)
In this case you have got a csv file with ',' as separate between columns and utf-8 format. In addition, numerical index won't appear.
def digits(n)
count = 0
if n == 0:
return 1
if n < 0:
n *= -1
while (n >= 10**count):
count += 1
n += n%10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
I know this thread is old but anyway I'm sharing, I have to install all third part dependencies of the imported assembly - as the imported assembly wasn't included as Nuget package thus its dependencies were missing.
Hop this help :)
Here is an old version I have that works on version 1.0 of the .NET framework and does not need generic types.
public static Array RemoveAt(Array source, int index)
{
if (source == null)
throw new ArgumentNullException("source");
if (0 > index || index >= source.Length)
throw new ArgumentOutOfRangeException("index", index, "index is outside the bounds of source array");
Array dest = Array.CreateInstance(source.GetType().GetElementType(), source.Length - 1);
Array.Copy(source, 0, dest, 0, index);
Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
return dest;
}
This is used like this:
class Program
{
static void Main(string[] args)
{
string[] x = new string[20];
for (int i = 0; i < x.Length; i++)
x[i] = (i+1).ToString();
string[] y = (string[])MyArrayFunctions.RemoveAt(x, 3);
for (int i = 0; i < y.Length; i++)
Console.WriteLine(y[i]);
}
}
I'd use
files=(*)
And then if you need data about the file, such as size, use the stat
command on each file.
I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:
'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'
Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.
// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
from collections import OrderedDict
list1 = ['k1', 'k2']
list2 = ['v1', 'v2']
new_ordered_dict = OrderedDict(zip(list1, list2))
print new_ordered_dict
# OrderedDict([('k1', 'v1'), ('k2', 'v2')])
ARM
is a RISC (Reduced Instruction Set Computing) architecture while x86
is a CISC (Complex Instruction Set Computing) one.
The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.
So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.
About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86
isn't specially designed to work with a keyboard neither ARM
for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO
while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.
If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:
An ARM processor is a Reduced Instruction Set Computer (RISC) processor.
Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).
RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.
ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.
An example comparing instruction set architecture:
For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86
repe cmpsb /* repeat while equal compare string bytewise */
while on ARM
shortest form might look like (without error checking etc.)
top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2 /* subtract r2 from r3 and put result into r2 */
beq top /* branch(/jump) if result is zero */
which should give you a hint on how RISC and CISC instruction sets differ in complexity.
I figured it out!
Follow these steps:
You're welcome!
This is apparently a bug in the Entity Framework that the model does not get updated when your Edmx file is located inside a folder. The workarounds available at the moment are:
Hope that helps someone out there.
Link: http://thedatafarm.com/blog/data-access/watch-out-for-vs2012-edmx-code-generation-special-case/
They work at different levels.
The simplest way to view the difference, from a beginner perspective is that jQuery is essentially an abstract of JavaScript, so the way we design a page for JavaScript is pretty much how we will do it for jQuery. Start with the DOM then build a behavior layer on top of that. Not so with Angular.Js. The process really begins from the ground up, so the end result is the desired view.
With jQuery you do dom-manipulations, with Angular.Js you create whole web-applications.
jQuery was built to abstract away the various browser idiosyncracies, and work with the DOM without having to add IE6 checks and so on. Over time, it developed a nice, robust API which allowed us to do a lot of things, but at its core, it is meant for dealing with the DOM, finding elements, changing UI, and so on. Think of it as working directly with nuts and bolts.
Angular.Js was built as a layer on top of jQuery, to add MVC concepts to front end engineering. Instead of giving you APIs to work with DOM, Angular.Js gives you data-binding, templating, custom components (similar to jQuery UI, but declarative instead of triggering through JS) and a whole lot more. Think of it as working at a higher level, with components that you can hook together, instead of directly at the nuts and bolts level.
Additionally, Angular.Js gives you structures and concepts that apply to various projects, like Controllers, Services, and Directives. jQuery itself can be used in multiple (gazillion) ways to do the same thing. Thankfully, that is way less with Angular.Js, which makes it easier to get into and out of projects. It offers a sane way for multiple people to contribute to the same project, without having to relearn a system from scratch.
A short comparison can be this-
And much more
Think this helps.
More can be found-
The only way is to drop foreign keys before doing the truncate. And after truncating the data, you must re-create the indexes.
The following script generates the required SQL for dropping all foreign key constraints.
DECLARE @drop NVARCHAR(MAX) = N'';
SELECT @drop += N'
ALTER TABLE ' + QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name)
+ ' DROP CONSTRAINT ' + QUOTENAME(fk.name) + ';'
FROM sys.foreign_keys AS fk
INNER JOIN sys.tables AS ct
ON fk.parent_object_id = ct.[object_id]
INNER JOIN sys.schemas AS cs
ON ct.[schema_id] = cs.[schema_id];
SELECT @drop
Next, the following script generates the required SQL for re-creating foreign keys.
DECLARE @create NVARCHAR(MAX) = N'';
SELECT @create += N'
ALTER TABLE '
+ QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name)
+ ' ADD CONSTRAINT ' + QUOTENAME(fk.name)
+ ' FOREIGN KEY (' + STUFF((SELECT ',' + QUOTENAME(c.name)
-- get all the columns in the constraint table
FROM sys.columns AS c
INNER JOIN sys.foreign_key_columns AS fkc
ON fkc.parent_column_id = c.column_id
AND fkc.parent_object_id = c.[object_id]
WHERE fkc.constraint_object_id = fk.[object_id]
ORDER BY fkc.constraint_column_id
FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'')
+ ') REFERENCES ' + QUOTENAME(rs.name) + '.' + QUOTENAME(rt.name)
+ '(' + STUFF((SELECT ',' + QUOTENAME(c.name)
-- get all the referenced columns
FROM sys.columns AS c
INNER JOIN sys.foreign_key_columns AS fkc
ON fkc.referenced_column_id = c.column_id
AND fkc.referenced_object_id = c.[object_id]
WHERE fkc.constraint_object_id = fk.[object_id]
ORDER BY fkc.constraint_column_id
FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'') + ');'
FROM sys.foreign_keys AS fk
INNER JOIN sys.tables AS rt -- referenced table
ON fk.referenced_object_id = rt.[object_id]
INNER JOIN sys.schemas AS rs
ON rt.[schema_id] = rs.[schema_id]
INNER JOIN sys.tables AS ct -- constraint table
ON fk.parent_object_id = ct.[object_id]
INNER JOIN sys.schemas AS cs
ON ct.[schema_id] = cs.[schema_id]
WHERE rt.is_ms_shipped = 0 AND ct.is_ms_shipped = 0;
SELECT @create
Run the generated script to drop all foreign keys, truncate tables, and then run the generated script to re-create all foreign keys.
The queries are taken from here.
I just had the same problem. I'd say it has nothing to do with the apache.conf.
a2ensite must have changed - line 532 is the line that enforces the .conf suffix:
else {
$dir = 'sites';
$sffx = '.conf';
$reload = 'reload';
}
If you change it to:
else {
$dir = 'sites';
#$sffx = '.conf';
$sffx = '';
$reload = 'reload';
}
...it will work without any suffix.
Of course you wouldn't want to change the a2ensite script, but changing the conf file's suffix is the correct way.
It's probably just a way of enforcing the ".conf"-suffix.
And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.
Try setting fixed-width font with this:
\lstset{basicstyle=\ttfamily}
To see all the installed packages locally or globally, use these commands:
npm list
for local packages or npm list -g
for globally installed packages.npm list --depth=0
npm list | sls <package name>
node -v
Try this:
decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together
It can be writen shorter, but this is more descriptive.
EDIT: Short way:
decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));
Hey hey thanks from Xamarin user! :) Here it goes translated to c#
//***************************************************************************
public static class ImageExtensions
//***************************************************************************
{
//-------------------------------------------------------------
public static UIImage WithAlpha(this UIImage image, float alpha)
//-------------------------------------------------------------
{
UIGraphics.BeginImageContextWithOptions(image.Size,false,image.CurrentScale);
image.Draw(CGPoint.Empty, CGBlendMode.Normal, alpha);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
}
Usage example:
var MySupaImage = UIImage.FromBundle("opaquestuff.png").WithAlpha(0.15f);
Sometimes you have things other than text inside a table cell that you'd like to be horizontally centered. In order to do this, first set up some css...
<style>
div.centered {
margin: auto;
width: 100%;
display: flex;
justify-content: center;
}
</style>
Then declare a div
with class="centered"
inside each table cell you want centered.
<td>
<div class="centered">
Anything: text, controls, etc... will be horizontally centered.
</div>
</td>
As pointed already by @Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent
is processed SecurityContextHolder
is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder
) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:
AuthenticationSuccessEvent
AuthenticationSuccessHandler
implementation.AuthenticationSuccessHandler
has one important advantage over first way: SecurityContextHolder
will be already populated. So just move your stateService.rowCount()
call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...)
method and the problem will go away.
you should add this line above your page
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
#!/usr/bin/perl -w
$fileToLocate = '/whatever/path/for/file/you/are/searching/MyFile.txt';
if (-e $fileToLocate) {
print "File is present";
}
$mail->IsSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]";
$mail->Password = "**********";
$mail->Port = "465";
That is a working configuration.
try to replace what you have
import datetime
def print_time():
parser = datetime.datetime.now()
return parser.strftime("%d-%m-%Y %H:%M:%S")
print(print_time())
# Output>
# 03-02-2021 22:39:28
The most recent and in my opinion preferred approach is the f-string
:
''.join(f'{i:02x}' for i in [1, 15, 255])
The old format style was the %
-syntax:
['%02x'%i for i in [1, 15, 255]]
The more modern approach is the .format
method:
['{:02x}'.format(i) for i in [1, 15, 255]]
More recently, from python 3.6 upwards we were treated to the f-string
syntax:
[f'{i:02x}' for i in [1, 15, 255]]
Note that the f'{i:02x}'
works as follows.
:
is the input or variable to format. x
indicates that the string should be hex. f'{100:02x}'
is '64'
and f'{100:02d}'
is '1001'
.02
indicates that the string should be left-filled with 0
's to length 2
. f'{100:02x}'
is '64'
and f'{100:30x}'
is ' 64'
.As @Renich suggests (but with an important typo that has not been fixed unfortunately), you can also use extended globbing for pattern matching. So you can use the same patterns you use to match files in command arguments (e.g. ls *.pdf
) inside of bash comparisons.
For your particular case you can do the following.
if [[ "${cms}" != @(wordpress|magento|typo3) ]]
The @
means "Matches one of the given patterns". So this is basically saying cms
is not equal to 'wordpress' OR 'magento' OR 'typo3'. In normal regular expression syntax @ is similar to just ^(wordpress|magento|typo3)$
.
Mitch Frazier has two good articles in the Linux Journal on this Pattern Matching In Bash and Bash Extended Globbing.
For more background on extended globbing see Pattern Matching (Bash Reference Manual).
Years from 1000 to 2999
^[12][0-9]{3}$
For 1900-2099
^(19|20)\d{2}$
The tip on Oracle's OTN = Don't type your password in TOAD when you try to connect and let it popup a dialog box for your password. Type the password in there and it will work. Not sure what they've done in TOAD with passwords but that is a workaround. It has to do with case sensitive passwords in 11g. I think if you change the password to all upper case it will work with TOAD. https://community.oracle.com/thread/908022
If you are a developer, this is what you need to do:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
You are POSTing from the client:
await client.PostAsJsonAsync("api/products", product);
not PUTing.
Your Web API method accepts only PUT requests.
So:
await client.PutAsJsonAsync("api/products", product);
You have three options:
So, to get the 2º one you just need to install syslogd and OpenSSH from Cydia, restart required after to get syslogd going; now just open a ssh session to your device (via terminal or putty on windows), and type "tail -f /var/log/syslog". And there you go, wireless real time system log.
If you would like to try the 3º just search for "dup2" online, it's a system call.
I suggest using concat()
if you are using nodeJS. In all other cases, I have found that slice(0)
works fine.
How about this
find . -type f|xargs grep "needle text"
According to your Code :
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
System.out.print(name[i] +'\n');
}
If You check System.out.print(name.length);
you will get 3;
that mean your name length is 3
your loop is running from 0 to 3 which should be running either "0 to 2" or "1 to 3"
Answer
String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
System.out.print(name[i] +'\n');
}
The XPath turns into this:
Get me all of the div elements that have an id equal to container.
As for getting the first etc, you have two options.
Turn it into a .findElement()
- this will just return the first one for you anyway.
or
To explicitly do this in XPath, you'd be looking at:
(//div[@id='container'])[1]
for the first one, for the second etc:
(//div[@id='container'])[2]
Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:
(//div[@id='container'])[last()]
Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.
As for getting the parent 'node', well, you can use parent:
//div[@id='container']/parent::*
That would get the div's direct parent.
You could then go further and say I want the first *div* with an id of container, and I want his parent:
(//div[@id='container'])[1]/parent::*
Hope that helps!
It works fine. I tested it like this:
String command = @"C:\Doit.bat";
ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
// ProcessInfo.CreateNoWindow = true;
I commented out turning off the window so I could SEE it run.
input[type=checkbox].css-checkbox {
position: absolute;
overflow: hidden;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
margin: -1px;
padding: 0;
border: 0;
}
input[type=checkbox].css-checkbox + label.css-label {
padding-left: 20px;
height: 15px;
display: inline-block;
line-height: 15px;
background-repeat: no-repeat;
background-position: 0 0;
font-size: 15px;
vertical-align: middle;
cursor: pointer;
}
input[type=checkbox].css-checkbox:checked + label.css-label {
background-position: 0 -15px;
}
.css-label{
background-image:url(http://csscheckbox.com/checkboxes/dark-check-green.png);
}
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
I think the real answer to the OP's question is succinctly contained in this excerpt from the Numpy.correlate documentation:
mode : {'valid', 'same', 'full'}, optional
Refer to the `convolve` docstring. Note that the default
is `valid`, unlike `convolve`, which uses `full`.
This implies that, when used with no 'mode' definition, the Numpy.correlate function will return a scalar, when given the same vector for its two input arguments (i.e. - when used to perform autocorrelation).
You seem to look for the input attribute value
, "the initial value of the control"?
<input type="text" value="Morlodenhof 7" />
https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value
Increasing the timeout will not likely solve your issue since, as you say, the actual target web server is responding just fine.
I had this same issue and I found it had to do with not using a keep-alive on the connection. I can't actually answer why this is but, in clearing the connection header I solved this issue and the request was proxied just fine:
server {
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://localhost:5000;
}
}
Have a look at this posts which explains it in more detail: nginx close upstream connection after request Keep-alive header clarification http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
For higher API 10, the Dialog disappears when on touched outside, whereas in lower than API 11, the Dialog doesn't disappear. For prevent this, you need to do:
In styles.xml
: <item name="android:windowCloseOnTouchOutside">false</item>
OR
In onCreate()
method, use: this.setFinishOnTouchOutside(false);
Note: for API 10 and lower, this method doesn't have effect, and is not needed.
Define class method:
class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
Now if bah()
has to be instance method (i.e. have access to self), you can still directly access the class variable.
class Foo(object):
bar = 1
def bah(self):
print self.bar
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
Update March 2013
The expiry date of the provisioning profile is linked to the expiry date of the developer certificate. And I didn't want to wait for it to expire so here is what I did -
x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().
If you want to use the same set of arguments all the time, the following is all you need.
run {
args = ["--myarg1", "--myarg2"]
}
I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY
We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"
--
To make content itself clickable:
HTML
<input type="checkbox" id="activate-div">
<label for="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked ~ label
.my-div{background-color:#000}
To make button change content:
HTML
<input type="checkbox" id="activate-div">
<div class="my-div">
//MY DIV CONTENT
</div>
<label for="activate-div">
//MY BUTTON STUFF
</label>
CSS
#activate-div{display:none}
.my-div{background-color:#FFF}
#activate-div:checked +
.my-div{background-color:#000}
Hope it helps!!
To get body content from javascript ,i have tried the following code:
var frameObj = document.getElementById('id_description_iframe');
var frameContent = frameObj.contentWindow.document.body.innerHTML;
where "id_description_iframe" is your iframe's id. This code is working fine for me.
Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.
SELECT * FROM information_schema.innodb_trx\G
From the document:
The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
This global variable works for my project:
public class Global {
public static int ivar1, ivar2;
public static String svar1, svar2;
public static int[] myarray1 = new int[10];
}
// How to use other or many activity
Global.ivar1 = 10;
int i = Global.ivar1;
To insert a single row of data:
INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');
To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');
To insert multiple rows of data in SQL Server 2008 or later:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'
Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.
As Seth stated thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occuring.
Consider the following method:
private int myInt = 0;
public int AddOne()
{
int tmp = myInt;
tmp = tmp + 1;
myInt = tmp;
return tmp;
}
Now thread A
and thread B
both would like to execute AddOne()
. but A
starts first and reads the value of myInt (0)
into tmp
. Now for some reason the scheduler decides to halt thread A
and defer execution to thread B
. Thread B
now also reads the value of myInt
(still 0
) into it's own variable tmp
. Thread B
finishes the entire method, so in the end myInt = 1
. And 1
is returned. Now it's Thread A
's turn again. Thread A
continues. And adds 1
to tmp
(tmp
was 0
for thread A
). And then saves this value in myInt
. myInt
is again 1
.
So in this case the method AddOne()
was called two times, but because the method was not implemented in a thread safe way the value of myInt
is not 2
, as expected, but 1
because the second thread read the variable myInt
before the first thread finished updating it.
Creating thread safe methods is very hard in non trivial cases. And there are quite a few techniques. In Java you can mark a method as synchronized, this means that only one thread can execute that method at a given time. The other threads wait in line. This makes a method thread safe, but if there is a lot of work to be done in a method, then this wastes a lot of time. Another technique is to 'mark only a small part of a method as synchronized' by creating a lock or semaphore, and locking this small part (usually called the critical section). There are even some methods that are implemented as lockless thread safe, which means that they are built in such a way that multiple threads can race through them at the same time without ever causing problems, this can be the case when a method only executes one atomic call. Atomic calls are calls that can't be interrupted and can only be done by one thread at a time.
This depends very much on the specific case. Preferably, I think one should use the switch
over the if-else
if there are many nested if-elses
.
The question is how much is many?
Yesterday I was asking myself the same question:
public enum ProgramType {
NEW, OLD
}
if (progType == OLD) {
// ...
} else if (progType == NEW) {
// ...
}
if (progType == OLD) {
// ...
} else {
// ...
}
switch (progType) {
case OLD:
// ...
break;
case NEW:
// ...
break;
default:
break;
}
In this case, the 1st if
has an unnecessary second test. The 2nd feels a little bad because it hides the NEW.
I ended up choosing the switch
because it just reads better.
You can use the following CTE as well. You can just modify it as you find fit. But this will add the same values into the student CTE.
This will add 1000 records but you can change it to 10000 or to a maximum of 32767
;WITH thetable(rowid,sname,semail,spassword) AS
(
SELECT 1 , 'name' , 'email' , 'password'
UNION ALL
SELECT rowid+1 ,'name' , 'email' , 'password'
FROM thetable WHERE rowid < 1000
)
SELECT rowid,sname,semail,spassword
FROM thetable ORDER BY rowid
OPTION (MAXRECURSION 1000);
if ( $("#txt").val().length > 0 )
{
// do something
}
Your method fails when there is more than 1 space character inside the textbox.
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
Something else you can try if you are having issues encoding to 'utf-8' and want to go cell by cell you could try the following.
Python 2
(Where "df" is your DataFrame object.)
for column in df.columns:
for idx in df[column].index:
x = df.get_value(idx,column)
try:
x = unicode(x.encode('utf-8','ignore'),errors ='ignore') if type(x) == unicode else unicode(str(x),errors='ignore')
df.set_value(idx,column,x)
except Exception:
print 'encoding error: {0} {1}'.format(idx,column)
df.set_value(idx,column,'')
continue
Then try:
df.to_csv(file_name)
You can check the encoding of the columns by:
for column in df.columns:
print '{0} {1}'.format(str(type(df[column][0])),str(column))
Warning: errors='ignore' will just omit the character e.g.
IN: unicode('Regenexx\xae',errors='ignore')
OUT: u'Regenexx'
Python 3
for column in df.columns:
for idx in df[column].index:
x = df.get_value(idx,column)
try:
x = x if type(x) == str else str(x).encode('utf-8','ignore').decode('utf-8','ignore')
df.set_value(idx,column,x)
except Exception:
print('encoding error: {0} {1}'.format(idx,column))
df.set_value(idx,column,'')
continue
If an Immutable/Singleton collections refers to the one which having only one object and which is not further gets modified, then the same functionality can be achieved by making a collection "UnmodifiableCollection" having only one object. Since the same functionality can be achieved by Unmodifiable Collection with one object, then what special purpose the Singleton Collection serves for?
try this,
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sample, menu);
super.onCreateOptionsMenu(menu,inflater);
}
Finally, in onCreateView
method, add this line to make the options appear in your Toolbar
setHasOptionsMenu(true);
Right click on "Command prompt" or "PowerShell", in menu click "Run as Administrator" (on Windows XP you can just run it as usual).
As Rick Vanover mentions in See what process is using a TCP port in Windows Server 2008
The following command will show what network traffic is in use at the port level:
Netstat -a -n -o
or
Netstat -a -n -o >%USERPROFILE%\ports.txt
(to open the port and process list in a text editor, where you can search for information you want)
Then,
with the PIDs listed in the netstat output, you can follow up with the Windows Task Manager (taskmgr.exe) or run a script with a specific PID that is using a port from the previous step. You can then use the "tasklist" command with the specific PID that corresponds to a port in question.
Example:
tasklist /svc /FI "PID eq 1348"
std::min_element(vec.begin(), vec.end())
- for std::vector
std::min_element(v, v+n)
- for array
std::min_element( std::begin(v), std::end(v) )
- added C++11 version from comment by @JamesKanze
>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>>
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
list(map(chr, [66, 53, 0, 94]))
map(func, *iterables) --> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
"Make an iterator"
means it will return an iterator.
"that computes the function using arguments from each of the iterables"
means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.
So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.
There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
This is a fiddle I always use with my Web applications:
$('body').on('dragstart drop', function(e){
e.preventDefault();
return false;
});
It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.
The expression $(document).ready(function() deprecated in jQuery3.
See working fiddle with jQuery 3 here
Take into account I didn't include the showless button.
Here's the code:
JS
$(function () {
x=3;
$('#myList li').slice(0, 3).show();
$('#loadMore').on('click', function (e) {
e.preventDefault();
x = x+5;
$('#myList li').slice(0, x).slideDown();
});
});
CSS
#myList li{display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
If you are using MAMP on OS X, you will need to change the max_allowed_packet
value in the template for MySQL.
You can find it at: File > Edit template > MySQL my.cnf
Then just search for max_allowed_packet
, change the value and
save.
Here are my working example
@RequestMapping(value = "/api/v1/files/upload", method =RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("files") MultipartFile[] files) {
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<String> tempFileNames = new ArrayList<>();
String tempFileName;
FileOutputStream fo;
try {
for (MultipartFile file : files) {
tempFileName = "/tmp/" + file.getOriginalFilename();
tempFileNames.add(tempFileName);
fo = new FileOutputStream(tempFileName);
fo.write(file.getBytes());
fo.close();
map.add("files", new FileSystemResource(tempFileName));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
String response = restTemplate.postForObject(uploadFilesUrl, requestEntity, String.class);
} catch (IOException e) {
e.printStackTrace();
}
for (String fileName : tempFileNames) {
File f = new File(fileName);
f.delete();
}
return new ResponseEntity<Object>(HttpStatus.OK);
}
If you're using Hive 11 or better you can use the INSERT
statement with the LOCAL
keyword.
Example:
insert overwrite local directory '/home/carter/staging' row format delimited fields terminated by ',' select * from hugetable;
Note that this may create multiple files and you may want to concatenate them on the client side after it's done exporting.
Using this approach means you don't need to worry about the format of the source tables, can export based on arbitrary SQL query, and can select your own delimiters and output formats.
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
TMPDIR
environment variable.TEMP
environment variable.TMP
environment variable.Wimp$ScrapDir
environment variable.C:\TEMP
, C:\TMP
, \TEMP
, and \TMP
, in that order./tmp
, /var/tmp
, and /usr/tmp
, in that order.In MySQL, I use <>
to preferentially place specific rows at the front of a sort request.
For instance, under the column topic
, I have the classifications of 'Chair', 'Metabolomics', 'Proteomics', and 'Endocrine'. I always want to list any individual(s) with the topic 'Chair', first, and then list the other members in alphabetical order based on their topic
and then their name_last
.
I do this with:
SELECT scicom_list ORDER BY topic <> 'Chair',topic,name_last;
This outputs the rows in the order of:
Chair
Endocrine
Metabolomics
Proteomics
Notice that topic <> 'Chair'
is used to select all the rows with 'Chair' first. It then sorts the rows where topic = Chair
by name_last
.*
*This is a bit counterintuitive since <>
equals !=
based on other feedback in this post.
This syntax can also be used to prioritize multiple categories. For instance, if I want to have "Chair" and then "Vice Chair" listed before the rest of the topics, I use the following
SELECT scicom_list ORDER BY topic <> 'Chair',topic <> 'Vice Chair',topic,name_last;
This outputs the rows in the order of:
Chair
Vice Chair
Endocrine
Metabolomics
Proteomics
I know I am posting this answer little late, but I felt it is worth using Google's fuse location provider service to get the current location.
Main features of this api are :
1.Simple APIs: Lets you choose your accuracy level as well as power consumption.
2.Immediately available: Gives your apps immediate access to the best, most recent location.
3.Power-efficiency: It chooses the most efficient way to get the location with less power consumptions
4.Versatility: Meets a wide range of needs, from foreground uses that need highly accurate location to background uses that need periodic location updates with negligible power impact.
It is flexible in while updating in location also.
If you want current location only when your app starts then you can use getLastLocation(GoogleApiClient)
method.
If you want to update your location continuously then you can use requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener)
You can find a very nice blog about fuse location here and google doc for fuse location also can be found here.
Update
According to developer docs starting from Android O they have added new limits on background location.
If your app is running in the background, the location system service computes a new location for your app only a few times each hour. This is the case even when your app is requesting more frequent location updates. However if your app is running in the foreground, there is no change in location sampling rates compared to Android 7.1.1 (API level 25).
The dynamic way of implement whereNotIn:
$users = User::where('status',0)->get();
foreach ($users as $user) {
$data[] = $user->id;
}
$available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();
Depending on what language you are programming in, you can use a function to replace double quotes with two double quotes.
For example in PHP that would be:
str_replace('"', '""', $string);
If you are trying to do that using SQL only, maybe REPLACE() is what you are looking for.
So your query would look something like this:
"UPDATE Table SET columnname = '" & REPLACE(@wstring, '"', '""') & "' where ... blah ... blah "
If you trust the host, either add the valid certificate, specify --no-check-certificate
or add:
check_certificate = off
into your ~/.wgetrc
.
In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.