I made it...
I just write
jQuery('#container').append(html)
instead
document.getElementById('container').innerHTML += html;
If you just want the last character or any character at know position you can simply trat string as an array! - strings are iteratorable in javascript -
Var x = "hello_world";
x[0]; //h
x[x.length-1]; //d
Yet if you need more than just one character then use splice is effective
x.slice(-5); //world
Regarding your example
"rating_element-<?php echo $id?>"
To extract id you can easily use split + pop
Id= inputId.split('rating_element-')[1];
This will return the id, or undefined if no id was after 'rating_element' :)
You can disable sql_mode=only_full_group_by by some command you can try this by terminal or MySql IDE
mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
I have tried this and worked for me. Thanks :)
How about onblur event :
<input type="text" name="name" value="value" onblur="alert(1);"/>
Assuming we're talking SQL Server DateTime
Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:
errorDate BETWEEN '12/20/2008' AND '12/21/2008'
My preferred method for a time range like that is:
'20081220' <= errorDate AND errordate < '20081221'
Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)
Avoids using either shift
or a for
cycle at the cost of size and readability.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set /a arg_idx=1
set "curr_arg_value="
:loop1
if !arg_idx! GTR 9 goto :done
set curr_arg_label=%%!arg_idx!
call :get_value curr_arg_value !curr_arg_label!
if defined curr_arg_value (
echo/!curr_arg_label!: !curr_arg_value!
set /a arg_idx+=1
goto :loop1
)
:done
set /a cnt=!arg_idx!-1
echo/argument count: !cnt!
endlocal
goto :eof
:get_value
(
set %1=%2
)
Output:
count_cmdline_args.bat testing more_testing arg3 another_arg
%1: testing
%2: more_testing
%3: arg3
%4: another_arg
argument count: 4
EDIT: The "trick" used here involves:
Constructing a string that represents a currently evaluated command-line argument variable (i.e. "%1", "%2" etc.) using a string that contains a percent character (%%
) and a counter variable arg_idx
on each loop iteration.
Storing that string into a variable curr_arg_label
.
Passing both that string (!curr_arg_label!
) and a return variable's name (curr_arg_value
) to a primitive subprogram get_value
.
In the subprogram its first argument's (%1
) value is used on the left side of assignment (set
) and its second argument's (%2
) value on the right. However, when the second subprogram's argument is passed it is resolved into value of the main program's command-line argument by the command interpreter. That is, what is passed is not, for example, "%4" but whatever value the fourth command-line argument variable holds ("another_arg" in the sample usage).
Then the variable given to the subprogram as return variable (curr_arg_value
) is tested for being undefined, which would happen if currently evaluated command-line argument is absent. Initially this was a comparison of the return variable's value wrapped in square brackets to empty square brackets (which is the only way I know of testing program or subprogram arguments which may contain quotes and was an overlooked leftover from trial-and-error phase) but was since fixed to how it is now.
Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example)
function intDivide(numerator, denominator) {
return parseInt((numerator/denominator).toString().split(".")[0]);
}
let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
_x000D_
This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin.
Thank You
That basically means that you need to import the .h file containing the declaration of States.
However, there is a lot of other stuff wrong with your code.
+alloc
'ing it. That won't work[super init]
in -init
.@class
in the header, but never imported the class.Here is pythonic way to do it. This function will allow you to loop through key-value pair in all the levels. It does not save the whole thing to the memory but rather walks through the dict as you loop through it
def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield (key, value)
yield from recursive_items(value)
else:
yield (key, value)
a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
for key, value in recursive_items(a):
print(key, value)
Prints
a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6
document.forms[ 'forms1' ].onsubmit = function() {
return [].some.call( this.elements, function( el ) {
return el.type === 'radio' ? el.checked : false
} )
}
Just something out of my head. Not sure the code is working.
Missing implementation of a function in class
The reason I faced this issue was because I had deleted the function's implementation from the cpp file, but forgotten to delete the declaration from the .h file.
My answer doesn't specifically answer your question, but lets people who come to this thread looking for answer know that this can also one cause.
The instructions in the official Python documentation worked for me: https://docs.python.org/2/using/windows.html#executing-scripts
Launch a command prompt.
Associate the correct file group with .py scripts:
assoc .py=Python.File
Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
The example shows how to associate the .py extension with the .pyw executable, but it works if you want to associate the .py extension with the Anaconda Python executable. You need administrative rights. The name "Python.File" could be anything, you just have to make sure is the same name in the ftype command. When you finish and before you try double-clicking the .py file, you must change the "Open with" in the file properties. The file type will be now ".py" and it is opened with the Anaconda python.exe.
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
For linux in case; you can use wget command
import os
url1 = 'YOUR_URL_WHATEVER'
os.system('wget {}'.format(url1))
String.format()
to the rescue!!
The main new feature of Vim 8.1 is support for running a terminal in a Vim window.
:term
will open the terminal in another window inside Vim.
This is a known bug, try to use "axios": "0.13.1"
https://github.com/mzabriskie/axios/issues/378
I had the same problem so I ended up using "axios": "0.12.0"
. It works fine for me.
You can do this:
HTML code:
<form action="submit.php" method="get" id="form">
<a href="javascript: submitForm()">
<img src="save.gif" alt="Save icon"/>
<br/>
save
</a>
</form>
note: you can use and action and method of your choice and Id and any text starting from href="javascript: and ending to ()" but make sure that when I type the same things such as id and some text you type in your replacement in the same places(java script and HTML code).
java script code:
var form=document.getElementById("form");
function submitForm()
{
form.submit();
}
You should use the filter
method rather than map unless you want to mutate the items in the array, in addition to filtering.
eg.
var filteredItems = items.filter(function(item)
{
return ...some condition...;
});
[Edit: Of course you could always do sourceArray.filter(...).map(...)
to both filter and mutate]
Function pointers are a great way to do this, e.g.
result = switchFunction(someStringKey); //result is an optional return value
...this calls a function that you have set by string key (one function per case):
setSwitchFunction("foo", fooFunc);
setSwitchFunction("bar", barFunc);
Use a pre-existing hashmap/table/dictionary implementation such as khash, return that pointer to a function inside of switchFunction()
, and execute it (or just return it from switchFunction()
and execute it yourself). If the map implementation doesn't store that, just use a uint64_t
instead that you cast accordingly to a pointer.
The standard MIME type is application/pdf
. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.
MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.
The use of x-pdf
predates the standardization of the MIME type for PDF. MIME types in the x-
namespace are considered experimental, just as those in the vnd.
namespace are considered vendor-specific. x-pdf
might be used for compatibility with old software.
The first constructor in the header should not end with a semicolon. #include <string>
is missing in the header. string
is not qualified with std::
in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream
is broken. I suggest learning C++ before trying to use it.
Let's fix this up:
//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__
#include <iostream>
#include <string>
class Polygone {
public:
// declarations have to end with a semicolon, definitions do not
Polygone(){} // why would we needs this?
Polygone(const std::string& fichier);
};
# endif
and
//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>
Polygone::Polygone(const std::string& nom)
{
std::ifstream fichier (nom, ios::in);
if (fichier.is_open())
{
// keep the scope as tiny as possible
std::string line;
// getline returns the stream and streams convert to booleans
while ( std::getline(fichier, line) )
{
std::cout << line << std::endl;
}
}
else
{
std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
}
}
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
Below code absolutely worked for me to update File extension.
Ex: abc.pdf to abc.txt
Filepath = "Pls mention your Filepath"
Set objFso = CreateObject("Scripting.FileSystemObject")
'' Below line of code is to get the object for Folder where list of files are located
Set objFolder = objFso.GetFolder(Filepath)
'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files
For Each file In FileCollection
WScript.Echo "File name ->" + file.Name
''Instr used to Return the position of the first occurrence of "." within the File name
s = InStr(1, file.Name, ".",1)
WScript.Echo s
WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))
'Left(file.Name,s-1) = Used to fetch the file name without extension
' Move method is used to move the file in the Desitnation folder you mentioned
file.Move(Filepath & Left(file.Name,s-1)&".txt")
Next
Using the "file" command may be useful for this:
#!/bin/bash
check_file(){
if [ -z "${1}" ] ;then
echo "Please input something"
return;
fi
f="${1}"
result="$(file $f)"
if [[ $result == *"cannot open"* ]] ;then
echo "NO FILE FOUND ($result) ";
elif [[ $result == *"directory"* ]] ;then
echo "DIRECTORY FOUND ($result) ";
else
echo "FILE FOUND ($result) ";
fi
}
check_file "${1}"
Output examples :
$ ./f.bash login
DIRECTORY FOUND (login: directory)
$ ./f.bash ldasdas
NO FILE FOUND (ldasdas: cannot open `ldasdas' (No such file or directory))
$ ./f.bash evil.php
FILE FOUND (evil.php: PHP script, ASCII text)
FYI: the answers above work but you can use -s to help in weird situations by checking for a valid file first:
#!/bin/bash
check_file(){
local file="${1}"
[[ -s "${file}" ]] || { echo "is not valid"; return; }
[[ -d "${file}" ]] && { echo "is a directory"; return; }
[[ -f "${file}" ]] && { echo "is a file"; return; }
}
check_file ${1}
BigDecimal does not seem to respect Locale settings.
Locale.getDefault(); //returns sl_SI
Slovenian locale should have a decimal comma. Guess I had strange misconceptions regarding numbers.
a = new BigDecimal("1,2") //throws exception
a = new BigDecimal("1.2") //is ok
a.toPlainString() // returns "1.2" always
I have edited a part of my message that made no sense since it proved to be due the human error (forgot to commit data and was looking at the wrong thing).
Same as BigDecimal can be said for any Java .toString() functions. I guess that is good in some ways. Serialization for example or debugging. There is an unique string representation.
Also as others mentioned using formatters works OK. Just use formatters, same for the JSF frontend, formatters do the job properly and are aware of the locale.
Many text-editors allow you to change to LF
, see Atom instructions below. Simple and explicit.
Click CRLF
on bottom right:
Select LF
in dropdown on top:
The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.
For IE, I found that changing
.flex > div
{
flex: 1 0 50%;
}
to
.flex > div
{
flex: 1 0 45%;
}
seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.
In the case of Firefox I solved it by adding
display: inline-block;
to the items.
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
There are already great solutions on this page, but all have assumed the dataset is uniformly/evenly sampled/distributed. I will try to provide a more general example of randomly sampled data. I will also use this MATLAB tutorial as an example:
Adding the required modules:
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import scipy.signal
Generating sample data:
N = 600 # Number of samples
t = np.random.uniform(0.0, 1.0, N) # Assuming the time start is 0.0 and time end is 1.0
S = 1.0 * np.sin(50.0 * 2 * np.pi * t) + 0.5 * np.sin(80.0 * 2 * np.pi * t)
X = S + 0.01 * np.random.randn(N) # Adding noise
Sorting the data set:
order = np.argsort(t)
ts = np.array(t)[order]
Xs = np.array(X)[order]
Resampling:
T = (t.max() - t.min()) / N # Average period
Fs = 1 / T # Average sample rate frequency
f = Fs * np.arange(0, N // 2 + 1) / N; # Resampled frequency vector
X_new, t_new = scipy.signal.resample(Xs, N, ts)
Plotting the data and resampled data:
plt.xlim(0, 0.1)
plt.plot(t_new, X_new, label="resampled")
plt.plot(ts, Xs, label="org")
plt.legend()
plt.ylabel("X")
plt.xlabel("t")
Now calculating the FFT:
Y = scipy.fftpack.fft(X_new)
P2 = np.abs(Y / N)
P1 = P2[0 : N // 2 + 1]
P1[1 : -2] = 2 * P1[1 : -2]
plt.ylabel("Y")
plt.xlabel("f")
plt.plot(f, P1)
P.S. I finally got time to implement a more canonical algorithm to get a Fourier transform of unevenly distributed data. You may see the code, description, and example Jupyter notebook here.
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
One solution to this would be a list comprehension, with pattern matching inside your tuple:
>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]
Another way would be using map
and filter
:
>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]
Yes, according to HTML5 drafts you can use the pattern
attribute to specify the allowed input using a regular expression. For some types of data, you can use special input fields like <input type=email>
. But these features still widely lack support or have qualitatively poor support.
Adding a new answer just as a reference for future researchers and as nobody mentioned that yet I think it's valid.
Another good option is ng-grid http://angular-ui.github.io/ng-grid/.
And there's a beta version (http://ui-grid.info/) available already with some improvements:
UPDATE:
It seems UI GRID is not beta anymore.
With the 3.0 release, the repository has been renamed from "ng-grid" to "ui-grid".
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
In my case I've to specify the complete package name of library UI component that I use in my layout file.
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
There are some ways to overcome the cross-domain barrier:
There are some plugins that help with cross-domain requests:
Heads up!
The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction. But if you can't do that in back-end, then pay attention to the following tips.
Using third-party proxies is not a secure practice, because they can keep track of your data, so it can be used with public information, but never with private data.
CORS Anywhere is a node.js proxy which adds CORS headers to the proxied request.
To use the API, just prefix the URL with the API URL. (Supports https: see github repository)
If you want to automatically enable cross-domain requests when needed, use the following snippet:
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
Whatever Origin is a cross domain jsonp access. This is an open source alternative to anyorigin.com.
To fetch the data from google.com, you can use this snippet:
// It is good specify the charset you expect.
// You can use the charset you want instead of utf-8.
// See details for scriptCharset and contentType options:
// http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
$.ajaxSetup({
scriptCharset: "utf-8", //or "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function (data) {
console.log("> ", data);
//If the expected response is text/plain
$("#viewer").html(data.contents);
//If the expected response is JSON
//var response = $.parseJSON(data.contents);
});
CORS Proxy is a simple node.js proxy to enable CORS request for any website. It allows javascript code on your site to access resources on other domains that would normally be blocked due to the same-origin policy.
How does it work? CORS Proxy takes advantage of Cross-Origin Resource Sharing, which is a feature that was added along with HTML 5. Servers can specify that they want browsers to allow other websites to request resources they host. CORS Proxy is simply an HTTP Proxy that adds a header to responses saying "anyone can request this".
This is another way to achieve the goal (see www.corsproxy.com). All you have to do is strip http:// and www. from the URL being proxied, and prepend the URL with www.corsproxy.com/
$.get(
'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
Recently I found this one, it involves various security oriented Cross Origin Remote Sharing utilities. But it is a black-box with Flash as backend.
You can see it in action here: CORS proxy browser
Get the source code on GitHub: koto/cors-proxy-browser
use the HorizontalContentAlignment property.
Sample
<Label HorizontalContentAlignment="Center"/>
No such thing, probably just a macro for int
I didn't want to change the background of my input text neither it will work with my SVG icon.
What i did is adding negative margin to the icon so it appear inside the input box
and adding same value padding to the input so text won't go under the icon.
<div class="search-input-container">
<input
type="text"
class="search-input"
style="padding-right : 30px;"
/>
<img
src="@/assets/search-icon.svg"
style="margin-left: -30px;"
/>
</div>
*inline-style is for readability consider using classes
try this below solution:
exclude:path.resolve(__dirname, "node_modules")
I've just spent 2 hours battling with jQuery Upload but gave up because of the amount of dependencies (I had 13 JS files included to get all the bells and whistles).
I did a bit more searching and came across a neat project called Dropzone.js, which does not have any dependencies.
The author has also created a bootstrap demo which was inspired by the jQuery File Upload plugin.
I hope this saves someone else some time.
This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<a id="link" href="#">show box</a>
<div id="box" style="background: #eee; display: none">
<p>a paragraph of text</p>
<input type="file" />
</div>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var box = $('#box');
var link = $('#link');
link.click(function() {
box.show(); return false;
});
$(document).click(function() {
box.hide();
});
box.click(function(e) {
e.stopPropagation();
});
</script>
</body>
</html>
Here's what I do:
<?php
/**
* /application/core/MY_Loader.php
*
*/
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
For CI 3.x:
class MY_Loader extends CI_Loader {
public function template($template_name, $vars = array(), $return = FALSE)
{
if($return):
$content = $this->view('templates/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('templates/footer', $vars, $return);
return $content;
else:
$this->view('templates/header', $vars);
$this->view($template_name, $vars);
$this->view('templates/footer', $vars);
endif;
}
}
Then, in your controller, this is all you have to do:
<?php
$this->load->template('body');
I tested this for version 2.4 of artifact org.codehaus.mojo and that worked ~
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlDirectory>path/to/dir/wsdl</wsdlDirectory>
</configuration>
<id>wsimport-web-service</id>
<phase>generate-sources</phase>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>javax.xml</groupId>
<artifactId>webservices-api</artifactId>
<version>${webservices-api-version}</version>
</dependency>
</dependencies>
<configuration>
<vmArgs>
<vmArg>-Djavax.xml.accessExternalSchema=all</vmArg>
</vmArgs>
<sourceDestDir>generated-sources/jaxws-wsimport</sourceDestDir>
<xnocompile>true</xnocompile>
<verbose>true</verbose>
<extension>true</extension>
<sei>/</sei>
</configuration>
</plugin>
</plugins>
VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.
The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues
you just add this style in your style.xml
file which is in your values folder
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
After that set this style to your activity class in your AndroidManifest.xml file
android:theme="@style/AppTheme.NoActionBar"
Edit:- If you are going with programmatic way to hide ActionBar then use below code in your activity onCreate()
method.
if(getSupportedActionbar()!=null)
this.getSupportedActionBar().hide();
and if you want to hide ActionBar from Fragment then
getActivity().getSupportedActionBar().hide();
AppCompat v7:-
Use following theme in your Activities where you don't want actiobBar Theme.AppComat.NoActionBar
or Theme.AppCompat.Light.NoActionBar
or if you want to hide in whole app then set this theme in your <application... />
in your AndroidManifest
.
In Kotlin:
add this line of code in your onCreate()
method or you can use above theme.
if (supportActionBar != null)
supportActionBar?.hide()
i hope this will help you more.
Posting this for Xamarin users.
The key to detecting if the app was launched via a push notification is the AppDelegate.FinishedLaunching(UIApplication app, NSDictionary options)
method, and the options dictionary that's passed in.
The options dictionary will have this key in it if it's a local notification: UIApplication.LaunchOptionsLocalNotificationKey
.
If it's a remote notification, it will be UIApplication.LaunchOptionsRemoteNotificationKey
.
When the key is LaunchOptionsLocalNotificationKey
, the object is of type UILocalNotification
.
You can then look at the notification and determine which specific notification it is.
Pro-tip: UILocalNotification
doesn't have an identifier in it, the same way UNNotificationRequest
does. Put a dictionary key in the UserInfo containing a requestId so that when testing the UILocalNotification
, you'll have a specific requestId available to base some logic on.
I found that even on iOS 10+ devices that when creating location notifications using the UNUserNotificationCenter
's AddNotificationRequest
& UNMutableNotificationContent
, that when the app is not running(I killed it), and is launched by tapping the notification in the notification center, that the dictionary still contains the UILocalNotificaiton
object.
This means that my code that checks for notification based launch will work on iOS8 and iOS 10+ devices
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
_logger.InfoFormat("FinishedLaunching");
if(options != null)
{
if (options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey))
{
//was started by tapping a local notification when app wasn't previously running.
//works if using UNUserNotificationCenter.Current.AddNotificationRequest OR UIApplication.SharedApplication.PresentLocalNotificationNow);
var localNotification = options[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification;
//I would recommended a key such as this :
var requestId = localNotification.UserInfo["RequestId"].ToString();
}
}
return true;
}
You can also use :f followed by :w
In [42]: a = [4, 6, 12]
In [43]: [sum(a[:i+1]) for i in xrange(len(a))]
Out[43]: [4, 10, 22]
This is slighlty faster than the generator method above by @Ashwini for small lists
In [48]: %timeit list(accumu([4,6,12]))
100000 loops, best of 3: 2.63 us per loop
In [49]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100000 loops, best of 3: 2.46 us per loop
For larger lists, the generator is the way to go for sure. . .
In [50]: a = range(1000)
In [51]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100 loops, best of 3: 6.04 ms per loop
In [52]: %timeit list(accumu(a))
10000 loops, best of 3: 162 us per loop
Using CSS3 you don't need to make your own image with the transparency.
Just have a div with the following
position:absolute;
left:0;
background: rgba(255,255,255,.5);
The last parameter in background (.5) is the level of transparency (a higher number is more opaque).
To change the Android-x86 screen resolution on VirtualBox you need to:
Add custom screen resolution:
Android <6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x16"
Android >=6.0:
VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"
Figure out what is the ‘hex’-value for your VideoMode
:
2.1. Start the VM
2.2. In GRUB menu enter a (Android >=6.0: e)
2.3. In the next screen append vga=ask
and press Enter
2.4. Find your resolution and write down/remember the 'hex'-value for Mode
column
Translate the value to decimal notation (for example 360
hex is 864
in decimal).
Go to menu.lst
and modify it:
4.1. From the GRUB menu select Debug Mode
4.2. Input the following:
mount -o remount,rw /mnt
cd /mnt/grub
vi menu.lst
4.3. Add vga=864
(if your ‘hex’-value is 360
). Now it should look like this:
kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode DPI=160 UVESA_MODE=320x480 SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img vga=864
4.4. Save it:
:wq
Unmount and reboot:
cd /
umount /mnt
reboot -f
Hope this helps.
Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.
same example
... ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
... div collapse="isCollapsed"> ...
with
@media screen and (min-width: 768px) {
.collapse{
display: block !important;
}
}
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
I am using a bit of PHP to achieve the result. It's a bit rusty though. But it should work.
<?php
function pref(){
return (isset($_SERVER['HTTP_REFERER'])) ? true : '';
}
?>
<html>
<body>
<input type="hidden" id="_pref" value="<?=pref()?>">
<button type="button" id="myButton">GoBack</button>
<!-- Include jquery library -->
<script>
if (!$('#_pref').val()) {
$('#myButton').hide() // or $('#myButton').remove()
}
</script>
</body>
</html>
You can find a nice list of corresponding URL encoded characters on W3Schools.
+
becomes %2B
%20
You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.
Before using a BackgroundWorker
consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.
BackgroundWorker.CancelAsync()
will set CancellationPending
to true
but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending
.
Thread.Abort()
on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.
Threading needs very careful consideration no matter what the task, for some further reading:
Parallel Programming in the .NET Framework Managed Threading Best Practices
I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all
<div class="nav-collapse collapse" >
Simply add the properties as such, like on the MENU button
<div class="nav-collapse collapse" data-toggle="collapse" data-target=".nav-collapse">
I've added to <body>
as well, worked. Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.
DK
I would do it using a for loop as shown below :
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
set - unordered collection of unique elements. List of elements can be passed to set's constructor. So, pass list with duplicate elements, we get set with unique elements and transform it back to list then get list with unique elements. I can say nothing about performance and memory overhead, but I hope, it's not so important with small lists.
list(set(my_not_unique_list))
Simply and short.
Don't forget to reboot your computer after installing node! That one got me.
You can use the Material Design Switch for Bootstrap 3.3.0
http://bootsnipp.com/snippets/featured/material-design-switch
There are no values that will cause the checkbox to be unchecked. If the checked
attribute exists, the checkbox will be checked regardless of what value you set it to.
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).
In SQL Server, you can do:
select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)
This attempts the conversion, keeping the previous value if available.
Note: I hope you learned a lesson about storing dates as dates and not strings.
In XCode menu Product->Clean and then Product->Build worked for me. I encountered this issue when added new ViewController to my project in new Group/Folder.
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
Value cannot be null. Parameter name: source
Above error comes in situation when you are querying the collection which is null.
For demonstration below code will result in such an exception.
Console.WriteLine("Hello World");
IEnumerable<int> list = null;
list.Where(d => d ==4).FirstOrDefault();
Here is the output of the above code.
Hello World Run-time exception (line 11): Value cannot be null. Parameter name: source
Stack Trace:
[System.ArgumentNullException: Value cannot be null. Parameter name: source] at Program.Main(): line 11
In your case ListMetadataKor
is null.
Here is the fiddle if you want to play around.
Highlight "B1" and press F4. This will lock the cell.
Now you can drag it around and it will not change. The principle is simple. It adds a dollar sign before both coordinates. A dollar sign in front of a coordinate will lock it when you copy the formula around. You can have partially locked coordinates and fully locked coordinates.
It is very convenient to use train_test_split
without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split
not changing partition sizes won`t give initially intended partition:
x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))
Then the portion of validation and test sets in the x_remain change and could be counted as
new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0
new_val_size = 1.0 - new_test_size
x_val, x_test = train_test_split(x_remain, test_size=new_test_size)
In this occasion all initial partitions are saved.
If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I'm just shooting in the dark here.
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
@loginame = N'MyNewAdminUser',
@rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
This is a simplified method:
svg{
font : bold 70px Century Gothic, Arial;
width : 100%;
height : 120px;
}
text{
fill : none;
stroke : black;
stroke-width : .5px;
stroke-linejoin : round;
animation : 2s pulsate infinite;
}
@keyframes pulsate {
50%{ stroke-width:5px }
}
_x000D_
<svg viewBox="0 0 450 50">
<text y="50">Scalable Title</text>
</svg>
_x000D_
Here's a more complex demo.
If you need just one character and you don't want to keep things in the buffer, you can simply read a whole line and drop everything that isn't needed.
Replace:
stdin.read(1)
with
stdin.readline().strip()[:1]
This will read a line, remove spaces and newlines and just keep the first character.
For anyone learning this stuff, comments are more important, so drawing on Xak Tacit's idea
(from User500099's link) for Single Property comments, add this to the top of the XAML code block:
<!--Comments Allowed With Markup Compatibility (mc) In XAML!
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
Usage in property:
ØignoreØ:AttributeToIgnore="Text Of AttributeToIgnore"-->
Then in the code block
<Application FooApp:Class="Foo.App"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ØignoreØ="http://www.galasoft.ch/ignore"
mc:Ignorable="ØignoreØ"
...
AttributeNotToIgnore="TextNotToIgnore"
...
...
ØignoreØ:IgnoreThisAttribute="IgnoreThatText"
...
>
</Application>
Simply you could use:
PartialView("../ABC/XXX")
I was facing the same issue but I mitigated it by placing:
server.timeout = 0;
before server.listen
. server
is an HTTP server here. The default timeout is 2 minutes as per the API documentation.
It is happening because your .bash_profile is not reflecting changes.To reflect it, just use the following command
$ source .bash_profile
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".
Using a check for newkey!=oldkey
, this way you can do:
if newkey!=oldkey:
dictionary[newkey] = dictionary[oldkey]
del dictionary[oldkey]
Use the Oracle documentation and search for keyword "trigger" in your browser.
This approach should work with other metadata type questions.
interesting_keys = ('l', 'm', 'n')
subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict}
You can see that JSONObject extends a HashMap
, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
The term "asynchronous" can be used in slightly different meanings, resulting in seemingly conflicting answers here, while they are actually not. Wikipedia on Asynchrony has this definition:
Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be "outside" events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.
non-JavaScript code can queue such "outside" events to some of JavaScript's event queues. But that is as far as it goes.
There is no external interruption of running JavaScript code in order to execute some other JavaScript code in your script. Pieces of JavaScript are executed one after the other, and the order is determined by the order of events in each event queue, and the priority of those queues.
For instance, you can be absolutely sure that no other JavaScript (in the same script) will ever execute while the following piece of code is executing:
let a = [1, 4, 15, 7, 2];
let sum = 0;
for (let i = 0; i < a.length; i++) {
sum += a[i];
}
In other words, there is no preemption in JavaScript. Whatever may be in the event queues, the processing of those events will have to wait until such piece of code has ran to completion. The EcmaScript specification says in section 8.4 Jobs and Jobs Queues:
Execution of a Job can be initiated only when there is no running execution context and the execution context stack is empty.
As others have already written, there are several situations where asynchrony comes into play in JavaScript, and it always involves an event queue, which can only result in JavaScript execution when there is no other JavaScript code executing:
setTimeout()
: the agent (e.g. browser) will put an event in an event queue when the timeout has expired. The monitoring of the time and the placing of the event in the queue happens by non-JavaScript code, and so you could imagine this happens in parallel with the potential execution of some JavaScript code. But the callback provided to setTimeout
can only execute when the currently executing JavaScript code has ran to completion and the appropriate event queue is being read.
fetch()
: the agent will use OS functions to perform an HTTP request and monitor for any incoming response. Again, this non-JavaScript task may run in parallel with some JavaScript code that is still executing. But the promise resolution procedure, that will resolve the promise returned by fetch()
, can only execute when the currently executing JavaScript has ran to completion.
requestAnimationFrame()
: the browser's rendering engine (non-JavaScript) will place an event in the JavaScript queue when it is ready to perform a paint operation. When JavaScript event is processed the callback function is executed.
queueMicrotask()
: immediately places an event in the microtask queue. The callback will be executed when the call stack is empty and that event is consumed.
There are many more examples, but all these functions are provided by the host environment, not by core EcmaScript. With core EcmaScript you can synchronously place an event in a Promise Job Queue with Promise.resolve()
.
EcmaScript provides several language constructs to support the asynchrony pattern, such as yield
, async
, await
. But let there be no mistake: no JavaScript code will be interrupted by an external event. The "interruption" that yield
and await
seem to provide is just a controlled, predefined way of returning from a function call and restoring its execution context later on, either by JS code (in the case of yield
), or the event queue (in the case of await
).
When JavaScript code accesses the DOM API, this may in some cases make the DOM API trigger one or more synchronous notifications. And if your code has an event handler listening to that, it will be called.
This may come across as pre-emptive concurrency, but it is not: once your event handler(s) return(s), the DOM API will eventually also return, and the original JavaScript code will continue.
In other cases the DOM API will just dispatch an event in the appropriate event queue, and JavaScript will pick it up once the call stack has been emptied.
It is just this:
if 'errormessage' in kwargs:
print("yeah it's here")
You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict
(where some_key
is something hashable, not necessarily a string).
The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals()
and globals()
. Your example is similar, because you are checking existence of specific key in kwargs
dictionary (the dictionary containing keyword arguments).
I find this simple T-SQL query useful for returning valid e-mail addresses
SELECT email
FROM People
WHERE email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0
The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.
It can be reversed to do what you want like this:
SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)
Well there is an easier way
First Give your checkboxes a class example 'id_chk'
Then inside the checkbox wich will control 'id_chk' checkboxes state put:
<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />
Thats all, hope this helps
Why stop at just the instance name? You can inventory your SQL Server environment with following:
SELECT
SERVERPROPERTY('ServerName') AS ServerName,
SERVERPROPERTY('MachineName') AS MachineName,
CASE
WHEN SERVERPROPERTY('InstanceName') IS NULL THEN ''
ELSE SERVERPROPERTY('InstanceName')
END AS InstanceName,
'' as Port, --need to update to strip from Servername. Note: Assumes Registered Server is named with Port
SUBSTRING ( (SELECT @@VERSION),1, CHARINDEX('-',(SELECT @@VERSION))-1 ) as ProductName,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
SERVERPROPERTY('ProductBuild') AS ProductBuild,
SERVERPROPERTY('Edition') AS Edition,
CASE SERVERPROPERTY('EngineEdition')
WHEN 1 THEN 'PERSONAL'
WHEN 2 THEN 'STANDARD'
WHEN 3 THEN 'ENTERPRISE'
WHEN 4 THEN 'EXPRESS'
WHEN 5 THEN 'SQL DATABASE'
WHEN 6 THEN 'SQL DATAWAREHOUSE'
END AS EngineEdition,
CASE SERVERPROPERTY('IsHadrEnabled')
WHEN 0 THEN 'The Always On Availability Groups feature is disabled'
WHEN 1 THEN 'The Always On Availability Groups feature is enabled'
ELSE 'Not applicable'
END AS HadrEnabled,
CASE SERVERPROPERTY('HadrManagerStatus')
WHEN 0 THEN 'Not started, pending communication'
WHEN 1 THEN 'Started and running'
WHEN 2 THEN 'Not started and failed'
ELSE 'Not applicable'
END AS HadrManagerStatus,
CASE SERVERPROPERTY('IsSingleUser') WHEN 0 THEN 'No' ELSE 'Yes' END AS InSingleUserMode,
CASE SERVERPROPERTY('IsClustered')
WHEN 1 THEN 'Clustered'
WHEN 0 THEN 'Not Clustered'
ELSE 'Not applicable'
END AS IsClustered,
'' as ServerEnvironment,
'' as ServerStatus,
'' as Comments
This is exactly what I needed for my MVC site configuration!
I added a little modification to the OnException
method to handle multiple HandleErrorAttribute
instances, as suggested by Atif Aziz:
bear in mind that you may have to take care that if multiple
HandleErrorAttribute
instances are in effect then duplicate logging does not occur.
I simply check context.ExceptionHandled
before invoking the base class, just to know if someone else handled the exception before current handler.
It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.
Hope it is useful:
public override void OnException(ExceptionContext context)
{
bool exceptionHandledByPreviousHandler = context.ExceptionHandled;
base.OnException(context);
Exception e = context.Exception;
if (exceptionHandledByPreviousHandler
|| !context.ExceptionHandled // if unhandled, will be logged anyhow
|| RaiseErrorSignal(e) // prefer signaling, if possible
|| IsFiltered(context)) // filtered?
return;
LogException(e);
}
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
Combination of Mritunjay and Bartu's answers are full answer to this question. I copying the full example.
<input class="form-control" type="email" required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>
Here,
this.setCustomValidity('Please Enter valid email')" - Display the custom message on invalidated of the field
oninput="setCustomValidity('')" - Remove the invalidate message on validated filed.
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
An answer using PIL (just in case it's useful).
given a numpy array "A":
from PIL import Image
im = Image.fromarray(A)
im.save("your_file.jpeg")
you can replace "jpeg" with almost any format you want. More details about the formats here
Add class text-center
to your column:
<div class="col text-center">
I am centered
</div>
ctype_digit
was built precisely for this purpose.
In a very general way and to support SQL server here is
SELECT TOP(N) *
FROM tbl_name
ORDER BY tbl_id DESC
and for the performance, it is not bad (less than one second for more than 10,000 records On Server machine)
With the option FollowSymLinks enabled:
$ rg "FollowSymLinks" /etc/httpd/
/etc/httpd/conf/httpd.conf
269: Options Indexes FollowSymLinks
you need all the directories in symlink to be executable by the user httpd is using.
so for this general use case:
cd /path/to/your/web
sudo ln -s $PWD /srv/http/
You can check owner an permissions with namei:
$ namei -m /srv/http/web
f: /srv/http/web
drwxr-xr-x /
drwxr-xr-x srv
drwxr-xr-x http
lrwxrwxrwx web -> /path/to/your/web
drwxr-xr-x /
drwxr-xr-x path
drwx------ to
drwxr-xr-x your
drwxr-xr-x web
In my case to
directory was only executable for my user:
Enable execution by others solve it:
chmod o+x /path/to
See the non executable directory could be different, or you need to affect groups instead others, that depends on your case.
In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:
sc.exe config Service obj= user password= pass
Specyfying the .exe extension, PowerShell bypasses the alias lookup.
HTH
What would be the right thing to use to write to the Windows equivalent of stdout?
In effect, but very unfortunately, both Windows PowerShell and PowerShell Core as of v7.0, send all of their 6(!) output streams to stdout when called from the outside, via PowerShell's CLI.
See this GitHub issue for a discussion of this problematic behavior, which likely won't get fixed for the sake of backward compatibility.
In practice, this means that whatever PowerShell stream you send output to will be seen as stdout output by an external caller:
E.g., if you run the following from cmd.exe
, you'll see no output, because the stdout redirection to NUL
applies equally to all PowerShell streams:
C:\>powershell -noprofile -command "Write-Error error!" >NUL
However - curiously - if you redirect stderr, PowerShell does send its error stream to stderr, so that with 2>
you can capture the error-stream output selectively; the following outputs just 'hi'
- the success-stream output - while capturing the error-stream output in file err.txt
:
C:\>powershell -noprofile -command "'hi'; Write-Error error!" 2>err.txt
The desirable behavior is:
1
) to stdout.Send output from all other streams to stderr, which is the only option, given that between processes only 2 output streams exist - stdout (standard output) for data, and stderr (standard error) for error messages and all other types of messages - such as status information - that aren't data.
It's advisable to make this distinction in your code, even though it currently isn't being respected.
Inside PowerShell:
Write-Host
is for display output, and bypasses the success output stream - as such, its output can neither be (directly) captured in a variable nor suppressed nor redirected.
Its original intent was simply to create user feedback and create simple, console-based user interfaces (colored output).
Due to the prior inability to be captured or redirected, PowerShell version 5 made Write-Host
to the newly introduced information stream (number 6
), so since then it is possible to capture and redirect Write-Host
output.
Write-Error
is meant for writing non-terminating errors to the error stream (number 2
); conceptually, the error stream is the equivalent of stderr.
Write-Output
writes to the success [output] stream (number 1
), which is conceptually equivalent to stdout; it is the stream to write data (results) to.
Write-Output
is rarely needed due to PowerShell's implicit output feature:
Write-Output "Honey, I'm $HOME"
and "Honey, I'm $HOME"
are equivalent, with the latter not only being more concise, but also faster.Here is the sh for last used simulator and application. Just run sh and copy printed text and paste and run command for show in finder.
#!/bin/zsh
lastUsedSimulatorAndApplication=`ls -td -- ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Data/Application/*/ | head -n1`
echo $lastUsedSimulatorAndApplication
WORKING:
$("#ContentPlaceHolder1_txtNombre").keyup(function () {
var txt = $(this).val();
$('.column').each(function () {
$(this).show();
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
$(this).hide();
}
});
//}
});
My answer, cobbling together others' answers. This should correct for the failure to compensate for numeric keys:
function array_to_xml($array, $root, $element) {
$xml = new SimpleXMLElement("<{$root}/>");
foreach ($array as $value) {
$elem = $xml->addChild($element);
xml_recurse_child($elem, $value);
}
return $xml;
}
function xml_recurse_child(&$node, $child) {
foreach ($child as $key=>$value) {
if(is_array($value)) {
foreach ($value as $k => $v) {
if(is_numeric($k)){
xml_recurse_child($node, array($key => $v));
}
else {
$subnode = $node->addChild($key);
xml_recurse_child($subnode, $value);
}
}
}
else {
$node->addChild($key, $value);
}
}
}
The array_to_xml()
function presumes that the array is made up of numeric keys first. If your array had an initial element, you would drop the foreach()
and $elem
statements from the array_to_xml()
function and just pass $xml
instead.
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P
Type Debugger for Chrome in the search bar, install it and enable it.
In your launch.json
file add this config :
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch localhost with sourcemaps",
"type": "chrome",
"request": "launch",
"url": "http://localhost/mypage.html",
"webRoot": "${workspaceRoot}/app/files",
"sourceMaps": true
},
{
"name": "Launch index.html (without sourcemaps)",
"type": "chrome",
"request": "launch",
"file": "${workspaceRoot}/index.html"
},
]
}
You must launch Chrome with remote debugging enabled in order for the extension to attach to it.
Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222
In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
In a terminal, launch google-chrome --remote-debugging-port=9222
Do this to distinguish that.
If for example your number is 3.1214 and stored in num but you don't know kind of num:
num = 3.1214
// cast num to int
int x = (int)num;
if(x == num)
{
// num is a integer
}
else
// num is float
}
In this example we see that num is not integer.
Using:
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
//do your ReconTool stuff
}
}
will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.
Using maven just use mvn spring-boot:run
while in gradle it would be gradle bootRun
An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner
. That would look like:
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//implement your business logic here
}
}
Check out this guide from Spring's official guide repository.
The full Spring Boot documentation can be found here
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
I have made a Windows command line tool that do just that.
You can download it here: http://commandline.dk/csv2ddl.htm
Usage:
C:\Temp>csv2ddl.exe mysql test.csv test.sql
Or
C:\Temp>csv2ddl.exe mysql advanced doublequote comma test.csv test.sql
@Konrad what surprises me is that in my tests, I'm passing the list into a method that accepts IEnumerable<T>
, so the runtime can't optimize it by calling the Count() extension method for IList<T>
.
I can only assume that the Count() extension method for IEnumerable is doing something like this:
public static int Count<T>(this IEnumerable<T> list)
{
if (list is IList<T>) return ((IList<T>)list).Count;
int i = 0;
foreach (var t in list) i++;
return i;
}
... in other words, a bit of runtime optimization for the special case of IList<T>
.
/EDIT @Konrad +1 mate - you're right about it more likely being on ICollection<T>
.
This is due to spring-config.xml is not in classpath.
Add complete path of spring-config.xml to your classpath.
Also write command you execute to run your project. You can check classpath in command.
Simple way to get this done !!
public int findNearestPositive(int array[])
{
boolean isNegative=false;
int number=0;
int value=0;
if(array[0]<=0 && array[array.length-1]<0)
{
return 1;
}
for(int i=0;i<array.length;i++)
{
value=i+1;
isNegative=false;
for(int j=0;j<array.length;j++)
{
if(value==array[j])
{
isNegative=true;
}
}
if(isNegative!=true)
{
if(number==0){
number=value;
}else if(value<number){
number=value;
}
}
}
if(number==0)
{
number=value+1;
}
return number;
}
Newer version:
GlideApp.with(imageView)
.asBitmap()
.override(200, 200)
.centerCrop()
.load(mUrl)
.error(R.drawable.defaultavatar)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.signature(ObjectKey(System.currentTimeMillis() / (1000*60*60*24))) //refresh avatar cache every day
.into(object : CustomTarget<Bitmap>(){
override fun onLoadCleared(placeholder: Drawable?) {}
override fun onLoadFailed(errorDrawable: Drawable?) {
//add context null check in case the user left the fragment when the callback returns
context?.let { imageView.addImage(BitmapFactory.decodeResource(resources, R.drawable.defaultavatar)) }
}
override fun onResourceReady(
resource: Bitmap,
transition: Transition<in Bitmap>?) { context?.let { imageView.addImage(resource) } }
})
The dictionary:
d={'key1':'value1','key2':'value2','key3':'value3'}
Another one line solution:
print(*d.items(), sep='\n')
Output:
('key1', 'value1')
('key2', 'value2')
('key3', 'value3')
(but, since no one has suggested something like this before, I suspect it is not good practice)
Hide the keyboard
editText.setInputType(InputType.TYPE_NULL);
Show Keyboard
etData.setInputType(InputType.TYPE_CLASS_TEXT);
etData.setFocusableInTouchMode(true);
in the parent layout
android:focusable="false"
Perl Code for Unix systems:
# Capture date from shell
my $current_date = `date +"%m/%d/%Y"`;
# Remove newline character
$current_date = substr($current_date,0,-1);
print $current_date, "\n";
How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull()
.
When executable path has whitespace in system, call
#include<iostream>
using namespace std;
int main()
{
system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
system("pause");
return 0;
}
Schema is a way of categorising the objects in a database. It can be useful if you have several applications share a single database and while there is some common set of data that all application accesses.
Here is a little code to accomplish it:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
For Windows 10 the event ID for lock=4800 and unlock=4801.
As it says in the answer provided by Mario and User 00000, you will need to enable logging of lock and unlock events by using their method described above by running gpedit.msc and navigating to the branch they indicated:
Computer Configuration -> Windows Settings -> Security Settings -> Advanced Audit Policy Configuration -> System Audit Policies - Local Group Policy Object -> Logon/Logoff -> Audit Other Login/Logoff
Enable for both success and failure events.
After enabling logging of those events you can filter for Event ID 4800 and 4801 directly.
This method works for Windows 10 as I just used it to filter my security logs after locking and unlocking my computer.
Be careful:
strip
does a rstrip and lstrip (removes leading and trailing spaces, tabs, returns and form feeds, but it does not remove them in the middle of the string).
If you only replace spaces and tabs you can end up with hidden CRLFs that appear to match what you are looking for, but are not the same.
You don't want to do that. It can cause undefined behavior depending on the collection. You want to use an Iterator directly. Although the for each construct is syntactic sugar and is really using an iterator, it hides it from your code so you can't access it to call Iterator.remove
.
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Instead write your code:
List<String> names = ....
Iterator<String> it = names.iterator();
while (it.hasNext()) {
String name = it.next();
// Do something
it.remove();
}
Note that the code calls Iterator.remove
, not List.remove
.
Addendum:
Even if you are removing an element that has not been iterated over yet, you still don't want to modify the collection and then use the Iterator
. It might modify the collection in a way that is surprising and affects future operations on the Iterator
.
java.time.temporal.ChronoUnit.DAYS.between(
earlier.toLocalDate(),
later.toLocalDate()
)
…or…
java.time.temporal.ChronoUnit.HOURS.between(
earlier.truncatedTo( ChronoUnit.HOURS ) ,
later.truncatedTo( ChronoUnit.HOURS )
)
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
The equivalent of Joda-Time DateTime
is ZonedDateTime
.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Apparently you want to count the days by dates, meaning you want to ignore the time of day. For example, starting a minute before midnight and ending a minute after midnight should result in a single day. For this behavior, extract a LocalDate
from your ZonedDateTime
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate localDateStart = zdtStart.toLocalDate() ;
LocalDate localDateStop = zdtStop.toLocalDate() ;
Use the ChronoUnit
enum to calculate elapsed days or other units.
long days = ChronoUnit.DAYS.between( localDateStart , localDateStop ) ;
As for you asking about a more general way to do this counting where you are interested the delta of hours as hour-of-the-clock rather than complete hours as spans-of-time of sixty minutes, use the truncatedTo
method.
Here is your example of 14:45 to 15:12 on same day.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime start = ZonedDateTime.of( 2017 , 1 , 17 , 14 , 45 , 0 , 0 , z );
ZonedDateTime stop = ZonedDateTime.of( 2017 , 1 , 17 , 15 , 12 , 0 , 0 , z );
long hours = ChronoUnit.HOURS.between( start.truncatedTo( ChronoUnit.HOURS ) , stop.truncatedTo( ChronoUnit.HOURS ) );
1
This does not work for days. Use toLocalDate() in this case.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
DROP TABLE IF EXISTS [table_name]
it first checks if the table exists, if it does it deletes the table while
DROP TABLE [table_name]
it deletes without checking, so if it doesn't exist it exits with an error
First extract the path element from the URL:
from urllib.parse import urlparse
parsed= urlparse('https://www.dummy.example/this/is/PATH?q=/a/b&r=5#asx')
and then you can extract the last segment with string functions:
parsed.path.rpartition('/')[2]
(example resulting to 'PATH'
)
You'll have to use an HttpServletRequestWrapper:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
@Override
public String getHeader(String name) {
final String value = request.getParameter(name);
if (value != null) {
return value;
}
return super.getHeader(name);
}
};
chain.doFilter(wrapper, response);
}
Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames
for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.
A simpler way which eliminates checking if the app can open the url.
loadInBrowser = () => {
Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
};
Calling it with a button.
<Button title="Open in Browser" onPress={this.loadInBrowser} />
I had a similar issue I was getting the entire object in this
but the value was displaying while doing #each
.
Solution: I re-structure my array of object like this:
let list = results.map((item)=>{
return { name:item.name, author:item.author }
});
and then in template file:
{{#each list}}
<tr>
<td>{{name }}</td>
<td>{{author}}</td>
</tr>
{{/each}}
You can also pass the environment to script/server:
$ script/server -e production
OpenCode appears to be a project at the MIT Media Lab for running Java Code online in a web browser interface. Years ago, I played around a lot at TopCoder. It runs a Java Web Start app, though, so you would need a Java run time installed.
The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.
Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).
Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.
Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/
If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.
Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Older response
I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.
What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.
Update: See this SO post -- https://stackoverflow.com/a/9567402/413254
This will surely work .
To Disable a button
$('#btn_id').button('disable');
To Enable a button
$('#btn_id').button('enable');
You're not reading the file content:
my_file_contents = f.read()
See the docs for further infos
You could, without calling read()
or readlines()
loop over your file object:
f = open('goodlines.txt')
for line in f:
print(line)
If you want a list out of it (without \n
as you asked)
my_list = [line.rstrip('\n') for line in f]
A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.
You could simply use a background-blend-mode
.foo {
background-image: url(images/image1.png), url(images/image2.png);
background-color: violet;
background-blend-mode: screen multiply;
}
What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.
multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.
If by "array" you actually mean a Python list, you can use
a = [0] * 10
or
a = [None] * 10
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
isNull()/isNotNull() will return the respective rows which have dt_mvmt as Null or !Null.
method_1 = df.filter(df['dt_mvmt'].isNotNull()).count()
method_2 = df.filter(df.dt_mvmt.isNotNull()).count()
Both will return the same result
You could use the complete.cases
function and put it into a function thusly:
DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
completeFun <- function(data, desiredCols) {
completeVec <- complete.cases(data[, desiredCols])
return(data[completeVec, ])
}
completeFun(DF, "y")
# x y z
# 1 1 0 NA
# 2 2 10 33
completeFun(DF, c("y", "z"))
# x y z
# 2 2 10 33
EDIT: Only return rows with no NA
s
If you want to eliminate all rows with at least one NA
in any column, just use the complete.cases
function straight up:
DF[complete.cases(DF), ]
# x y z
# 2 2 10 33
Or if completeFun
is already ingrained in your workflow ;)
completeFun(DF, names(DF))
This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.
In curl "url" | grep -qs foo
, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.
A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.
E.g.
curl "url" | tac | tac | grep -qs foo
tac
is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.
You might have tried using Microsoft's Excel XML in zip container (.xlsx and .xslm) for version control and found the vba was stored in vbaProject.bin (which is useless for version control).
The solution is simple.
When you repeat this with the next version of the spreadsheet you'll have to make sure you make the folder's files exactly match those in the zip container (and don't leave any deleted files behind).
Sometimes dict()
is a good choice:
a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))
mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],
[random.randint(0,100) for x in range(0,7)]))
As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)
Extending String prototype:
String.prototype.b64encode = function() {
return btoa(unescape(encodeURIComponent(this)));
};
String.prototype.b64decode = function() {
return decodeURIComponent(escape(atob(this)));
};
Usage:
var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );
NOTE:
As stated in the comments, using unescape
is not recommended as it may be removed in the future:
Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.
Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
The HTML element defines bold text, without any extra importance.
<b>This text is bold</b>
The HTML element defines strong text, with added semantic "strong" importance.
<strong>This text is strong</strong>
Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
As a simple one line expression recommend this,
^([a-zA-z0-9/\\''(),-\s]{2,255})$
first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option
innoDB will allow you to view the "relation view" which will help you make the foreign key
For Angular 7, I followed these steps to directly import json data:
In tsconfig.app.json:
add "resolveJsonModule": true
in "compilerOptions"
In a service or component:
import * as exampleData from '../example.json';
And then
private example = exampleData;
sysname
is used by sp_send_dbmail
, a stored procedure that "Sends an e-mail message to the specified recipients" and located in the msdb database.
According to Microsoft,
[ @profile_name = ] 'profile_name'
Is the name of the profile to send the message from. The profile_name is of type sysname, with a default of NULL. The profile_name must be the name of an existing Database Mail profile. When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user. If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database. If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.
If you want to install a bunch of dependencies from, say a requirements.txt, you would do:
mkdir dependencies
pip download -r requirements.txt -d "./dependencies"
tar cvfz dependencies.tar.gz dependencies
And, once you transfer the dependencies.tar.gz to the machine which does not have internet you would do:
tar zxvf dependencies.tar.gz
cd dependencies
pip install * -f ./ --no-index
Here is my example:
.box{_x000D_
_x000D_
width: 400px; _x000D_
height: 80px; _x000D_
background-color: #C9C; _x000D_
text-align: center; _x000D_
font: 20px normal Arial, Helvetica, sans-serif; _x000D_
color: #fff; _x000D_
padding: 100px 0 0 0;_x000D_
-webkit-box-shadow: 0 8px 6px -6px black;_x000D_
-moz-box-shadow: 0 8px 6px -6px black;_x000D_
box-shadow: 0 8px 6px -6px black;_x000D_
}
_x000D_
<div class="box">_x000D_
</div>
_x000D_
Another alternative is to change the overflow:
body {
overflow: hidden;
}
in your iframe's HTML.
// Here is the code for unicode strings!
int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
wchar_t *posstr=wcsstr(txt1,txt2);
if(posstr!=NULL)
{
return (posstr-txt1);
}else
{
return -1;
}
}
// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
wchar_t *tmp;
wchar_t *nextStr;
int pos;
tmp=wcsdup(buff);
pos=mystrstr(tmp,txt1);
if(pos!=-1)
{
buff[0]=0;
wcsncpy(buff,tmp,pos);
buff[pos]=0;
wcscat(buff,txt2);
nextStr=tmp+pos+wcslen(txt1);
while(wcslen(nextStr)!=0)
{
pos=mystrstr(nextStr,txt1);
if(pos==-1)
{
wcscat(buff,nextStr);
break;
}
wcsncat(buff,nextStr,pos);
wcscat(buff,txt2);
nextStr=nextStr+pos+wcslen(txt1);
}
}
free(tmp);
}
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
We can use the formula method of aggregate
. The variables on the 'rhs' of ~
are the grouping variables while the .
represents all other variables in the 'df1' (from the example, we assume that we need the mean
for all the columns except the grouping), specify the dataset and the function (mean
).
aggregate(.~id1+id2, df1, mean)
Or we can use summarise_each
from dplyr
after grouping (group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
Or using summarise
with across
(dplyr
devel version - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
Or another option is data.table
. We convert the 'data.frame' to 'data.table' (setDT(df1)
, grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD
) and get the mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings
. If the file doesn't exist, create it and put on something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>6666</port>
<username></username>
<password></password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
After editing the file, it's just a matter of clicking on Update Settings
button and it's done. I've just done it and it worked :)
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
I came accross the same problem and solved it by checking my #includes. If you use QKeyEvent you have to make sure that you also include it.
I had a class like this and my error appeared when working with "event"in the .cpp file.
myfile.h
#include <QKeyEvent> // adding this import solved the problem.
class MyClass : public QWidget
{
Q_OBJECT
public:
MyClass(QWidget* parent = 0);
virtual ~QmitkHelpOverlay();
protected:
virtual void keyPressEvent(QKeyEvent* event);
};
A good idea is to set all of the "" (blank cells) to NA before any further analysis.
If you are reading your input from a file, it is a good choice to cast all "" to NAs:
foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited
If you have already your table loaded, you can act as follows:
foo[foo==""] <- NA
Then to keep only rows with no NA you may just use na.omit()
:
foo <- na.omit(foo)
Or to keep columns with no NA:
foo <- foo[, colSums(is.na(foo)) == 0]
Try this:
"0x" + BitConverter.ToString(arraytoinsert).Replace("-", "")
Although you should really be using a parameterised query rather than string concatenation of course...
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
My fix for this problem was:
Xcode > Preferences. In Accounts click on your Apple ID. Click View Details, click on your projects Provisioning Profile (I think this helps) and click the refresh button bottom left.
I just wanted to add that "Include" is part of eager loading. It is described in Entity Framework 6 tutorial by Microsoft. Here is the link: https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
Excerpt from the linked page:
Here are several ways that the Entity Framework can load related data into the navigation properties of an entity:
Lazy loading. When the entity is first read, related data isn't retrieved. However, the first time you attempt to access a navigation property, the data required for that navigation property is automatically retrieved. This results in multiple queries sent to the database — one for the entity itself and one each time that related data for the entity must be retrieved. The DbContext class enables lazy loading by default.
Eager loading. When the entity is read, related data is retrieved along with it. This typically results in a single join query that retrieves all of the data that's needed. You specify eager loading by using the
Include
method.Explicit loading. This is similar to lazy loading, except that you explicitly retrieve the related data in code; it doesn't happen automatically when you access a navigation property. You load related data manually by getting the object state manager entry for an entity and calling the Collection.Load method for collections or the Reference.Load method for properties that hold a single entity. (In the following example, if you wanted to load the Administrator navigation property, you'd replace
Collection(x => x.Courses)
withReference(x => x.Administrator)
.) Typically you'd use explicit loading only when you've turned lazy loading off.Because they don't immediately retrieve the property values, lazy loading and explicit loading are also both known as deferred loading.
The full command would be something like below, notice the quotes
icacls "c:\inetpub\wwwroot\tmp" /grant "IIS AppPool\DefaultAppPool:F"
Why does it have to be encoded? A request looks like this:
GET /url HTTP/1.1
(Ignoring headers)
There are 3 fields separated by a white space. If you put a space in your url:
GET /url end_url HTTP/1.1
You know have 4 fields, the HTTP server will tell you it is an invalid request.
GET /url%20end_url HTTP/1.1
3 fields => valid
Note: in the query string (after ?), a space is usually encoded as a +
GET /url?var=foo+bar HTTP/1.1
rather than
GET /url?var=foo%20bar HTTP/1.1
Here is a slight improvement on the this answer above taking care of both .xlsx and .xls files in the same routine, in case it helps someone!
I also add a line to choose to save with the active sheet name instead of the workbook, which is most practical for me often:
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, InStrRev(CurrentWB.Name, ".") - 1) & ".csv"
'Optionally, comment previous line and uncomment next one to save as the current sheet name
'MyFileName = CurrentWB.Path & "\" & CurrentWB.ActiveSheet.Name & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
See the relevel()
function. Here is an example:
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
head(DF)
str(DF)
m1 <- lm(y ~ x + b, data = DF)
summary(m1)
Now alter the factor b
in DF
by use of the relevel()
function:
DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
The models have estimated different reference levels.
> coef(m1)
(Intercept) x b2 b3 b4 b5
3.2903239 1.4358520 0.6296896 0.3698343 1.0357633 0.4666219
> coef(m2)
(Intercept) x b1 b2 b4 b5
3.66015826 1.43585196 -0.36983433 0.25985529 0.66592898 0.09678759
You can format the datetime to the Y-M-D portion:
DATE_FORMAT(datetime, '%Y-%m-%d')
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
Better yet:
for i in xa*; do
sed -i 's/asd/dfg/g' $i
done
because nobody knows how many files are there, and it's easy to break command line limits.
Here's what happens when there are too many files:
# grep -c aaa *
-bash: /bin/grep: Argument list too long
# for i in *; do grep -c aaa $i; done
0
... (output skipped)
#
If using Vagrant try reloading your box. This solved my issue.
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
That's as easy as
IsNull(FieldName, 0)
Or more completely:
SELECT iar.Description,
ISNULL(iai.Quantity,0) as Quantity,
ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.
Example:
<div data-foo="bar"></div>
If you grabbed the value of the attribute using .data('foo')
, it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah')
and then later use .data('foo')
to grab the value, it would return "bar" even though the DOM says data-foo="blah"
. If you use .data()
to set the value, it'll change the value in the jQuery object but not in the DOM.
Basically, .data()
is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr()
is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data()
and .attr()
. Otherwise, stick with one or the other.
In my experience, doing this on the HTML template proved difficult so I decided to use an event to call a function on TS and then check the condition. If true make condition equals to true and then use that variable on the ngIf on HTML
emptyClause(array:any) {
if (array.length === 0) {
// array empty or does not exist
this.emptyMessage=false;
}else{
this.emptyMessage=true;
}
}
HTML
<div class="row">
<form>
<div class="col-md-1 col-sm-1 col-xs-1"></div>
<div class="col-md-10 col-sm-10 col-xs-10">
<div [hidden]="emptyMessage" class="alert alert-danger">
No Clauses Have Been Identified For the Search Criteria
</div>
</div>
<div class="col-md-1 col-sm-1 col-xs-1"></div>
</form>
It seems the two of them are conceptually different.
Direct Casting
Types don't have to be strictly related. It comes in all types of flavors.
It feels like the object is going to be converted into something else.
AS operator
Types have a direct relationship. As in:
It feels like the you are going to handle the object in a different way.
Samples and IL
class TypeA
{
public int value;
}
class TypeB
{
public int number;
public static explicit operator TypeB(TypeA v)
{
return new TypeB() { number = v.value };
}
}
class TypeC : TypeB { }
interface IFoo { }
class TypeD : TypeA, IFoo { }
void Run()
{
TypeA customTypeA = new TypeD() { value = 10 };
long longValue = long.MaxValue;
int intValue = int.MaxValue;
// Casting
TypeB typeB = (TypeB)customTypeA; // custom explicit casting -- IL: call class ConsoleApp1.Program/TypeB ConsoleApp1.Program/TypeB::op_Explicit(class ConsoleApp1.Program/TypeA)
IFoo foo = (IFoo)customTypeA; // is-a reference -- IL: castclass ConsoleApp1.Program/IFoo
int loseValue = (int)longValue; // explicit -- IL: conv.i4
long dontLose = intValue; // implict -- IL: conv.i8
// AS
int? wraps = intValue as int?; // nullable wrapper -- IL: call instance void valuetype [System.Runtime]System.Nullable`1<int32>::.ctor(!0)
object o1 = intValue as object; // box -- IL: box [System.Runtime]System.Int32
TypeD d1 = customTypeA as TypeD; // reference conversion -- IL: isinst ConsoleApp1.Program/TypeD
IFoo f1 = customTypeA as IFoo; // reference conversion -- IL: isinst ConsoleApp1.Program/IFoo
//TypeC d = customTypeA as TypeC; // wouldn't compile
}
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
if it is just a format issue use ToShortDateString()
From iOS 7 there is an API and you can get (and set) the tint color with:
self.view.tintColor
Or if you need the CGColor:
self.view.tintColor.CGColor
The answer, from this page in CSS:
pre {
white-space: pre-wrap; /* Since CSS 2.1 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
You can use a lookahead:
/(?=\S)[^\\]/
Update
The scipy.stats.mode
function has been significantly optimized since this post, and would be the recommended method
Old answer
This is a tricky problem, since there is not much out there to calculate mode along an axis. The solution is straight forward for 1-D arrays, where numpy.bincount
is handy, along with numpy.unique
with the return_counts
arg as True
. The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values. As a solution, I've developed this function, and use it heavily:
import numpy
def mode(ndarray, axis=0):
# Check inputs
ndarray = numpy.asarray(ndarray)
ndim = ndarray.ndim
if ndarray.size == 1:
return (ndarray[0], 1)
elif ndarray.size == 0:
raise Exception('Cannot compute mode on empty array')
try:
axis = range(ndarray.ndim)[axis]
except:
raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))
# If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
if all([ndim == 1,
int(numpy.__version__.split('.')[0]) >= 1,
int(numpy.__version__.split('.')[1]) >= 9]):
modals, counts = numpy.unique(ndarray, return_counts=True)
index = numpy.argmax(counts)
return modals[index], counts[index]
# Sort array
sort = numpy.sort(ndarray, axis=axis)
# Create array to transpose along the axis and get padding shape
transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
shape = list(sort.shape)
shape[axis] = 1
# Create a boolean array along strides of unique values
strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
numpy.diff(sort, axis=axis) == 0,
numpy.zeros(shape=shape, dtype='bool')],
axis=axis).transpose(transpose).ravel()
# Count the stride lengths
counts = numpy.cumsum(strides)
counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
counts[strides] = 0
# Get shape of padded counts and slice to return to the original shape
shape = numpy.array(sort.shape)
shape[axis] += 1
shape = shape[transpose]
slices = [slice(None)] * ndim
slices[axis] = slice(1, None)
# Reshape and compute final counts
counts = counts.reshape(shape).transpose(transpose)[slices] + 1
# Find maximum counts and return modals/counts
slices = [slice(None, i) for i in sort.shape]
del slices[axis]
index = numpy.ogrid[slices]
index.insert(axis, numpy.argmax(counts, axis=axis))
return sort[index], counts[index]
Result:
In [2]: a = numpy.array([[1, 3, 4, 2, 2, 7],
[5, 2, 2, 1, 4, 1],
[3, 3, 2, 2, 1, 1]])
In [3]: mode(a)
Out[3]: (array([1, 3, 2, 2, 1, 1]), array([1, 2, 2, 2, 1, 2]))
Some benchmarks:
In [4]: import scipy.stats
In [5]: a = numpy.random.randint(1,10,(1000,1000))
In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop
In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop
In [8]: a = numpy.random.randint(1,500,(1000,1000))
In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop
In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop
In [11]: a = numpy.random.random((200,200))
In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop
In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop
EDIT: Provided more of a background and modified the approach to be more memory-efficient
No need to create overload methods, just use one single method with params as shown below
// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);
The Eclipse (software) page on Wikipedia summarizes it pretty well:
Releases
Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.
So far, each Simultaneous Release has occurred at the end of June.
Release Main Release Platform version Projects Photon 27 June 2018 4.8 Oxygen 28 June 2017 4.7 Neon 22 June 2016 4.6 Mars 24 June 2015 4.5 Mars Projects Luna 25 June 2014 4.4 Luna Projects Kepler 26 June 2013 4.3 Kepler Projects Juno 27 June 2012 4.2 Juno Projects Indigo 22 June 2011 3.7 Indigo projects Helios 23 June 2010 3.6 Helios projects Galileo 24 June 2009 3.5 Galileo projects Ganymede 25 June 2008 3.4 Ganymede projects Europa 29 June 2007 3.3 Europa projects Callisto 30 June 2006 3.2 Callisto projects Eclipse 3.1 28 June 2005 3.1 Eclipse 3.0 28 June 2004 3.0
To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").
On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).
To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).
Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').
^((?!foo).)*$
This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.
$.active
returns the number of active Ajax requests.
More info here
You can use Magical Take Photo library.
1. try with compile in gradle
compile 'com.frosquivel:magicaltakephoto:1.0'
2. You need this permission in your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
3. instance the class like this
// "this" is the current activity param
MagicalTakePhoto magicalTakePhoto = new MagicalTakePhoto(this,ANY_INTEGER_0_TO_4000_FOR_QUALITY);
4. if you need to take picture use the method
magicalTakePhoto.takePhoto("my_photo_name");
5. if you need to select picture in device, try with the method:
magicalTakePhoto.selectedPicture("my_header_name");
6. You need to override the method onActivityResult of the activity or fragment like this:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
magicalTakePhoto.resultPhoto(requestCode, resultCode, data);
// example to get photo
// imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}
Note: Only with this Library you can take and select picture in the device, this use a min API 15.
I solved it downgrading in gradle from
compile 'com.android.support:design:23.1.0'
to
compile 'com.android.support:design:23.0.1'
It seems like I always get problems when I update any component of Android Studio. Getting tired of it.
for i in ...:
for j in ...:
for k in ...:
if something:
# continue loop i
In a general case, when you have multiple levels of looping and break
does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following
def inner():
for j in ...:
for k in ...:
if something:
return
for i in ...:
inner()
The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).
Or you can define inner
as a nested function and let it just capture what it needs (may be slower?)
for i in ...:
def inner():
for j in ...:
for k in ...:
if something:
return
inner()
Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.
The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.
Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.
class ContinueI(Exception):
pass
continue_i = ContinueI()
for i in ...:
try:
for j in ...:
for k in ...:
if something:
raise continue_i
except ContinueI:
continue
Create a special exception class for this, so that you don't risk accidentally silencing some other exception.
I am sure there are still other solutions.
I usually use this form:
{{#if FriendStatus.IsFriend}}
...
{{else}} {{#if FriendStatus.FriendRequested}}
...
{{else}}
...
{{/if}}{{/if}}
Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page
<meta http-equiv="refresh" content="300">
Using Script:
setInterval(function() {
window.location.reload();
}, 300000);
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
You could inititialize it with a size of 0, but you will have to reinitialize it, when you know what the size is, as you cannot append to the array.
string[] a = new string[0];