SoftReference
is designed for caches. When it is found that a WeakReference
references an otherwise unreachable object, then it will get cleared immediately. SoftReference
may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx
). SoftReference
s will be cleared before OutOfMemoryError
is thrown, unless otherwise reachable.
As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished
, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog
in your operation's dealloc
method and confirm that's getting called.
You said:
I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit
The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self
, or even just references an instance variable of self
, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation
subclass is released.
For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.
If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation
is getting deallocated). A common example is the use of a repeating NSTimer
. Or some custom delegate
or other object that is erroneously maintaining a strong
reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:
Or in Xcode 5:
To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.
Click the Clone or download button and choose your method. I placed these into a dev/py/libs
directory in my user home directory. It does not matter where they are saved, because they will not be installed there.
You will need to run the following inside the setup-tools directory.
python bootstrap.py
python setup.py install
Now you can navigate to the more-itertools direcotry and install it as normal.
cd ...
) into the directory containing setup.py
python setup.py install
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.
~function () {
function Smooth () {
this.$container = document.querySelector('.levit-container');
this.$placeholder = document.createElement('div');
}
Smooth.prototype.init = function () {
var instance = this;
setContainer.call(instance);
setPlaceholder.call(instance);
bindEvents.call(instance);
}
function bindEvents () {
window.addEventListener('scroll', handleScroll.bind(this), false);
}
function setContainer () {
var style = this.$container.style;
style.position = 'fixed';
style.width = '100%';
style.top = '0';
style.left = '0';
style.transition = '0.5s ease-out';
}
function setPlaceholder () {
var instance = this,
$container = instance.$container,
$placeholder = instance.$placeholder;
$placeholder.setAttribute('class', 'levit-placeholder');
$placeholder.style.height = $container.offsetHeight + 'px';
document.body.insertBefore($placeholder, $container);
}
function handleScroll () {
this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
}
var smooth = new Smooth();
smooth.init();
}();
There is nothing particularly tricky about the example you posted.
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
Think of it this way:
var x = (1 < 2) ? true : false;
Could also be written as:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
x = (1 < 2); // x will be set to "true"
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
Make sure you have the list of dict items. If you get UnicodeError
may be the value inside the dict contains unicode format. That issue can be solved in your views.py
.
If the dict is unicode
object, you have to encode into utf-8
.
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
You can use now()
as well in your query, i.e. :
insert into table (time) values(now());
It will use the current timestamp.
Here's a little app to get you started...
import difflib as dl
a = file('file').read()
b = file('file1').read()
sim = dl.get_close_matches
s = 0
wa = a.split()
wb = b.split()
for i in wa:
if sim(i, wb):
s += 1
n = float(s) / float(len(wa))
print '%d%% similarity' % int(n * 100)
You can use Cmd command to run Batch file.
Here is my way =>
cmd /c ""Full_Path_Of_Batch_Here.cmd" "
More information => cmd /?
I think the best way is to store them in some yml file and then load that file using this command in intializer file
APP_CONFIG = YAML.load_file("#{Rails.root}/config/CONFIG.yml")[Rails.env].to_hash
you can easily access environment related config variables.
Your Yml file key value structure:
development:
app_key: 'abc'
app_secret: 'abc'
production:
app_key: 'xyz'
app_secret: 'ghq'
Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);
c1
is mutable (i.e. neither unmodifiable nor immutable).
c2
is unmodifiable: it can't be changed itself, but if later on I change c1
then that change will be visible in c2
.
This is because c2
is simply a wrapper around c1
and not really an independent copy. Guava provides the ImmutableList
interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).
Regarding your second question:
The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.
Wikipedia never lets down:
I created a website with ASP.Net WebForms where you can see the result of using all forms mentioned in previous responses from a site in Azure.
http://wfserverpaths.azurewebsites.net/
Summary:
Server.MapPath("/") => D:\home\site\wwwroot\
Server.MapPath("~") => D:\home\site\wwwroot\
HttpRuntime.AppDomainAppPath => D:\home\site\wwwroot\
HttpRuntime.AppDomainAppVirtualPath => /
AppDomain.CurrentDomain.BaseDirectory => D:\home\site\wwwroot\
HostingEnvironment.MapPath("/") => D:\home\site\wwwroot\
HostingEnvironment.MapPath("~") => D:\home\site\wwwroot\
To stop the pipeline of which ForEach-Object
is part just use the statement continue
inside the script block under ForEach-Object
. continue
behaves differently when you use it in foreach(...) {...}
and in ForEach-Object {...}
and this is why it's possible. If you want to carry on producing objects in the pipeline discarding some of the original objects, then the best way to do it is to filter out using Where-Object
.
For today (year 2017) we have that awesome npm module: https://github.com/felixrieseberg/windows-build-tools which usually solves lots of troubles with building of native things for windows.
Try to fix the issue with:
Remove node_modules
npm install --global windows-build-tools
npm install
using System.Windows.Interop; ...
private BitmapImage Bitmap2BitmapImage(Bitmap bitmap)
{
BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return (BitmapImage)i;
}
just tested JailCoder www.jailcoder.com and i'm able to run and debug on jailbroken devices. You just need a fresh untouched install of xCode, if not, just uninstall and install xCode again and run JailCoder
First instantiate a firefox driver
WebDriver driver = new FirefoxDriver();
then maximize it
driver.manage().window().maximize();
I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException
.
I have the code which is pretty much the same as OP's code:
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34);
System.out.println(k);
}
and the corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object);
Code:
0: aload_0
1: areturn
2: astore_1
3: aconst_null
4: areturn
Exception table:
from to target type
0 1 2 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #3 // double 345435.34d
3: invokestatic #5 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: invokestatic #6 // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
9: checkcast #7 // class java/lang/String
12: astore_1
13: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
16: aload_1
17: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
20: return
Notice that checkcast
byte code instruction happens in the main method not the convertInstanceOfObject
and convertInstanceOfObject
method does not have any instruction that can throw ClassCastException
. Because the main method does not catch the ClassCastException
hence when you execute the main method you will get a ClassCastException
and not the expectation of printing null
.
Now I modify the code to the accepted answer:
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34, String.class);
System.out.println(k);
}
The corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
Code:
0: aload_1
1: aload_0
2: invokevirtual #2 // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
5: areturn
6: astore_2
7: aconst_null
8: areturn
Exception table:
from to target type
0 5 6 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #4 // double 345435.34d
3: invokestatic #6 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: ldc #7 // class java/lang/String
8: invokestatic #8 // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
11: checkcast #7 // class java/lang/String
14: astore_1
15: getstatic #9 // Field java/lang/System.out:Ljava/io/PrintStream;
18: aload_1
19: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
Notice that there is an invokevirtual
instruction in the convertInstanceOfObject
method that calls Class.cast()
method which throws ClassCastException
which will be catch by the catch(ClassCastException e)
bock and return null
; hence, "null" is printed to console without any exception.
I do it this way:
The html:
<head>
<style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>
The xCss.php:
<? // place here your vars
$fntBtn = 'bold 14px Arial'
$colBorder = '#556677' ;
$colBG0 = '#dddddd' ;
$colBG1 = '#44dddd' ;
$colBtn = '#aadddd' ;
// here goes your css after the php-close tag:
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }
sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.
# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make
Note: Makefile requires curl binary to download sqlite libraries/deps.
with this method you can get specific range of string.you need to pass start index and after that total number of characters you want.
extension String{
func substring(fromIndex : Int,count : Int) -> String{
let startIndex = self.index(self.startIndex, offsetBy: fromIndex)
let endIndex = self.index(self.startIndex, offsetBy: fromIndex + count)
let range = startIndex..<endIndex
return String(self[range])
}
}
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
There is no "unset" state for std::string
, it is always set to something.
Ctrl + MouseWheel on active editor.
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
if (chapeau) {
You forgot the ending brace to this if
statement, so the subsequent else if
is considered a syntax error. You need to add the brace when the if
statement body is complete:
if (chapeau) {
cout << "le Professeur Violet";
}
else if (moustaches) {
cout << "le Colonel Moutarde";
}
// ...
Check the setting in your user config /home/username/.netbeans/version/etc/netbeans.conf
I had the problem where I was specifying the location globally, but my user setting was overriding the global setting.
CentOS 7/Netbeans 8.1
Typically speaking, you're going to have a hard time getting an empty string here, considering %s
ignores white space (spaces, tabs, newlines)... but regardless, scanf()
actually returns the number of successful matches...
From the man page:
the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
so if somehow they managed to get by with an empty string (ctrl+z
for example) you can just check the return result.
int count = 0;
do {
...
count = scanf("%62s", url); // You should check return values and limit the
// input length
...
} while (count <= 0)
Note you have to check less than because in the example I gave, you'd get back -1
, again detailed in the man page:
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.
Thanks Jason Rogers's answer first.
In Android && cpp should be this:
const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
Can fix this errors:
1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'
3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'
4.add "env->DeleteLocalRef(nativeString);" at end.
The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1
and 1st Jan 1900 00:00
equals 1
. So 11th June 2009 17:30
is about 39975.72917
.
If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.
So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss
, then it should be possible to achieve what you want.
Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).
String text = "In early March, the city of Topeka, Kansas," + "<br>" +
"temporarily changed its name to Google..." + "<br>" + "<br>" +
"...in an attempt to capture a spot" + "<br>" +
"in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
"source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");
The LogRewrite directive as mentioned by Ben is not available anymore in Apache 2.4. You need to use the LogLevel directive instead. E.g.
LogLevel alert rewrite:trace6
See http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging
Constant time solution, runs in O(8).
Store the state of the board as a binary number. The smallest bit (2^0) is the top left row of the board. Then it goes rightwards, then downwards.
I.E.
+-----------------+ | 2^0 | 2^1 | 2^2 | |-----------------| | 2^3 | 2^4 | 2^5 | |-----------------| | 2^6 | 2^7 | 2^8 | +-----------------+
Each player has their own binary number to represent the state (because tic-tac-toe) has 3 states (X, O & blank) so a single binary number won't work to represent the state of the board for multiple players.
For example, a board like:
+-----------+ | X | O | X | |-----------| | O | X | | |-----------| | | O | | +-----------+ 0 1 2 3 4 5 6 7 8 X: 1 0 1 0 1 0 0 0 0 O: 0 1 0 1 0 0 0 1 0
Notice that the bits for player X are disjoint from the bits for player O, this is obvious because X can't put a piece where O has a piece and vice versa.
To check whether a player has won, we need to compare all the positions covered by that player to a position we know is a win-position. In this case, the easiest way to do that would be by AND-gating the player-position and the win-position and seeing if the two are equal.
boolean isWinner(short X) {
for (int i = 0; i < 8; i++)
if ((X & winCombinations[i]) == winCombinations[i])
return true;
return false;
}
eg.
X: 111001010 W: 111000000 // win position, all same across first row. ------------ &: 111000000
Note: X & W = W
, so X is in a win state.
This is a constant time solution, it depends only on the number of win-positions, because applying AND-gate is a constant time operation and the number of win-positions is finite.
It also simplifies the task of enumerating all valid board states, their just all the numbers representable by 9 bits. But of course you need an extra condition to guarantee a number is a valid board state (eg. 0b111111111
is a valid 9-bit number, but it isn't a valid board state because X has just taken all the turns).
The number of possible win positions can be generated on the fly, but here they are anyways.
short[] winCombinations = new short[] {
// each row
0b000000111,
0b000111000,
0b111000000,
// each column
0b100100100,
0b010010010,
0b001001001,
// each diagonal
0b100010001,
0b001010100
};
To enumerate all board positions, you can run the following loop. Although I'll leave determining whether a number is a valid board state upto someone else.
NOTE: (2**9 - 1) = (2**8) + (2**7) + (2**6) + ... (2**1) + (2**0)
for (short X = 0; X < (Math.pow(2,9) - 1); X++)
System.out.println(isWinner(X));
Use the .val() method.
Also I think you meant to use $("#txtEmail")
as $("txtEmail")
returns elements of type <txtEmail>
which you probably don't have.
See here at the jQuery documentation.
Also jQuery val() method.
With docker compose there's a simple alternative (no need to create a Dockerfile). Just create a init-database.sh:
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER docker;
CREATE DATABASE my_project_development;
GRANT ALL PRIVILEGES ON DATABASE my_project_development TO docker;
CREATE DATABASE my_project_test;
GRANT ALL PRIVILEGES ON DATABASE my_project_test TO docker;
EOSQL
And reference it in the volumes section:
version: '3.4'
services:
postgres:
image: postgres
restart: unless-stopped
volumes:
- postgres:/var/lib/postgresql/data
- ./init-database.sh:/docker-entrypoint-initdb.d/init-database.sh
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
ports:
- 5432:5432
volumes:
postgres:
$protocal = 'http';
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || $_SERVER['HTTPS'] == 'on') {$protocal = 'https';}
echo $protocal;
I had the same issue and i had it formatted into JSON as a String instead. Might be a bit of a hack but it's easy to implement.
private BigDecimal myValue = new BigDecimal("25.50");
...
public String getMyValue() {
return myValue.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don't waste your time trying to handle this with pure JavaScript. I waste my time trying to make it dd/mm/yyyy
. There's no complete solutions that fits with all browsers. So I recommend to use jQuery
datepicker / momentJS or tell your client to work with the default date format instead
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
Using Sieve of Eratosthenes, source on Rosettacode
fastest solution: https://repl.it/@caub/getPrimes-bench
function getPrimes(limit) {_x000D_
if (limit < 2) return [];_x000D_
var sqrtlmt = limit**.5 - 2;_x000D_
var nums = Array.from({length: limit-1}, (_,i)=>i+2);_x000D_
for (var i = 0; i <= sqrtlmt; i++) {_x000D_
var p = nums[i]_x000D_
if (p) {_x000D_
for (var j = p * p - 2; j < nums.length; j += p)_x000D_
nums[j] = 0;_x000D_
}_x000D_
}_x000D_
return nums.filter(x => x); // return non 0 values_x000D_
}_x000D_
document.body.innerHTML = `<pre style="white-space:pre-wrap">${getPrimes(100).join(', ')}</pre>`;_x000D_
_x000D_
// for fun, this fantasist regexp way (very inefficient):_x000D_
// Array.from({length:101}, (_,i)=>i).filter(n => n>1&&!/^(oo+)\1+$/.test('o'.repeat(n))
_x000D_
You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:
import { Field } from "sparkson";
class Response {
constructor(
@Field("name") public name: string,
@Field("error") public error: boolean
) {}
}
The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.
Worked for me. Task Manager -> Name of project -> End task. (i had 3 same processes with my project name);
VS 2013; Win 8;
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 :)
You should trigger the animation to revert once it's completed w/ javascript.
$(".item").live("animationend webkitAnimationEnd", function(){
$(this).removeClass('animate');
});
I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
It's safe to increase the size of your varchar column. You won't corrupt your data.
If it helps your peace of mind, keep in mind, you can always run a database backup before altering your data structures.
By the way, correct syntax is:
ALTER TABLE table_name MODIFY col_name VARCHAR(10000)
Also, if the column previously allowed/did not allow nulls, you should add the appropriate syntax to the end of the alter table statement, after the column type.
There are some changes required to JavaScript code to handle rendering based on user liking or not liking the page mandated by Facebook moving to Auth2.0 authorization.
Change is fairly simple:-
sessions has to be replaced by authResponse and uid by userID
Moreover given the requirement of the code and some issues faced by people(including me) in general with FB.login, use of FB.getLoginStatus is a better alternative. It saves query to FB in case user is logged in and has authenticated your app.
Refer to Response and Sessions Object section for info on how this might save query to FB server. http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
Issues with FB.login and its fixes using FB.getLoginStatus. http://forum.developers.facebook.net/viewtopic.php?id=70634
Here is the code posted above with changes which worked for me.
$(document).ready(function(){
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id =" + page_id + " and uid=" + user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
});
I got same exception while running gradle build for my android project.
Caused by: java.lang.IllegalStateException: Failed to find target with hash string 'android-27'
This issue related to android SDK version enable for your Android Studio. Please find the solution of this problem from attached screen.
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
to get the items checked you can use CheckedItems
or GetItemsChecked
. I tried below code in .NET 4.5
Iterate through the CheckedItems
collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2
.
//Determine if there are any items checked.
if(chBoxListTables.CheckedItems.Count != 0)
{
//looped through all checked items and show results.
string s = "";
for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
{
s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
}
MessageBox.Show(s);//show result
}
-OR-
Step through the Items collection and call the GetItemChecked
method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2
.
int i;
string s;
s = "Checked items:\n" ;
for (i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";
}
}
MessageBox.Show (s);
Hope this helps...
basing on this blog post https://8thlight.com/blog/dariusz-pasciak/2016/10/17/docker-compose-wait-for-dependencies.html
I configured my docker-compose.yml
as shown below:
version: "3.1"
services:
rabbitmq:
image: rabbitmq:3.7.2-management-alpine
restart: always
environment:
RABBITMQ_HIPE_COMPILE: 1
RABBITMQ_MANAGEMENT: 1
RABBITMQ_VM_MEMORY_HIGH_WATERMARK: 0.2
RABBITMQ_DEFAULT_USER: "rabbitmq"
RABBITMQ_DEFAULT_PASS: "rabbitmq"
ports:
- "15672:15672"
- "5672:5672"
volumes:
- data:/var/lib/rabbitmq:rw
start_dependencies:
image: alpine:latest
links:
- rabbitmq
command: >
/bin/sh -c "
echo Waiting for rabbitmq service start...;
while ! nc -z rabbitmq 5672;
do
sleep 1;
done;
echo Connected!;
"
volumes:
data: {}
Then I do for run =>:
docker-compose up start_dependencies
rabbitmq
service will start in daemon mode, start_dependencies
will finish the work.
var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );
(ans == null).Dump(); // False
(ans.Count() == 0 ).Dump(); // True
(Dump is from LinqPad)
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object)
to turn it into (a string of) JSON text.
declare your asyncTask in your activity:
private YourAsyncTask mTask;
instantiate it like this:
mTask = new YourAsyncTask().execute();
kill/cancel it like this:
mTask.cancel(true);
I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.
outerLink {
overflow: hidden;
position: relative;
}
outerLink:hover:after {
background: #000;
content: "";
display: block;
height: 100%;
left: 0;
opacity: 0.5;
position: absolute;
top: 0;
width: 100%;
}
Are you ssh'ing to a directory that's inside your work tree? If the root of your ssh mount point doesn't include the .git dir, then zsh won't be able to find git info. Make sure you're mounting something that includes the root of the repo.
As for GIT_DISCOVERY_ACROSS_FILESYSTEM, it doesn't do what you want. Git by default will stop at a filesystem boundary. If you turn that on (and it's just an env var), then git will cross the filesystem boundary and keep looking. However, that's almost never useful, because you'd be implying that you have a .git directory on your local machine that's somehow meant to manage a work tree that's comprised partially of an sshfs mount. That doesn't make much sense.
I'm a little bit late and i will talk about Python3. To understand what id() is and how it (and Python) works, consider next example:
>>> x=1000
>>> y=1000
>>> id(x)==id(y)
False
>>> id(x)
4312240944
>>> id(y)
4312240912
>>> id(1000)
4312241104
>>> x=1000
>>> id(x)
4312241104
>>> y=1000
>>> id(y)
4312241200
You need to think about everything on the right side as objects. Every time you make assignment - you create new object and that means new id. In the middle you can see a "wild" object which is created only for function - id(1000). So, it's lifetime is only for that line of code. If you check the next line - you see that when we create new variable x, it has the same id as that wild object. Pretty much it works like memory address.
As the others say, there is a MessageBox
in the WPF namespace (System.Windows
).
The problem is that it is the same old messagebox with OK, Cancel, etc. Windows Vista and Windows 7 have moved on to use Task Dialogs instead.
Unfortunately there is no easy standard interface for task dialogs. I use an implementation from CodeProject KB.
body, html {
width: 100%;
height: 100%;
}
Worked for me :)
below is used to a add a new remote:
git remote add origin [email protected]:User/UserRepo.git
below is used to change the url of an existing remote repository:
git remote set-url origin [email protected]:User/UserRepo.git
below will push your code to the master branch of the remote repository defined with origin
and -u
let you point your current local branch to the remote master branch:
git push -u origin master
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.
I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.
It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
You just have to use class="row-eq-height"
with your class="row"
to get equal height columns for previous bootstrap versions.
but with bootstrap 4 this comes natively.
check this link --http://getbootstrap.com.vn/examples/equal-height-columns/
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
Note that the MoreLINQ NuGet provides the ForEach
extension method you're looking for (as well as a Pipe
method which executes the delegate and yields its result). See:
Also you can use 'os.popen'. Example:
import os
command = os.popen('ls -al')
print(command.read())
print(command.close())
Output:
total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root 77 ago 13 21:53 test.py
None
The axios library creates a Promise() object. Promise is a built-in object in JavaScript ES6. When this object is instantiated using the new keyword, it takes a function as an argument. This single function in turn takes two arguments, each of which are also functions — resolve and reject.
Promises execute the client side code and, due to cool Javascript asynchronous flow, could eventually resolve one or two things, that resolution (generally considered to be a semantically equivalent to a Promise's success), or that rejection (widely considered to be an erroneous resolution). For instance, we can hold a reference to some Promise object which comprises a function that will eventually return a response object (that would be contained in the Promise object). So one way we could use such a promise is wait for the promise to resolve to some kind of response.
You might raise we don't want to be waiting seconds or so for our API to return a call! We want our UI to be able to do things while waiting for the API response. Failing that we would have a very slow user interface. So how do we handle this problem?
Well a Promise is asynchronous. In a standard implementation of engines responsible for executing Javascript code (such as Node, or the common browser) it will resolve in another process while we don't know in advance what the result of the promise will be. A usual strategy is to then send our functions (i.e. a React setState function for a class) to the promise, resolved depending on some kind of condition (dependent on our choice of library). This will result in our local Javascript objects being updated based on promise resolution. So instead of getters and setters (in traditional OOP) you can think of functions that you might send to your asynchronous methods.
I'll use Fetch in this example so you can try to understand what's going on in the promise and see if you can replicate my ideas within your axios code. Fetch is basically similar to axios without the innate JSON conversion, and has a different flow for resolving promises (which you should refer to the axios documentation to learn).
GetCache.js
const base_endpoint = BaseEndpoint + "cache/";
// Default function is going to take a selection, date, and a callback to execute.
// We're going to call the base endpoint and selection string passed to the original function.
// This will make our endpoint.
export default (selection, date, callback) => {
fetch(base_endpoint + selection + "/" + date)
// If the response is not within a 500 (according to Fetch docs) our promise object
// will _eventually_ resolve to a response.
.then(res => {
// Lets check the status of the response to make sure it's good.
if (res.status >= 400 && res.status < 600) {
throw new Error("Bad response");
}
// Let's also check the headers to make sure that the server "reckons" its serving
//up json
if (!res.headers.get("content-type").includes("application/json")) {
throw new TypeError("Response not JSON");
}
return res.json();
})
// Fulfilling these conditions lets return the data. But how do we get it out of the promise?
.then(data => {
// Using the function we passed to our original function silly! Since we've error
// handled above, we're ready to pass the response data as a callback.
callback(data);
})
// Fetch's promise will throw an error by default if the webserver returns a 500
// response (as notified by the response code in the HTTP header).
.catch(err => console.error(err));
};
Now we've written our GetCache method, lets see what it looks like to update a React component's state as an example...
Some React Component.jsx
// Make sure you import GetCache from GetCache.js!
resolveData() {
const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
const setData = data => {
this.setState({
data: data,
loading: false
// We could set loading to true and display a wee spinner
// while waiting for our response data,
// or rely on the local state of data being null.
});
};
GetCache("mySelelection", date, setData);
}
Ultimately, you don't "return" data as such, I mean you can but it's more idiomatic to change your way of thinking... Now we are sending data to asynchronous methods.
Happy Coding!
$ adb shell
$su
# getenforce
Enforcing
now try
adb shell
su
chmod 777 /path/to/yout_file
exit from shell
open new CMD and try adb pull /path/to/yout_file
It will work fine now.
you'll have security problems because of this any application will be able to access your database.
Yes, you can.
However, it requires SQL CLR with EXTERNAL_ACCESS or UNSAFE permission and specifying a connection string. This is obviously not recommended.
For example, using Eval SQL.NET (a SQL CLR which allow to add C# syntax in SQL)
CREATE FUNCTION [dbo].[fn_modify_table_state]
(
@conn VARCHAR(8000) ,
@sql VARCHAR(8000)
)
RETURNS INT
AS
BEGIN
RETURN SQLNET::New('
using(var connection = new SqlConnection(conn))
{
connection.Open();
using(var command = new SqlCommand(sql, connection))
{
return command.ExecuteNonQuery();
}
}
').ValueString('conn', @conn).ValueString('sql', @sql).EvalReadAccessInt()
END
GO
DECLARE @conn VARCHAR(8000) = 'Data Source=XPS8700;Initial Catalog=SqlServerEval_Debug;Integrated Security=True'
DECLARE @sql VARCHAR(8000) = 'UPDATE [Table_1] SET Value = -1 WHERE Name = ''zzz'''
DECLARE @rowAffecteds INT = dbo.fn_modify_table_state(@conn, @sql)
Documentation: Modify table state within a SQL Function
Disclaimer: I'm the owner of the project Eval SQL.NET
I've found variants of System.IO.Path.Combine(myPath, "..")
to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.
Path.Combine makes sure you never go wrong with slashes.
..
behaves exactly like it does everywhere else in Windows. You can add any number of \..
to a path in cmd or explorer and it will behave exactly as I describe below.
Some basic ..
behavior:
..
will chop that off:Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..")
=> D:\Grandparent\Parent\
..
will move up a level:Path.Combine(@"D:\Grandparent\Parent\", "..")
=> D:\Grandparent\
..\..
follows the same rules, twice in a row:Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..")
=> D:\Grandparent\
Path.Combine(@"D:\Grandparent\Parent\", @"..\..")
=> D:\
Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..")
=> D:\Grandparent\
Path.Combine(@"D:\Grandparent\Parent\", "..", "..")
=> D:\
You can use the listings package. It supports many different languages and there are lots of options for customising the output.
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
Wouldn't strtok()
work for you?
You can use Apache commons-lang
StringUtils.isEmpty(String str)
- Checks if a String is empty ("") or null.
or
StringUtils.isBlank(String str)
- Checks if a String is whitespace, empty ("") or null.
the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API
You can install mod_security
and put in /etc/modsecurity/modsecurity.conf
:
SecRuleEngine On
SecAuditEngine On
SecAuditLog /var/log/apache2/modsec_audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIJDFHZ
A better approach is:
int x = rand.nextInt(max - min + 1) + min;
Your formula generates numbers between min
and min + max
.
Random random = new Random(1234567);
int min = 5;
int max = 20;
while (true) {
int x = (int)(Math.random() * max) + min;
System.out.println(x);
if (x < min || x >= max) { break; }
}
Result:
10
16
13
21 // Oops!!
See it online here: ideone
According to the official documentation on sitemaps.org it needs to be a full URL:
You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:
Sitemap: http://www.example.com/sitemap.xml
Assuming the quotation marks are actually part of the output, couldn't you just use the -o switch to return everything between the quote marks?
COMPANY_NAME="\"ABC Inc\";" | echo $COMPANY_NAME | grep -o "\"*.*\""
......../info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?
For me the issue was a password issue. I run Keychain and deleted Github passwords. I run the pull command after that and it asked me for username and password. After that it worked ok.
Do keep in mind that you don't need a stable sort if you compare all members. The 2.0 solution, as requested, can look like this:
public void SortList() {
MyList.Sort(delegate(MyClass a, MyClass b)
{
int xdiff = a.x.CompareTo(b.x);
if (xdiff != 0) return xdiff;
else return a.y.CompareTo(b.y);
});
}
Do note that this 2.0 solution is still preferable over the popular 3.5 Linq solution, it performs an in-place sort and does not have the O(n) storage requirement of the Linq approach. Unless you prefer the original List object to be untouched of course.
You should return json always, but change its status, or in following example the ResponseCode property:
if(callbackResults.ResponseCode!="200"){
/* Some error, you can add a message too */
} else {
/* All fine, proceed with code */
};
I have written a Python script using GitPython to do delete local branches which don't exist on remote.
import git
import subprocess
from git.exc import GitCommandError
import os
def delete_merged_branches():
current_dir = input("Enter repository directory:")
repo = git.Repo(current_dir)
git_command = git.Git(current_dir)
# fetch the remote with prune, this will delete the remote references in local.
for remote in repo.remotes:
remote.fetch(prune=True)
local_branches = [branch.name for branch in repo.branches]
deleted_branches = []
# deleted_branches are the branches which are deleted on remote but exists on local.
for branch in local_branches:
try:
remote_name = 'origin/'+ branch
repo.git.checkout(remote_name)
except GitCommandError:
# if the remote reference is not present, it means the branch is deleted on remote.
deleted_branches.append(branch)
for branch in deleted_branches:
print("Deleting branch:"+branch)
git_command.execute(["git", "branch", "-D",branch])
# clean up the work flow.
repo.git.checkout('master')
repo.git.pull()
if __name__ == '__main__':
delete_merged_branches()
Hope someone finds it useful, please add comments if I missed anything.
In order to answer you questions;
"?v=1" this is written only beacuse to download a fresh copy of the css and js files instead of using from the cache of the browser.
If you mention this query string parameter at the end of your stylesheet or the js file then it forces the browser to download a new file, Due to which the recent changes in the .css and .js files are made effetive in your browser.
If you dont use this versioning then you may need to clear the cache of refresh the page in order to view the recent changes in those files.
Here is an article that explains this thing How and Why to make versioning of CSS and JS files
It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,
if (window.variableName)
is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.
That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.
if ( variableName && typeof variableName !== 'undefined' )
For using dictionary object in typescript you can use interface as below:
interface Dictionary<T> {
[Key: string]: T;
}
and, use this for your class property type.
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
to use and initialize this class,
getUsers(): Observable<any> {
var searchParams = new SearchParameters();
searchParams.SearchFor['userId'] = '1';
searchParams.SearchFor['userName'] = 'xyz';
return this.http.post(searchParams, 'users/search')
.map(res => {
return res;
})
.catch(this.handleError.bind(this));
}
<application
android:icon="@drawable/app_icon"
android:label="@string/app_name">
<activity
android:name="com.cipl.worldviewfinal.SplashActivity"
android:label="@string/title_activity_splash" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
To change android app's name , go to activity which is launcher activity and change its label like I have done above in my code.
Simply pass the sorted items from the dictionary to the plot()
function. concentration.items()
returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.
You can take advantage of list unpacking (with *
) to pass the sorted data directly to zip, and then again to pass it into plot()
:
import matplotlib.pyplot as plt
concentration = {
0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}
plt.plot(*zip(*sorted(concentration.items())))
plt.show()
sorted()
sorts tuples in the order of the tuple's items so you don't need to specify a key
function because the tuples returned by dict.item()
already begin with the key value.
You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:
Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.
Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.
For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:
NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.
The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md
I stopped using datetime
in my applications after facing many problems and bugs related to time zones. IMHO using timestamp
is better than datetime
in most of the cases.
When you ask what is the time ? and the answer comes as something like '2019-02-05 21:18:30', that is not completed, not defined answer because it lacks another part, in which timezone ? Washington ? Moscow ? Beijing ?
Using datetimes without the timezone means that your application is dealing with only 1 timezone, however timestamps give you the benefits of datetime
plus the flexibility of showing the same exact point of time in different timezones.
Here are some cases that will make you regret using datetime
and wish that you stored your data in timestamps.
For your clients comfort you want to show them the times based on their preferred time zones without making them doing the math and convert the time to their meaningful timezone. all you need is to change the timezone and all your application code will be the same.(Actually you should always define the timezone at the start of the application, or request processing in case of PHP applications)
SET time_zone = '+2:00';
you changed the country you stay in, and continue your work of maintaining the data while seeing it in a different timezone (without changing the actual data).
datetime
= application supports 1 timezone (for both inserting and selecting)
timestamp
= application supports any timezone (for both inserting and selecting)
This answer is only for putting some highlight on the flexibility and ease of timestamps when it comes to time zones , it is not covering any other differences like the column size or range or fraction.
MySQL has a concept of user-defined variables.
They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.
They are prepended with an @
sign, like this: @var
You can initialize this variable with a SET
statement or inside a query:
SET @var = 1
SELECT @var2 := 2
When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:
DELIMITER //
CREATE PROCEDURE prc_test (var INT)
BEGIN
DECLARE var2 INT;
SET var2 = 1;
SELECT var2;
END;
//
DELIMITER ;
These variables are not prepended with any prefixes.
The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to NULL
each time the procedure is called, while the session-specific variable is not:
CREATE PROCEDURE prc_test ()
BEGIN
DECLARE var2 INT DEFAULT 1;
SET var2 = var2 + 1;
SET @var2 = @var2 + 1;
SELECT var2, @var2;
END;
SET @var2 = 1;
CALL prc_test();
var2 @var2
--- ---
2 2
CALL prc_test();
var2 @var2
--- ---
2 3
CALL prc_test();
var2 @var2
--- ---
2 4
As you can see, var2
(procedure variable) is reinitialized each time the procedure is called, while @var2
(session-specific variable) is not.
(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port
or "session variables" such as @@session.sql_mode
; these "session variables" are unrelated to session-specific user-defined variables.)
I know this is an old question that has an answer already, and there are a number of other decent answers. I see some answers that propose that you can solve this problem by looking up the correct insertion index in O(log n) - you can, but you can't insert in that time, because the array needs to be partially copied out to make space.
Bottom line: If you really need O(log n) inserts and deletes into a sorted array, you need a different data structure - not an array. You should use a B-Tree. The performance gains you will get from using a B-Tree for a large data set, will dwarf any of the improvements offered here.
If you must use an array. I offer the following code, based on insertion sort, which works, if and only if the array is already sorted. This is useful for the case when you need to resort after every insert:
function addAndSort(arr, val) {
arr.push(val);
for (i = arr.length - 1; i > 0 && arr[i] < arr[i-1]; i--) {
var tmp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = tmp;
}
return arr;
}
It should operate in O(n), which I think is the best you can do. Would be nicer if js supported multiple assignment. here's an example to play with:
this might be faster:
function addAndSort2(arr, val) {
arr.push(val);
i = arr.length - 1;
item = arr[i];
while (i > 0 && item < arr[i-1]) {
arr[i] = arr[i-1];
i -= 1;
}
arr[i] = item;
return arr;
}
Easiest way to do this is to use paste()
> paste("Today is", date())
[1] "Today is Sat Feb 21 15:25:18 2015"
paste0()
would result in the following:
> paste0("Today is", date())
[1] "Today isSat Feb 21 15:30:46 2015"
Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:
> paste0("Today is ", date())
[1] "Today is Sat Feb 21 15:32:17 2015"
Then combine either function with print()
> print(paste("This is", date()))
[1] "This is Sat Feb 21 15:34:23 2015"
Or
> print(paste0("This is ", date()))
[1] "This is Sat Feb 21 15:34:56 2015"
As other users have stated, you could also use cat()
Nothing above helped me. The fingerprint dialog did not appear. I checked another android device and the dialog appeared and debug was possible. So the problem was on device side not on computer side I made reset "to factory settings" on device and this helped me.
If you want to stream any webpage, you can use the method below.
import java.io.*;
import java.net.*;
public class c {
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
try (var reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
for (String line; (line = reader.readLine()) != null; ) {
result.append(line);
}
}
return result.toString();
}
public static void main(String[] args) throws Exception
{
System.out.println(getHTML(args[0]));
}
}
For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:
Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:
ng new app-name
So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve
This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)
As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:
"scripts": {
"build:watch": "tsc -p src/ -w",
"serve": "lite-server -c=bs-config.json",
"start": "concurrently \"npm run build:watch\" \"npm run serve\""
...
},
"devDependencies": {
"concurrently": "^3.2.0",
"lite-server": "^2.2.2",
In this case, 'npm start' will result in the following commands to be run:
concurrently "npm run build:watch" "npm run serve"
This will concurrently run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
As ugly as it is, here is a workaround that works as long as you aren't passing an array explicitly, but a variable corresponding to an array:
function passarray()
{
eval array_internally=("$(echo '${'$1'[@]}')")
# access array now via array_internally
echo "${array_internally[@]}"
#...
}
array=(0 1 2 3 4 5)
passarray array # echo's (0 1 2 3 4 5) as expected
I'm sure someone can come up with a clearner implementation of the idea, but I've found this to be a better solution than passing an array as "{array[@]"}
and then accessing it internally using array_inside=("$@")
. This becomes complicated when there are other positional/getopts
parameters. In these cases, I've had to first determine and then remove the parameters not associated with the array using some combination of shift
and array element removal.
A purist perspective likely views this approach as a violation of the language, but pragmatically speaking, this approach has saved me a whole lot of grief. On a related topic, I also use eval
to assign an internally constructed array to a variable named according to a parameter target_varname
I pass to the function:
eval $target_varname=$"(${array_inside[@]})"
Hope this helps someone.
My approach: use a div
instead of a pop-up window.
See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/
Or save the code below as test.html and try it locally.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$('.btnChoice').on('click', function(){
$('#divChoices').show()
thefield = $(this).prev()
$('.btnselect').on('click', function(){
theselected = $(this).prev()
thefield.val( theselected.val() )
$('#divChoices').hide()
})
})
$('#divChoices').css({
'border':'2px solid red',
'position':'fixed',
'top':'100',
'left':'200',
'display':'none'
})
});
</script>
</head>
<body>
<div class="divform">
<input type="checkbox" name="kvi1" id="kvi1" value="1">
<label>Field 1: </label>
<input size="10" type="number" id="sku1" name="sku1">
<button id="choice1" class="btnChoice">?</button>
<br>
<input type="checkbox" name="kvi2" id="kvi2" value="2">
<label>Field 2: </label>
<input size="10" type="number" id="sku2" name="sku2">
<button id="choice2" class="btnChoice">?</button>
</div>
<div id="divChoices">
Select something:
<br>
<input size="10" type="number" id="ch1" name="ch1" value="11">
<button id="btnsel1" class="btnselect">Select</button>
<label for="ch1">bla bla bla</label>
<br>
<input size="10" type="number" id="ch2" name="ch2" value="22">
<button id="btnsel2" class="btnselect">Select</button>
<label for="ch2">ble ble ble</label>
</div>
</body>
</html>
clean and simple.
the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :
df = df.query("columnNameA <= @x or columnNameB == @y")
with x and y are declared variables which you can refer to with @
Corrected;
/*
return true if the array is not empty
return false if it is empty
*/
function is_array_empty($arr){
if(is_array($arr)){
foreach($arr as $key => $value){
if(!empty($value) || $value != NULL || $value != ""){
return true;
break;//stop the process we have seen that at least 1 of the array has value so its not empty
}
}
return false;
}
}
These are typical npm paths if you install a package globally:
Windows XP - %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or - %AppData%\roaming\npm\node_modules
You can use unionByName to make this:
df = df_1.unionByName(df_2)
unionByName is available since Spark 2.3.0.
a, b, c, d, e, g, h, i, j = (True,)*9
f = False
I have used this form of switch-case
on rare occasion. Even then I have found another way to do what I wanted. If you find that this is the only way to accomplish what you need, I would recommend @Mark H's solution.
If this is intended to be a sort of factory creation decision process, there are better ways to do it. Otherwise, I really can't see why you want to use the switch on a type.
Here is a little example expanding on Mark's solution. I think it is a great way to work with types:
Dictionary<Type, Action> typeTests;
public ClassCtor()
{
typeTests = new Dictionary<Type, Action> ();
typeTests[typeof(int)] = () => DoIntegerStuff();
typeTests[typeof(string)] = () => DoStringStuff();
typeTests[typeof(bool)] = () => DoBooleanStuff();
}
private void DoBooleanStuff()
{
//do stuff
}
private void DoStringStuff()
{
//do stuff
}
private void DoIntegerStuff()
{
//do stuff
}
public Action CheckTypeAction(Type TypeToTest)
{
if (typeTests.Keys.Contains(TypeToTest))
return typeTests[TypeToTest];
return null; // or some other Action delegate
}
Inview library triggered event and works well with jquery 1.8 and higher! https://github.com/protonet/jquery.inview
$('div').on('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin
DOMDocument is slow to type and phpQuery has bad memory leak issues. I ended up using:
https://github.com/wasinger/htmlpagedom
To select a class:
include 'includes/simple_html_dom.php';
$doc = str_get_html($html);
$href = $doc->find('.lastPage')[0]->href;
I hope this helps someone else as well
For those who fear to mess anything up in your vscode json settings this is pretty easy to follow.
Open "File -> Preferences -> Keyboard Shortcuts"
or "Code -> Preferences -> Keyboard Shortcuts"
for Mac Users
In the search bar type transform
.
By default you will not have anything under Keybinding
. Now double-click on Transform to Lowercase
or Transform to Uppercase
.
Press your desired combination of keys to set your keybinding. In this case if copying off of Sublime i will press ctrl+shift+u
for uppercase or ctrl+shift+l
for lowercase.
Press Enter
on your keyboard to save and exit. Do same for the other option.
Enjoy KEYBINDING
Remember if you want to give Text a backgroundcolor and then also borderRadius in that case also write overflow:'hidden' your text having a background colour will also get the radius otherwise it's impossible to achieve until unless you wrap it with View and give backgroundcolor and radius to it.
<Text style={{ backgroundColor: 'black', color:'white', borderRadius:10, overflow:'hidden'}}>Dummy</Text>
@Override
public void onPause() {
super.onPause();
if(pDialog != null)
pDialog .dismiss();
pDialog = null;
}
refer this.
If you use oh-my-zsh (which every trendy geek should use), after activating the "osx" plugin in .zshrc
, simply enter the tab
command; it will open a new tab and cd
in the directory your were on.
My understanding of margin and padding comes from google's developer tool in the image attached
In Simple words, a margin is the space around an element and padding means the space between an element and the content inside that element. Both these two are used to create gaps but in different ways.
Using Margin to create gap:
In creating gap margin pushes the adjacent elements away
Using Padding to create gap:
Using padding to create gap either grows the element's size or shrinks the content inside
Why is it important to know the difference?
It is important to know the difference so you could know when to use either of them and use them appropriately.
It is also worthy of note that margins and padding come handy when designing a website's layout, as margin specifies whether an element will move up or down, left or right while padding specifies how an element will look and sit inside its container.
On my mac, the following inserts a single 'n' instead of newline:
sed 's/regexp/\n&/g'
This replaces with newline:
sed "s/regexp/\\`echo -e '\n\r'`/g"
That's right, each address needs to be quoted. If you have multiple addresses listed on the command line, the Send-MailMessage likes it if you specify both the human friendly and the email address parts.
As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them
You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery
using the following code. (Thanks @Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
What does res.render do and what does the html file look like?
res.render()
function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.
Answering Edit 2 part.
// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');
// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');
// here you render `orders` template
response.render("orders", {orders: orders_json});
So, the template path is views/
(first part) + orders
(second part) + .ejs
(third part) === views/orders.ejs
Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.
/proc/partitions
will list all the block devices and partitions that the system recognizes. You can then try using file -s <device>
to determine what kind of filesystem is present on the partition, if any.
You can use the html property: http://jsfiddle.net/UBr6c/
My <a href="#" title="This is a<br />test...<br />or not" class="my_tooltip">Tooltip</a> test.
$('.my_tooltip').tooltip({html: true})
I ended up just creating a headerView that contained a button ( i saw Son Nguyen's solution above after the fact, but heres my code.. it looks like a lot but it's pretty simple):
declare a couple bools for you sections
bool customerIsCollapsed = NO;
bool siteIsCollapsed = NO;
...code
now in your tableview delegate methods...
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _tblSearchResults.frame.size.width, 35)];
UILabel *lblSection = [UILabel new];
[lblSection setFrame:CGRectMake(0, 0, 300, 30)];
[lblSection setFont:[UIFont fontWithName:@"Helvetica-Bold" size:17]];
[lblSection setBackgroundColor:[UIColor clearColor]];
lblSection.alpha = 0.5;
if(section == 0)
{
if(!customerIsCollapsed)
[lblSection setText:@"Customers --touch to show--"];
else
[lblSection setText:@"Customers --touch to hide--"];
}
else
{
if(!siteIsCollapsed)
[lblSection setText:@"Sites --touch to show--"];
else
[lblSection setText:@"Sites --touch to hide--"]; }
UIButton *btnCollapse = [UIButton buttonWithType:UIButtonTypeCustom];
[btnCollapse setFrame:CGRectMake(0, 0, _tblSearchResults.frame.size.width, 35)];
[btnCollapse setBackgroundColor:[UIColor clearColor]];
[btnCollapse addTarget:self action:@selector(touchedSection:) forControlEvents:UIControlEventTouchUpInside];
btnCollapse.tag = section;
[headerView addSubview:lblSection];
[headerView addSubview:btnCollapse];
return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if(section == 0)
{
if(customerIsCollapsed)
return 0;
else
return _customerArray.count;
}
else if (section == 1)
{
if(siteIsCollapsed)
return 0;
else
return _siteArray.count;
}
return 0;
}
and finally the function that gets called when you touch one of the section header buttons:
- (IBAction)touchedSection:(id)sender
{
UIButton *btnSection = (UIButton *)sender;
if(btnSection.tag == 0)
{
NSLog(@"Touched Customers header");
if(!customerIsCollapsed)
customerIsCollapsed = YES;
else
customerIsCollapsed = NO;
}
else if(btnSection.tag == 1)
{
NSLog(@"Touched Site header");
if(!siteIsCollapsed)
siteIsCollapsed = YES;
else
siteIsCollapsed = NO;
}
[_tblSearchResults reloadData];
}
os.environ
behaves like a python dictionary, so all the common dictionary operations can be performed. In addition to the get
and set
operations mentioned in the other answers, we can also simply check if a key exists. The keys and values should be stored as strings.
Python 3
For python 3, dictionaries use the in keyword instead of has_key
>>> import os
>>> 'HOME' in os.environ # Check an existing env. variable
True
...
Python 2
>>> import os
>>> os.environ.has_key('HOME') # Check an existing env. variable
True
>>> os.environ.has_key('FOO') # Check for a non existing variable
False
>>> os.environ['FOO'] = '1' # Set a new env. variable (String value)
>>> os.environ.has_key('FOO')
True
>>> os.environ.get('FOO') # Retrieve the value
'1'
There is one important thing to note about using os.environ
:
Although child processes inherit the environment from the parent process, I had run into an issue recently and figured out, if you have other scripts updating the environment while your python script is running, calling os.environ
again will not reflect the latest values.
Excerpt from the docs:
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
os.environ.data
which stores all the environment variables, is a dict object, which contains all the environment values:
>>> type(os.environ.data) # changed to _data since v3.2 (refer comment below)
<type 'dict'>
You can subtract 7 from the current date with this:
WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()
I got this error too but for a different reason. It turns out I had made a typo when I tried to specify the version number as a variable:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:{$playServices}"
// ...
}
I had defined the variable playServices in gradle.properties in my project's root directory:
playServices=15.0.1
The typo was {$playServices}
which should have said ${playServices}
like this:
dependencies {
// ...
implementation "com.google.android.gms:play-services-location:${playServices}"
// ...
}
That fixed the problem for me.
It's in your home folder but it's hidden by default.
Typing the below commands in the terminal made it visible for me (only the .m2
folder that is, not all the other hidden folders).
> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2
Easy done:
(?<=\[)(.*?)(?=\])
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:
Alternatively you can just capture what's between the square brackets:
\[(.*?)\]
and return the first captured group instead of the entire match.
I think this is an easy way for adding a .gitignore file to an existing repository.
Prerequisite:
You need a browser to access your github account.
Steps
Have fun!
Also, if your PATH's dir is enclosed in quotes, it will work from the command prompt but you'll get the same error message
I.e. this causes an issue with Process.Start() not finding your exe:
PATH="C:\my program\bin";c:\windows\system32
Maybe it helps someone.
It's important to understand that there are two aspects to thread safety.
The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has been done are visible to other threads. Because each CPU has several levels of cache between it and main memory, threads running on different CPUs or cores can see "memory" differently at any given moment in time because threads are permitted to obtain and work on private copies of main memory.
Using synchronized
prevents any other thread from obtaining the monitor (or lock) for the same object, thereby preventing all code blocks protected by synchronization on the same object from executing concurrently. Synchronization also creates a "happens-before" memory barrier, causing a memory visibility constraint such that anything done up to the point some thread releases a lock appears to another thread subsequently acquiring the same lock to have happened before it acquired the lock. In practical terms, on current hardware, this typically causes flushing of the CPU caches when a monitor is acquired and writes to main memory when it is released, both of which are (relatively) expensive.
Using volatile
, on the other hand, forces all accesses (read or write) to the volatile variable to occur to main memory, effectively keeping the volatile variable out of CPU caches. This can be useful for some actions where it is simply required that visibility of the variable be correct and order of accesses is not important. Using volatile
also changes treatment of long
and double
to require accesses to them to be atomic; on some (older) hardware this might require locks, though not on modern 64 bit hardware. Under the new (JSR-133) memory model for Java 5+, the semantics of volatile have been strengthened to be almost as strong as synchronized with respect to memory visibility and instruction ordering (see http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#volatile). For the purposes of visibility, each access to a volatile field acts like half a synchronization.
Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread
A
when it writes to volatile fieldf
becomes visible to threadB
when it readsf
.
So, now both forms of memory barrier (under the current JMM) cause an instruction re-ordering barrier which prevents the compiler or run-time from re-ordering instructions across the barrier. In the old JMM, volatile did not prevent re-ordering. This can be important, because apart from memory barriers the only limitation imposed is that, for any particular thread, the net effect of the code is the same as it would be if the instructions were executed in precisely the order in which they appear in the source.
One use of volatile is for a shared but immutable object is recreated on the fly, with many other threads taking a reference to the object at a particular point in their execution cycle. One needs the other threads to begin using the recreated object once it is published, but does not need the additional overhead of full synchronization and it's attendant contention and cache flushing.
// Declaration
public class SharedLocation {
static public SomeObject someObject=new SomeObject(); // default object
}
// Publishing code
// Note: do not simply use SharedLocation.someObject.xxx(), since although
// someObject will be internally consistent for xxx(), a subsequent
// call to yyy() might be inconsistent with xxx() if the object was
// replaced in between calls.
SharedLocation.someObject=new SomeObject(...); // new object is published
// Using code
private String getError() {
SomeObject myCopy=SharedLocation.someObject; // gets current copy
...
int cod=myCopy.getErrorCode();
String txt=myCopy.getErrorText();
return (cod+" - "+txt);
}
// And so on, with myCopy always in a consistent state within and across calls
// Eventually we will return to the code that gets the current SomeObject.
Speaking to your read-update-write question, specifically. Consider the following unsafe code:
public void updateCounter() {
if(counter==1000) { counter=0; }
else { counter++; }
}
Now, with the updateCounter() method unsynchronized, two threads may enter it at the same time. Among the many permutations of what could happen, one is that thread-1 does the test for counter==1000 and finds it true and is then suspended. Then thread-2 does the same test and also sees it true and is suspended. Then thread-1 resumes and sets counter to 0. Then thread-2 resumes and again sets counter to 0 because it missed the update from thread-1. This can also happen even if thread switching does not occur as I have described, but simply because two different cached copies of counter were present in two different CPU cores and the threads each ran on a separate core. For that matter, one thread could have counter at one value and the other could have counter at some entirely different value just because of caching.
What's important in this example is that the variable counter was read from main memory into cache, updated in cache and only written back to main memory at some indeterminate point later when a memory barrier occurred or when the cache memory was needed for something else. Making the counter volatile
is insufficient for thread-safety of this code, because the test for the maximum and the assignments are discrete operations, including the increment which is a set of non-atomic read+increment+write
machine instructions, something like:
MOV EAX,counter
INC EAX
MOV counter,EAX
Volatile variables are useful only when all operations performed on them are "atomic", such as my example where a reference to a fully formed object is only read or written (and, indeed, typically it's only written from a single point). Another example would be a volatile array reference backing a copy-on-write list, provided the array was only read by first taking a local copy of the reference to it.
for me the "workaround" solution was to remove the "_normal" from the end of the string
Check it out below:
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Could you try something like this:
.red:first-of-type {
border: 5px solid red;
}
you also can use this for last element (if you need it):
.red:last-of-type {
border: 5px solid red;
}
The example below seemed to work. Just setting a height on the first element
<ul class="row">
<li class="span4" style="height: 100px"><h1>1</h1></li>
<li class="span4"><h1>2</h1></li>
<li class="span4"><h1>3</h1></li>
<li class="span4"><h1>4</h1></li>
<li class="span4"><h1>5</h1></li>
<li class="span4"><h1>6</h1></li>
<li class="span4"><h1>7</h1></li>
<li class="span4"><h1>8</h1></li>
</ul>
I can't help but thinking it's the wrong use of a row though.
Before starting python, you can do in bash
export MPLBACKEND=TkAgg
You can use the MouseClicked
event:
private void tableMouseClicked(java.awt.event.MouseEvent evt) {
// Do something.
}
add app:elevation="0dp"
in AppBarLayout for hiding shadow in appbar
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print("TryA L1\n");
q();
System.out.print("TryB L1\n");
}
catch (Exception i) {
System.out.print("Catch L1\n");
}
finally {
System.out.print("Finally L1\n");
throw new MyExc1();
}
}
static void q() throws Exception {
try {
System.out.print("TryA L2\n");
q2();
System.out.print("TryB L2\n");
}
catch (Exception y) {
System.out.print("Catch L2\n");
throw new MyExc2();
}
finally {
System.out.print("Finally L2\n");
throw new Exception();
}
}
static void q2() throws Exception {
throw new MyExc1();
}
}
Order:
TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1
Exception in thread "main" MyExc1 at C1.main(C1.java:30)
The shortest:
command || exit /b
If you need, you can set the exit code:
command || exit /b 666
And you can also log:
command || echo ERROR && exit /b
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo
, here's a sample:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book.
There is no mechanical procedure that can be used to get the BigOh.
As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.
The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.
For example, let's say you have this piece of code:
int sum(int* data, int N) {
int result = 0; // 1
for (int i = 0; i < N; i++) { // 2
result += data[i]; // 3
}
return result; // 4
}
This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function:
Number_Of_Steps = f(N)
So we have f(N)
, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:
Number_Of_Steps = f(data.length)
The parameter N
takes the data.length
value. Now we need the actual definition of the function f()
. This is done from the source code, in which each interesting line is numbered from 1 to 4.
There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C
number computational steps.
We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data
array.
That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:
f(N) = C + ??? + C
The next part is to define the value of the for
statement. Remember that we are counting the number of computational steps, meaning that the body of the for
statement gets executed N
times. That's the same as adding C
, N
times:
f(N) = C + (C + C + ... + C) + C = C + N * C + C
There is no mechanical rule to count how many times the body of the for
gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for
statement.
To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this:
C
.f()
get the polynomium in its standard form
.N
approaches infinity
.Our f()
has two terms:
f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1
Taking away all the C
constants and redundant parts:
f(N) = 1 + N ^ 1
Since the last term is the one which grows bigger when f()
approaches infinity (think on limits) this is the BigOh argument, and the sum()
function has a BigOh of:
O(N)
There are a few tricks to solve some tricky ones: use summations whenever you can.
As an example, this code can be easily solved using summations:
for (i = 0; i < 2*n; i += 2) { // 1
for (j=n; j > i; j--) { // 2
foo(); // 3
}
}
The first thing you needed to be asked is the order of execution of foo()
. While the usual is to be O(1)
, you need to ask your professors about it. O(1)
means (almost, mostly) constant C
, independent of the size N
.
The for
statement on the sentence number one is tricky. While the index ends at 2 * N
, the increment is done by two. That means that the first for
gets executed only N
steps, and we need to divide the count by two.
f(N) = Summation(i from 1 to 2 * N / 2)( ... ) =
= Summation(i from 1 to N)( ... )
The sentence number two is even trickier since it depends on the value of i
. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second for
get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for
never gets executed.
On formula, that means:
f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )
Again, we are counting the number of steps. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.
f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )
(We are assuming that foo()
is O(1)
and takes C
steps.)
We have a problem here: when i
takes the value N / 2 + 1
upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i
takes N / 2 + 1
.
f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )
Since the pivotal moment i > N / 2
, the inner for
won't get executed, and we are assuming a constant C execution complexity on its body.
Now the summations can be simplified using some identity rules:
w
)Applying some algebra:
f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )
f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )
=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )
=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 =
(N / 2 - 1) * (N / 2) / 2 =
((N ^ 2 / 4) - (N / 2)) / 2 =
(N ^ 2 / 8) - (N / 4)
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )
f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + C * N
f(N) = C * 1/4 * N ^ 2 + C * N
And the BigOh is:
O(N²)
Or just use this in your View(Razor page)
@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))
I recommend that don't add date format in your model class
Try and add <%@page import="java.util.Map.Entry"%>
to your jsp file
This is what matplotlib.pyplot.scatter
is for.
As a quick example:
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)
plt.scatter(t,x,c=y)
plt.show()
When creating the colors, you may use rgb
and set its alpha
argument:
plot(1:10, col = rgb(red = 1, green = 0, blue = 0, alpha = 0.5),
pch = 16, cex = 4)
points((1:10) + 0.4, col = rgb(red = 0, green = 0, blue = 1, alpha = 0.5),
pch = 16, cex = 4)
Please see ?rgb
for details.
I accidentally moved my HomeController.js out of the directly, where it was expected. Putting it again on original location.
After that my website started to load pages automatically every second, I was even unable to look at the error. So i cleared the browser cache. It solved the problem
Sounds like a job for the UNIX command split:
split MyBigFile.csv
Just split my 55 GB csv file in 21k chunks in less than 10 minutes.
It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win
setIncludeFontPadding (boolean includepad)
or in XML
this would be:
android:includeFontPadding="false"
Set whether the TextView
includes extra top and bottom padding to make room for accents that go above the normal ascent and descent. The default is true.
I use SyntaxHighlighter with my Blogger powered blog. The actual site is hosted on my own server rather than Blogger's though (Blogger has an option of ftping posts to your own site), but having your own domain and web hosting only costs a couple of dollars a month.
@GusDeCool or anyone else trying to replace more than one thousands separators, one way to do it is a regex global replace: /foo/g
. Just remember that .
is a metacharacter, so you have to escape it or put it in brackets (\.
or [.]
). Here's one option:
var str = '6.000.000';
str.replace(/[.]/g,",");
Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:
src("'js/**/!(*.min).js")
Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js
In most cases they are essentially the same, but the second version saves memory because there is only one instance of the function instead of a separate function for each object.
A reason to use the first form is to access "private members". For example:
var A = function () {
var private_var = ...;
this.x = function () {
return private_var;
};
this.setX = function (new_x) {
private_var = new_x;
};
};
Because of javascript's scoping rules, private_var is available to the function assigned to this.x, but not outside the object.
When would you use private
and when would you use protected
?
Private Inheritance can be thought of Implemented in terms of relationship rather than a IS-A relationship. Simply put, the external interface of the inheriting class has no (visible) relationship to the inherited class, It uses the private
inheritance only to implement a similar functionality which the Base class provides.
Unlike, Private Inheritance, Protected inheritance is a restricted form of Inheritance,wherein the deriving class IS-A kind of the Base class and it wants to restrict the access of the derived members only to the derived class.
I think you try to get the remote host of the conneting user...
You can get a String like 'myuser@localhost' from the command:
SELECT USER()
You can split this result on the '@' sign, to get the parts:
-- delivers the "remote_host" e.g. "localhost"
SELECT SUBSTRING_INDEX(USER(), '@', -1)
-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)
if you are conneting via ip address you will get the ipadress instead of the hostname.
Let me seperate up everything and solve approach each problem in isolation:
Authentication
For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.
Auth server load
If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.
Transmission Security
If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.
url = username:[email protected]/api/call/nonce
If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:
nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call
It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).
Secure secret storage
It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.
If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.
(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.
Actually I found the answer myself.
I just create a new CGRect
for the tableView.frame
with the height
of table.contentSize.height
That sets the height of the UITableView
to the height
of its content.
Since the code modifies the UI, do not forget to run it in the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
//This code will run in the main thread:
CGRect frame = self.tableView.frame;
frame.size.height = self.tableView.contentSize.height;
self.tableView.frame = frame;
});
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
On the .ASPX
page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
if (data != null) {
response(data.d);
}
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>
In your .ASPX.CS
code-behind file:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");
SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
con.Open();
cmd.Parameters.AddWithValue("@Name", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Name"].ToString());
}
return result;
}
}
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.
Just set the style
:
var menu = document.createElement("select");
menu.style.width = "100px";
Or if you like, you can use jQuery:
$(menu).css("width", "100px");
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv
. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.
You could come across another problem. After installing Boost on the Linux Mint I've had the same problem. Linking -lboost_system
or -lboost_system-mt
haven't worked because library have had name libboost_system.so.1.54.0
.
So the solution is to create symbolic link to the original file. In my case
sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.54.0 /usr/lib/libboost_system.so
For more information see this question.
If you only have one bean of type EmployeeService, and the interface EmployeeService does not have other implementations, you can simply put "@Service" before the EmployeeServiceImpl and "@Autowire" before the setter method. Otherwise, you should name the special bean like @Service("myspecial") and put "@autowire @Qualifier("myspecial") before the setter method.
You can browse package folder below method.
Preferences\Browse Packages
C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages
(equals %appdata%\Sublime Text 2\Packages
)To disable resizing completely:
textarea {
resize: none;
}
To allow only vertical resizing:
textarea {
resize: vertical;
}
To allow only horizontal resizing:
textarea {
resize: horizontal;
}
Or you can limit size:
textarea {
max-width: 100px;
max-height: 100px;
}
To limit size to parents width and/or height:
textarea {
max-width: 100%;
max-height: 100%;
}
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
What about com.sun.tools.javac.util.Pair?
You say that the date is used in connection with web services, so I assume that is serialized into a string at some point.
If this is the case, you should take a look at the setTimeZone method of the DateFormat class. This dictates which time zone that will be used when printing the time stamp.
A simple example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
String timestamp = formatter.format(cal.getTime());
I ran into this issue and resolved it by removing the width styling I had used on the SVG:
.svg-div img {
width: 200px; /* removed this */
height: auto;
}
I just had an issue where I needed to solve this properly.
Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.
the code I ended up with:
$.each(messages, function(idx, el){
window.setTimeout(function(){
doSomething(el);
},Math.floor(idx+1)*10000);
});
Basically, think of the timeouts as a "timeline" of your script.
This is what we WANT to code:
DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();
This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:
At Runtime 0 : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();
Hope this helps.
You can use try catch block here:
s="1234"
try:
num=int(s)
print "S contains only digits"
except:
print "S doesn't contain digits ONLY"
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"
}
});
It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:
For example:
curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource
OR, for a RESTful API:
curl -X POST -d @file http://host/resource
You can check out more information here-> http://curl.haxx.se/
EDITs:
OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests.
Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.
More EDITs
So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be
http://localhost/library/book/34
Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:
POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name
From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.
Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!
This code works on ROOTED phones:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd + "\n");
}
os.writeBytes("exit\n");
os.flush();
}
catch (IOException e){
e.printStackTrace();
}
}
}
For turning off GPS you can use this command instead
settings put secure location_providers_allowed -gps
You can also toggle network accuracy using the following commands: for turning on use:
settings put secure location_providers_allowed +network
and for turning off you can use:
settings put secure location_providers_allowed -network
You could just create an array of the correct size up-front and fill it:
frames = np.empty((480, 640, 3, 100))
for k in xrange(nframes):
frames[:,:,:,k] = cv2.imread('frame_{}.jpg'.format(k))
if the frames were individual jpg file that were named in some particular way (in the example, frame_0.jpg, frame_1.jpg, etc).
Just a note, you might consider using a (nframes, 480,640,3)
shaped array, instead.
In the comments @libjack mentioned a point which is really important. I would like to illustrate more into it. First, we can check what are the columns of our table by describe <table_name>;
command.
there is a double-column called _c1 and such columns are created by the hive itself when we moving data from one table to another. To address these columns we need to write it inside backticks
`_c1`
Finally, the ALTER command will be,
ALTER TABLE <table_namr> CHANGE `<system_genarated_column_name>` <new_column_name> <data_type>;
This is useful tutorial, how to upload file using the ng2-file-upload and WITHOUT ng2-file-upload.
For me it helps a lot.
At the moment, tutorial contains a couple of mistakes:
1- Client should have same upload url as a server,
so in app.component.ts
change line
const URL = 'http://localhost:8000/api/upload';
to
const URL = 'http://localhost:3000';
2- Server send response as 'text/html', so in app.component.ts
change
.post(URL, formData).map((res:Response) => res.json()).subscribe(
//map the success function and alert the response
(success) => {
alert(success._body);
},
(error) => alert(error))
to
.post(URL, formData)
.subscribe((success) => alert('success'), (error) => alert(error));
What about this?
my_string = "123,456.908"
commas_removed = my_string.replace(',', '') # remove comma separation
my_float = float(commas_removed) # turn from string to float.
In short:
my_float = float(my_string.replace(',', ''))
README.md
or .mkdn
or .markdown
denotes that the file is markdown formatted.
Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text
In Additional
Thread thread = new Thread(delegate() { download(i); });
thread.Start();
The returned data is the binary data of the image type. If you use JavaScript to retrieve the user photo, please get the photo data as blob type in a XMLHttpRequest, and then retrieve the blob URL from the response. For your reference:
var request = new XMLHttpRequest;
var photoUri=config.endpoints.graphApiUri + "/v1.0/me/photo/$value";
request.open("GET",photoUri);
request.setRequestHeader("Authorization","Bearer "+token);
request.responseType = "blob";
request.onload = function (){
if(request.readyState == 4 && request.status == 200){
var image = document.createElement("img");
var url = window.URL || window.webkitURL;
var blobUrl = url.createObjectURL(request.response);
image.src = blobUrl;
document.getElementById("UserShow").appendChild(image);
}
};
request.send(null);
Change hidden field value with checkbox toggle like below...
HTML:
<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox" onclick="toggle(this)"/> Delete All
Script:
function toggle(obj) {`var $input = $(obj);
if ($input.prop('checked')) {
$('#deleteAll').attr( 'value','Checked');
} else {
$('#deleteAll').attr( 'value','Unchecked');
}
}
Performing CRUD operations using Dapper is an easy task. I have mentioned the below examples that should help you in CRUD operations.
Code for CRUD:
Method #1: This method is used when you are inserting values from different entities.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, new
{
customerModel.FirstName,
customerModel.LastName,
StateModel.State,
CityModel.City,
isActive,
CreatedOn = DateTime.Now
});
}
Method #2: This method is used when your entity properties have the same names as the SQL columns. So, Dapper being an ORM maps entity properties with the matching SQL columns.
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";
var result = db.Execute(insertQuery, customerViewModel);
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string selectQuery = @"SELECT * FROM [dbo].[Customer] WHERE FirstName = @FirstName";
var result = db.Query(selectQuery, new
{
customerModel.FirstName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string updateQuery = @"UPDATE [dbo].[Customer] SET IsActive = @IsActive WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(updateQuery, new
{
isActive,
customerModel.FirstName,
customerModel.LastName
});
}
Code for CRUD:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
string deleteQuery = @"DELETE FROM [dbo].[Customer] WHERE FirstName = @FirstName AND LastName = @LastName";
var result = db.Execute(deleteQuery, new
{
customerModel.FirstName,
customerModel.LastName
});
}
right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition
then you can create a new or choose a different connection
worked perfectly.
the get data button is next to the tiny button with a red arrow next to the range text input box.
Bootstrap 4
<ul class="nav nav-pills nav-fill">
<li class="nav-item">
<a class="nav-link active" href="#">Active</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Longer nav link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
You want the php function "asort":
http://php.net/manual/en/function.asort.php
it sorts the array, maintaining the index associations.
Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():
Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.
I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing
). I ran into the same problem with declaring global variables and figured it out with some experiments.
The reason that g_c
was not changed by the run
function within your class is that the referencing to the global name within g_c
was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c
has two effects:
Preconditions the entrance of the key "g_c"
into the dictionary accessible by the built-in function, globals()
. However, the key will not appear in the dictionary until after a value is assigned to it.
(Potentially) alters the way Python looks for the variable g_c
within the current method.
The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c
occurs within the method, then Python defaults to searching for it among the globals()
. This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.
However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c
within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:
UnboundLocalError: local variable 'g_c' referenced before assignment
Now, if the declaration global g_c
occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c
within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:
SyntaxWarning: name 'g_c' is used prior to global declaration
If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.
Here is a code that summarizes what I just said (with a few more observations):
g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
+ str("g_c" in globals()))
class TestClass():
def direct_print(self):
print("Directly printing g_c without declaration or modification: "
+ str(g_c))
#Without any local reference to the name
#Python defaults to search for the variable in globals()
#This of course happens for all the module names you import
def mod_without_dec(self):
g_c = 1
#A local assignment without declaring reference to global variable
#makes Python default to access local name
print ("After mod_without_dec, local g_c=" + str(g_c))
print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))
def mod_with_late_dec(self):
g_c = 2
#Even with a late declaration, the global variable is accessed
#However, a syntax warning will be issued
global g_c
print ("After mod_with_late_dec, local g_c=" + str(g_c))
print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))
def mod_without_dec_error(self):
try:
print("This is g_c" + str(g_c))
except:
print("Error occured while accessing g_c")
#If you try to access g_c without declaring it global
#but within the method you also alter it at some point
#then Python will not search for the name in globals()
#!!!!!Even if the assignment command occurs later!!!!!
g_c = 3
def sound_practice(self):
global g_c
#With correct declaration within the method
#The local name g_c becomes an alias for globals()["g_c"]
g_c = 4
print("In sound_practice, the name g_c points to: " + str(g_c))
t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()
Transparency is a property outside the color itself, also known as alpha
component. You can't code it as RGB.
If you want a transparent background, you can do this:
background: transparent;
Additionally, I don't know if it might be helpful or not but, you could set the opacity
property:
.half{
opacity: 0.5;
filter: alpha(opacity=50);
}
You need both in order to get it working in IE and all other decent browsers.
sys.columns.is_identity = 1
e.g.,
select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
Value of %TEMP%
environment variable is often user-specific and Windows sets it up with regard to currently logged in user account. Some user accounts may have no user profile, for example when your process runs as a service on SYSTEM
, LOCALSYSTEM
or other built-in account, or is invoked by IIS application with AppPool identity with Create user profile option disabled. So even when you do not overwrite %TEMP%
variable explicitly, Windows may use c:\temp
or even c:\windows\temp
folders for, lets say, non-usual user accounts. And what's more important, process might have no access rights to this directory!
Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.
try to replace the text/javascript to text/html then save the note and reload browser then bring it back to text/javascript.. I don't know but for unknown reason this one works with me.. I am searching and copy-pasting and I just accidentally undo what I am typing then boom kablooey it worked 0.O by the way I am just noob.. sorry I just thought it could help though..
When you assign your variables "first_number" and "second_number", you need to change "document.getElementsById" to the singular "document.getElementById".
Use '_blank'. It will not only open the link in a new tab but the state of the original webpage will also remain unaffected.