in appdelegate :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[_window rootViewController]setModalPresentationStyle:UIModalPresentationCurrentContext];
return YES;
}
in you first view controller from where you have to load next view:
NextViewController *customvc = [[NextViewController alloc]init];
[self presentViewController:customvc animated:YES completion:^{
}];
in your nextViewController which is to be added transparent:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor];
UIView* backView = [[UIView alloc] initWithFrame:self.view.frame];
backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
[self.view insertSubview:backView atIndex:0];
}
Latest for iOS 13 and Swift 5.x
let vc = ViewController(nibName: "ViewController", bundle: nil)
vc.modalPresentationStyle = .fullScreen
self.present(vc, animated: true, completion: nil)
Swift 3
let vc0 : ViewController1 = ViewController1()
let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
self.present(vc2, animated: true, completion: nil)
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
Here's the solution you're looking for:
>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]
I'd recommend using a list comprehension (the [(x, bars) for x in foos]
part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:
>>> y = ((x, bars) for x in foos)
>>> for z in y:
... print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])
The difference is that the generator comprehension is lazily loaded.
UPDATE In response to this comment:
Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.
I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:
tbars = tuple(bars)
[(x, tbars) for x in foos]
Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:
from copy import copy
[(x, copy(bars)) for x in foos]
However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.
I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.
git bash is a shell where:
sh.exe
(packaged with msysgit, as share/WinGit/Git Bash.vbs
)$HOME
is definedSee "Fix msysGit Portable $HOME
location":
On a Windows 64:
C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"
This differs from git-cmd.bat
, which provides git commands in a plain DOS command prompt.
A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)
Update April 2015:
Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:
GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.
But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2
comes with its own installer too.
The git bash is now (with the new Git For Windows):
GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.
Original answer (June 2013) More precisely, from msygit wiki:
Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.To make the milky 'soup' of project names more clear, we say like this:
- msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
- MinGW - is a minimalist development environment for native Microsoft Windows applications.
It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as afork()
call- MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
- Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit
So, your two lines description about "git bash" are:
"Git bash
" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.
Reminder:
msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.
msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.
See more in "Difference between msysgit and Cygwin + git?".
It can, because a
is a variable allocated temporarily for the lifetime of its scope (foo
function). After you return from foo
the memory is free and can be overwritten.
What you're doing is described as undefined behavior. The result cannot be predicted.
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
You should not add to your list using c
inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element)
, the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N)
. If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg
i <- 1
while(...) {
l[[i]] <- new_element
i <- i + 1
}
For more info have a look at Patrick Burns' The R Inferno (Chapter 2).
You can insert multiple records by inserting from a result:
insert into db (@names,@email,@password)
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword'
Just add as many records you like. There may be limitations on the complexity of the query though, so it might not be possible to add as many as 1000 records at once.
The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.
According to the documentation, it's
CREATE TABLE something (
column1,
column2,
column3,
PRIMARY KEY (column1, column2)
);
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
In Python 3, they made the /
operator do a floating-point division, and added the //
operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the /
operator was simply integer division, unless one of the operands was already a floating point number.
In Python 2.X:
>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335
In Python 3:
>>> 10/3
3.3333333333333335
>>> 10//3
3
For further reference, see PEP238.
Everywhere inside the query string, the wildcard should be ?
instead of '?'
. That should solve the problem.
EDIT :
To add to that, you need to change date '?'
to to_date(?, 'yyyy-mm-dd')
. Please try that and let me know.
Use a bytecode editor, like:
Be careful because you need a very good knowledge of the Java bytecode.
You can also change the class at runtime with bytecode weaving (like AspectJ).
To summarize with a complete solution...
There are 2 options:
The shortcut exists in your Start Menu. Look inside the makefile to see if there are any 'setup' actions. Actions appear as the first word before a colon. Typically, all good makefiles have an "all" action so you can type: NMAKE all
Most well designed open source solutions provide a makefile with a setup action to generate Visual Studio Project Files for you so look for those first in your Makefile.
Otherwise you need to drag and drop each file or group of files and folders into each New Project you create within Visual Studio.
Hope this helps.
Pickle save:
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
See the pickle module documentation for additional information regarding the protocol
argument.
Pickle load:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON save:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
Supply extra arguments, like sort_keys
or indent
, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N
spaces.
json.dump(data, fp, sort_keys=True, indent=4)
JSON load:
with open('data.json', 'r') as fp:
data = json.load(fp)
Usage: If you're going to store information that you want to access on different web pages, you can use SessionState
If you want to store information that you want to access from the same page, then you can use Viewstate
Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.
The SessionState will clear in the following conditions
"A call stack is composed of stack frames..." — Wikipedia
A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.
According to the docs for ngHref you should be able to leave off the href or do href="".
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import express = require('express');
or (depending on your module loader)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
svn info
or svnversion
won't take into consideration subdirectories, to find the latest 'revision' of the live codebase the hacked way below worked for me - it might take a while to run:
repo_root$ find ./ | xargs -l svn info | grep 'Revision: ' | sort
...
Revision: 86
Revision: 86
Revision: 89
Revision: 90
$
If you are looking for this:
Here is the link:
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
You can use the AssemblyName
class to get the assembly name, provided you have the full name for the assembly:
AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().FullName).Name
or
AssemblyName.GetAssemblyName(e.Source).Name
I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.
My initial thought was to wrap my dictionary in an Array. [[String: UIImage]]
but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key
so I went with Tuples. Now my array looks like [(String, UIImage)]
so I can retrieve it by tuple.0
. No more converting it to an Array. Just my 2 cents.
jQuery $(window).height();
or $(window).width();
is only work perfectly when your html page doctype is html
<!DOCTYPE html>
<html lang="en">
...
This is for anyone that is trying to get a list of all files in a folder and its sub-folders and save it in a text document.
Below is the full code including the “using” statements, “namespace”, “class”, “methods” etc.
I tried commenting as much as possible throughout the code so you could understand what each part is doing.
This will create a text document that contains a list of all files in all folders and sub-folders of any given root folder. After all, what good is a list (like in Console.WriteLine) if you can’t do something with it.
Here I have created a folder on the C drive called “Folder1” and created a folder inside that one called “Folder2”. Next I filled folder2 with a bunch of files, folders and files and folders within those folders.
This example code will get all the files and create a list in a text document and place that text document in Folder1.
Caution: you shouldn’t save the text document to Folder2 (the folder you are reading from), that would be just bad practice. Always save it to another folder.
I hope this helps someone down the line.
using System;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
public static void Main(string[] args)
{
// Create a header for your text file
string[] HeaderA = { "****** List of Files ******" };
System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);
// Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
// named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
{
//Now that we have a list of files, write them to a text file.
WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
}
// Now, append the header and list to the text file.
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
{
// First - call the header
foreach (string line in HeaderA)
{
file.WriteLine(line);
}
file.WriteLine(); // This line just puts a blank space between the header and list of files.
// Now, call teh list of files.
foreach (string name in arrayA)
{
file.WriteLine(name);
}
}
}
// These are just the "throw new exception" calls that are needed when converting the array's to strings.
// This one is for the Header.
private static void WriteAllLines(string v, string file)
{
//throw new NotImplementedException();
}
// And this one is for the list of files.
private static void WriteAllLines(string v, string[] arrayA)
{
//throw new NotImplementedException();
}
}
}
Simple answer:
In the preamble make sure you have \usepackage{amssymb}
Then in the preamble we can define this simple command: \newcommand{\qed}{\hfill $\blacksquare$}
Then whenever you want the QED symbol to complete a proof, you type \qed
.
If you prefer a hollow square, replace \blacksquare
with \square
I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.
Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.
Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.
"shutdown() doesn't actually close the file descriptor—it just changes its usability. To free a socket descriptor, you need to use close()."1
I've implemented a number of good, short and fast Pseudorandom number generator (PRNG) functions in plain JavaScript. All of them can be seeded and provide good quality numbers.
First of all, take care to initialize your PRNGs properly. Most of the generators below have no built-in seed generating procedure (for sake of simplicity), but accept one or more 32-bit values as the initial state of the PRNG. Similar seeds (e.g. a simple seed of 1 and 2) can cause correlations in weaker PRNGs, resulting in the output having similar properties (such as randomly generated levels being similar). To avoid this, it is best practice to initialize PRNGs with a well-distributed seed.
Thankfully, hash functions are very good at generating seeds for PRNGs from short strings. A good hash function will generate very different results even when two strings are similar. Here's an example based on MurmurHash3's mixing function:
function xmur3(str) {
for(var i = 0, h = 1779033703 ^ str.length; i < str.length; i++)
h = Math.imul(h ^ str.charCodeAt(i), 3432918353),
h = h << 13 | h >>> 19;
return function() {
h = Math.imul(h ^ h >>> 16, 2246822507);
h = Math.imul(h ^ h >>> 13, 3266489909);
return (h ^= h >>> 16) >>> 0;
}
}
Each subsequent call to the return function of xmur3
produces a new "random" 32-bit hash value to be used as a seed in a PRNG. Here's how you might use it:
// Create xmur3 state:
var seed = xmur3("apples");
// Output four 32-bit hashes to provide the seed for sfc32.
var rand = sfc32(seed(), seed(), seed(), seed());
// Output one 32-bit hash to provide the seed for mulberry32.
var rand = mulberry32(seed());
// Obtain sequential random numbers like so:
rand();
rand();
Alternatively, simply choose some dummy data to pad the seed with, and advance the generator a few times (12-20 iterations) to mix the initial state thoroughly. This is often seen in reference implementations of PRNGs, but it does limit the number of initial states.
var seed = 1337 ^ 0xDEADBEEF; // 32-bit seed with optional XOR value
// Pad seed with Phi, Pi and E.
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
var rand = sfc32(0x9E3779B9, 0x243F6A88, 0xB7E15162, seed);
for (var i = 0; i < 15; i++) rand();
The output of these PRNG functions produce a positive 32-bit number (0 to 232-1) which is then converted to a floating-point number between 0-1 (0 inclusive, 1 exclusive) equivalent to Math.random()
, if you want random numbers of a specific range, read this article on MDN. If you only want the raw bits, simply remove the final division operation.
Another thing to note are the limitations of JS. Numbers can only represent whole integers up to 53-bit resolution. And when using bitwise operations, this is reduced to 32. This makes it difficult to implement algorithms written in C or C++, that use 64-bit numbers. Porting 64-bit code requires shims that can drastically reduce performance. So for the sake of simplicity and efficiency, I've only considered algorithms that use 32-bit math, as it is directly compatible with JS.
Now, onward to the the generators. (I maintain the full list with references here)
sfc32 is part of the PractRand random number testing suite (which it passes of course). sfc32 has a 128-bit state and is very fast in JS.
function sfc32(a, b, c, d) {
return function() {
a >>>= 0; b >>>= 0; c >>>= 0; d >>>= 0;
var t = (a + b) | 0;
a = b ^ b >>> 9;
b = c + (c << 3) | 0;
c = (c << 21 | c >>> 11);
d = d + 1 | 0;
t = t + d | 0;
c = c + t | 0;
return (t >>> 0) / 4294967296;
}
}
Mulberry32 is a simple generator with a 32-bit state, but is extremely fast and has good quality (author states it passes all tests of gjrand testing suite and has a full 232 period, but I haven't verified).
function mulberry32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
I would recommend this if you just need a simple but decent PRNG and don't need billions of random numbers (see Birthday problem).
As of May 2018, xoshiro128** is the new member of the Xorshift family, by Vigna & Blackman (professor Vigna was also responsible for the Xorshift128+ algorithm powering most Math.random
implementations under the hood). It is the fastest generator that offers a 128-bit state.
function xoshiro128ss(a, b, c, d) {
return function() {
var t = b << 9, r = a * 5; r = (r << 7 | r >>> 25) * 9;
c ^= a; d ^= b;
b ^= c; a ^= d; c ^= t;
d = d << 11 | d >>> 21;
return (r >>> 0) / 4294967296;
}
}
The authors claim it passes randomness tests well (albeit with caveats). Other researchers have pointed out that fails some tests in TestU01 (particularly LinearComp and BinaryRank). In practice, it should not cause issues when floats are used (such as these implementations), but may cause issues if relying on the raw low bits.
This is JSF or 'smallprng' by Bob Jenkins (2007), the guy who made ISAAC and SpookyHash. It passes PractRand tests and should be quite fast, although not as fast as SFC.
function jsf32(a, b, c, d) {
return function() {
a |= 0; b |= 0; c |= 0; d |= 0;
var t = a - (b << 27 | b >>> 5) | 0;
a = b ^ (c << 17 | c >>> 15);
b = c + d | 0;
c = d + t | 0;
d = a + t | 0;
return (d >>> 0) / 4294967296;
}
}
LCG is extremely fast and simple, but the quality of its randomness is so low, that improper use can actually cause bugs in your program!
Nonetheless, it is significantly better than some answers suggesting to use Math.sin
or Math.PI
! It's a one-liner though, which is nice :).
var LCG=s=>()=>(2**31-1&(s=Math.imul(48271,s)))/2**31;
This implementation is called the minimal standard RNG as proposed by Park–Miller in 1988 & 1993 and implemented in C++11 as minstd_rand
. Keep in mind that the state is 31-bit (31 bits give 2 billion possible states, 32 bits give double that). This is the very type of PRNG that others are trying to replace!
It will work, but I wouldn't use it unless you really need speed and don't care about randomness quality (what is random anyway?). Great for a game jam or a demo or something. LCGs suffer from seed correlations, so it is best to discard the first result of an LCG. And if you insist on using an LCG, adding an increment value may improve results, but it is probably an exercise in futility when much better options exist.
There seems to be other multipliers offering a 32-bit state (increased state-space):
var LCG=s=>()=>(s=Math.imul(741103597,s)>>>0)/2**32;
var LCG=s=>()=>(s=Math.imul(1597334677,s)>>>0)/2**32;
These LCG values are from: P. L'Ecuyer: A table of Linear Congruential Generators of different sizes and good lattice structure, April 30 1997.
MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
Specifies the maximum length of array or string data allowed in a property.
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
Specifies the minimum and maximum length of characters that are allowed in a data field.
Just one line will be OK.
cat "`dirname $0`"/../some.txt
Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:
C:\path\to\script> php script.php
Or, if you're using the PHP CGI, I think it's:
C:\path\to\script> php-cgi script.php
Plus, you would also set ini_set('max_execution_time', 0);
in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.
You can also use partial
from functools
if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:
def mock_year(year):
return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))
This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.
I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});
See this link
Resize or Modify a MS SQL Server Table Column with Default Constraint using T-SQL Commands
the solution for such a SQL Server problem is going to be
Dropping or disabling the DEFAULT Constraint on the table column.
Modifying the table column data type and/or data size.
Re-creating or enabling the default constraint back on the sql table column.
Bye
I came across this problem because my cols exceeded the row grid length (> 12)
A solution using 100% Bootstrap 4:
Since the rows in Bootstrap are already display: flex
You just need to add flex-fill
to the Col, and h-100
to the container and any children.
Pen here: https://codepen.io/joshkopecek/pen/Exjdgjo
<div class="container-fluid h-100">
<div class="row justify-content-center h-100">
<div class="col-4 hidden-md-down flex-fill" id="yellow">
XXXX
</div>
<div id="blue" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Form Goes Here
</div>
<div id="green" class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8 h-100">
Another form
</div>
</div>
</div>
try this...
public class Student
{
public int Grade { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name{0} : Grade{1}", Name, Grade);
}
}
class Program
{
static void Main(string[] args)
{
List<Student> listStudents = new List<Student>();
listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });
listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
}
}
int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;
for (int iCol = 0; iCol < countCol; iCol++)
{
DataColumn col = dt.Columns[iCol];
for (int iRow = 0; iRow < countRow; iRow++)
{
object cell = dt.Rows[iRow].ItemArray[iCol];
}
}
var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
owl.trigger('owl.prev');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
owl.trigger('owl.next');
})
var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
// With optional speed parameter
// Parameters has to be in square bracket '[]'
owl.trigger('prev.owl.carousel', [300]);
})
This will not only validate your email, but also sanitize it for unexpected characters:
$email = $_POST['email'];
$emailB = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($emailB, FILTER_VALIDATE_EMAIL) === false ||
$emailB != $email
) {
echo "This email adress isn't valid!";
exit(0);
}
This works in many popular languages like JavaScript and Ruby, why not in Python?
>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
Strange enough, in Python the join
method is on the str
class:
# this is the Python way
"".join(['a','b','c','d'])
Why join
is not a method in the list
object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list)
method means: join the list into a new string using str
as a separator (in this case str
is an empty string).
Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
Syntax:
SELECT <Expression>[Arithmetic_Operator]<expression>...
FROM [Table_Name]
WHERE [expression];
Use attribute fill-opacity
in your element of SVG.
Default value is 1, minimum is 0, in step use decimal values EX: 0.5 = 50% of alpha. Note: It is necessary to define fill
color to apply fill-opacity
.
See my example.
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
When it is matter of mysql how to count or get how many rows in a table with PHP PDO I use this
// count total number of rows
$query = "SELECT COUNT(*) as total_rows FROM sometable";
$stmt = $con->prepare($query);
// execute query
$stmt->execute();
// get total rows
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];
credits goes to Mike @ codeofaninja.com
The constructor of unique_ptr<T>
accepts a raw pointer to an object of type T
(so, it accepts a T*
).
In the first example:
unique_ptr<int> uptr (new int(3));
The pointer is the result of a new
expression, while in the second example:
unique_ptr<double> uptr2 (pd);
The pointer is stored in the pd
variable.
Conceptually, nothing changes (you are constructing a unique_ptr
from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:
unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);
Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).
This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:
unique_ptr<int> p = make_unique<int>(42);
Which is both clearer and safer. Now concerning this doubt of yours:
What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.
Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.
This way you do not have to remember doing delete
on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:
{
unique_ptr<int> p = make_unique<int>(42);
// Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete
Now unique_ptr
is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr
is non-copyable.
As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.
Here is assembly code:
7f0b024734be: 48 8d 14 f5 00 00 00 lea rdx,[rsi*8]
7f0b024734c5: 00
7f0b024734c6: 48 03 13 add rdx,QWORD PTR [rbx]
7f0b024734c9: 48 8d 7a 10 lea rdi,[rdx+16]
7f0b024734cd: 8b 5f 08 mov ebx,DWORD PTR [rdi+8]
7f0b024734d0: 89 d8 mov eax,ebx
7f0b024734d2: c1 f8 03 sar eax,0x3
7f0b024734d5: 85 db test ebx,ebx
7f0b024734d7: 0f 8e cb 05 00 00 jle 0x7f0b02473aa8
And what it does is:
rdx = 0x00007f0a808d4ed2 * 8; // equals 0x0003F854046A7690. WTF???
rdx = rdx + something from old gen heap; // results 0x000600007f090486
rdi = rdx + 16; // results 0x000600007f090496
ebx = something from edi address (0x000600007f090496) + 8
Well I've had a look at the address map and there is nothing mapped to 0x000600007f090496 which is why you are getting a SEGV. Are you getting the same error with 1.6.0_26 JVM? Can you try it on a 32bit JVM? Looks like a JVM issue to me. Why would it do the first rdx=0x0... * 8 thing?
In my case everything said above was OK, but I still have been receiving ORA-12545: Network Transport: Unable to resolve connect hostname
I tried to ping the Oracle machine and found out I cannot see it and added it to the hosts file. Then I received another error message ORA-12541: TNS:no listener
. After investigation I realized that pinging the same hostname from different machines getting different IP addresses(I don't know why) and I changed the IP address in my host file, which resolved the problem on 100%.
I'm bothering to write my experience as it seems obvious, but although I was sure the problem is in the above settings I totally forgot to check if I really can see the remote DB machine out there. Keep it in mind when you are out of ideas what is going on.....
These links helped me a lot:
http://www.moreajays.com/2013/03/ora-12545-connect-failed-because-target.html http://www.orafaq.com/wiki/ORA-12541
The solution is already answered here above (long ago).
But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).
This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.
I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:
<code>
- tag to prevent the curly brackets from being interpreted{@code ...}
- tag to get the generics included in the output@Override
via "{@literal @}Override
" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket{@code
and {@literal
, to compensate inner spaces and keep the alignmentjavadoc code:
/** this methods adds a specific translator from one type to another type. `
* i.e.
* <pre>
* <code>new BeanTranslator.Builder()
* .translate(
* new{@code Translator<String, Integer>}(String.class, Integer.class){
* {@literal @}Override
* public Integer translate(String instance) {
* return Integer.valueOf(instance);
* }})
* .build();
* </code>
* </pre>
* @param translator
*/
gets printed as
new BeanTranslator.Builder()
.translate(
new Translator<String, Integer>(String.class, Integer.class){
@Override
public Integer translate(String instance) {
return Integer.valueOf(instance);
}})
.build();
n
in name
.I
(capital i).vendor_
. Note: It will only update the screen in the first line - until Esc is pressed (6.), at which point all lines will be updated.An uppercase I
must be used rather than a lowercase i
, because the lowercase i
is interpreted as the start of a text object, which is rather useful on its own, e.g. for selecting inside a tag block (it
):
If the default behavior (example.com/?p=42
) is working, you should:
Admin: Settings > Permalinks
, and click Save. Sometime it fixes the issue. If it didn't:/path/to/wordpress/.htaccess
has been changed and now includes the line RewriteEngine On
. If it doesn't include the line, it's a Wordpress permissions issue.Verify that the 'rewrite' module is loaded: create a PHP file with
<?php
phpinfo()
?>
in it, open it in the browser and search for mod_rewrite
. It should be in the 'Loaded Modules' section.
If it's not, enable it - Look at your apache default index.html
file for details - in Ubuntu, you do it with the helper a2enmod
.
Verify that apache server is looking at the .htaccess
file. open httpd.conf
- or it's Ubuntu's alternative, /etc/apache2/apache2.conf
. In it, You should have something like
<Directory /path/to/wordpress>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
After making these changes, don't forget to restart your apache server. sudo service apache2 restart
origin/master
is an entity (since it is not a physical branch) representing the state of the master
branch on the remote origin
.
origin master
is the branch master
on the remote origin
.
So we have these:
Example (in local branch master
):
git fetch # get current state of remote repository
git merge origin/master # merge state of remote master branch into local branch
git push origin master # push local branch master to remote branch master
Use raw keyword, http://twig.sensiolabs.org/doc/api.html#escaper-extension
{{ word | raw }}
It's called market segmentation or something like that. nVidia produces one very configurable chip and then sells it in different configurations that essentially have the same elements and hence the same bill of materials to different market segments, although one would usually expect to find elements of higher quality on the more expensive Quadro boards.
What differentiates Quadro from GeForce is that GeForce usually has its dual precision floating point performance severely limited, e.g. to 1/4 or 1/8 of that of the Quadro/Tesla GPUs. This limitation is purely artificial and imposed on solely to differentiate the gamer/enthusiast segment from the professional segment. Lower DP performance makes GeForce boards bad candidates for stuff like scientific or engineering computing and those are markets where money streams from. Also Quadros (arguably) have more display channels and faster RAMDACs which allows them to drive more and higher resolution screens, a sort of setup perceived as professional for CAD/CAM work.
As Jason Morgan has pointed out, there are tricks that can unlock some of the disabled features in GeForce to bring them in par with Quadro. Those usually involves soldering and voids the warranty on the card. Since HPC puts lots of stress on the hardware and malfunctions occur more frequently that one would like them to, I would advise against using cheap tricks.
You could use reinterprete_cast to check inheritance at compile time.
Look here:
Using reinterpret_cast to check inheritance at compile time
Since TestRef is a class (which are reference objects), you can change the contents inside t without passing it as a ref. However, if you pass t as a ref, TestRef can change what the original t refers to. i.e. make it point to a different object.
This example does not swap two int pointers. It swaps the value of the integers that pa
and pb
are pointing to. Here's an example of what's going on when you call this:
void Swap1 (int *pa, int *pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
int main()
{
int a = 42;
int b = 17;
int *pa = &a;
int *pb = &b;
printf("--------Swap1---------\n");
printf("a = %d\n b = %d\n", a, b);
swap1(pa, pb);
printf("a = %d\n = %d\n", a, a);
printf("pb address = %p\n", pa);
printf("pa address = %p\n", pb);
}
The output here is:
a = 42
b = 17
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
--------Swap---------
pa = 17
pb = 42
a = 17
b = 42
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
Note that the values swapped, but the pointer's addresses did not swap!
In order to swap addresses we need to do this:
void swap2 (int **pa, int **pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
and in main call the function like swap2(&pa, &pb);
Now the addresses are swapped, as well as the values for the pointers. a
and b
have the same values that the are initialized with The integers a and b did not swap because it swap2
swaps the addresses being being pointed to by the pointers!:
a = 42
b = 17
pa address = 0x7fffddaa9c98
pb address = 0x7fffddaa9c9c
--------Swap---------
pa = 17
pb = 42
a = 42
b = 17
pa address = 0x7fffddaa9c9c
pb address = 0x7fffddaa9c98
Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.
The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.
Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters
nil?
can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:
return my_string.nil? || my_string.empty?
Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:
serve("ws").with(MyWSServlet.class,
new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});
Anything <0 is infinite idle time I believe.
Alternative method: In Eclipse 3.6, under "Line Wrapping" then "General Settings" there is an option to "Never join already wrapped lines." This means the formatter will wrap long lines but not undo any wrapping you already have.
I have seen such error and i solved it. You may have missing values in your data set. Number of observations in every column must also be the same.
If you're doing this in an Node.js app, you can use the leap-year package:
npm install --save leap-year
Then from your app, use the following code to verify whether the provided year or date object is a leap year:
var leapYear = require('leap-year');
leapYear(2014);
//=> false
leapYear(2016);
//=> true
Using a library like this has the advantage that you don't have to deal with the dirty details of getting all of the special cases right, since the library takes care of that.
This doesn't quite match the OP requirements, though hopefully it helps. With Laravel you can define your rules in an easy-to-maintain format like so:
$inputs = [
'email' => 'foo',
'password' => 'bar',
];
$rules = [
'email' => 'required|email',
'password' => [
'required',
'string',
'min:10', // must be at least 10 characters in length
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
'regex:/[@$!%*#?&]/', // must contain a special character
],
];
$validation = \Validator::make( $inputs, $rules );
if ( $validation->fails() ) {
print_r( $validation->errors()->all() );
}
Would output:
[
'The email must be a valid email address.',
'The password must be at least 10 characters.',
'The password format is invalid.',
]
(The regex rules share an error message by default—i.e. four failing regex rules result in one error message)
There is one "trick" for this problem that fits all scenarios, a so obvious solution that you will have to try it to believe it actually works... :)
Here it is...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>
Basically, you are asking MOD_REWRITE to forward to index.php
the URI request always when a file exists AND always when the requested file doesn't exist!
When investigating the source code of MOD-REWRITE to understand how it works I realized that all its checks always happen after the verification if the referenced file exists or not. Only then the RegEx
are processed. Even when your URI points to a folder, Apache will enforce the check for the index files listed in its configuration file.
Based on that simple discovery, turned obvious a simple file validation would be enough for all possible calls, as far as we double-tap the file presence check and route both results to the same end-point, covering 100% of the possibilities.
IMPORTANT: Notice there is no "/" in index.php
. By default, MOD_REWRITE will use the folder it is set as "base folder" for the forwarding. The beauty of it is that it doesn't necessarily need to be the "root folder" of the site, allowing this solution work for localhost/
and/or any subfolder you apply it.
Ultimately, some other solutions I tested before (the ones that appeared to be working fine) broke the PHP ability to "require" a file via its relative path, which is a bummer. Be careful.
Some people may say this is an inelegant solution. It may be, actually, but as far as tests, in several scenarios, several servers, several different Apache versions, etc., this solution worked 100% on all cases!
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
To set the disabled
to false using the name
property of the input:
document.myForm.myInputName.disabled = false;
Two-liner with new line:
for(int[] x: matrix)
System.out.println(Arrays.toString(x));
One liner without new line:
System.out.println(Arrays.deepToString(matrix));
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
This task can be easily done using PrettyKit by adding about 5 lines of code. If you use nib
files or storyboard
, also do not forget to apply this little hack . When you use this approach, you should subclass your cell from PrettyTableViewCell
:
#import <PrettyKit/PrettyKit.h>
@class RRSearchHistoryItem;
@interface RRSearchHistoryCell : PrettyTableViewCell
This is example of my cellForRowAtIndexPath
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"RRSearchHistoryCell";
RRSearchHistoryCell *cell = (RRSearchHistoryCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if ( cell == nil ) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RRSearchHistoryCell" owner:self options:nil];
cell = topLevelObjects[0];
cell.gradientStartColor = RGB(0xffffff);
cell.gradientEndColor = RGB(0xf3f3f3);
}
RRSearchHistoryItem *item = _historyTableData[indexPath.row];
[cell setHistoryItem:item];
[cell prepareForTableView:tableView indexPath:indexPath];
return cell;
}
Although this is old, it still keeps coming up pretty well in google. So I figured I'd mention this. No one mentioned to check for when x = 0.
0! and 1! both = 1.
This isn't being checked with the previous answers, and would cause a stack overflow, if fact(0) was run. Anyway simple fix:
public static int fact(int x){
if (x==1 | x==0)
return 1;
return fact(x-1) * x;
}// fact
Step 1: Define attributes in $appends
Step 2: Define accessor for that attributes.
Example:
<?php
...
class Movie extends Model{
protected $appends = ['cover'];
//define accessor
public function getCoverAttribute()
{
return json_decode($this->InJson)->cover;
}
The newer android phones in the market like HTC one, Xperia Z etc have resolutions in the >480dpi range, putting them in the new xxhdpi class as well. The new assets might be useful for them too.
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
overrides:
- files: *-tests.js
rules:
no-param-reassign: 0
You can also set a specific env for a folder, like this :
overrides:
- files: test/*-tests.js
env:
mocha: true
This configuration will fix error message about describe
and it
not defined, only for your test folder:
/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
@msb gives a safe solution.
I met this problem when I did import tensorflow as tf
in conda environment in CentOS 6.5
which only has glibc-2.12
.
ImportError: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by /home/
I want to supply some details:
First install glibc
to your home directory:
mkdir ~/glibc-install; cd ~/glibc-install
wget http://ftp.gnu.org/gnu/glibc/glibc-2.17.tar.gz
tar -zxvf glibc-2.17.tar.gz
cd glibc-2.17
mkdir build
cd build
../configure --prefix=/home/myself/opt/glibc-2.17 # <-- where you install new glibc
make -j<number of CPU Cores> # You can find your <number of CPU Cores> by using **nproc** command
make install
Second, follow the same way to install patchelf;
Third, patch your Python:
[myself@nfkd ~]$ patchelf --set-interpreter /home/myself/opt/glibc-2.17/lib/ld-linux-x86-64.so.2 --set-rpath /home/myself/opt/glibc-2.17/lib/ /home/myself/miniconda3/envs/tensorflow/bin/python
as mentioned by @msb
Now I can use tensorflow-2.0 alpha
in CentOS 6.5
.
ref: https://serverkurma.com/linux/how-to-update-glibc-newer-version-on-centos-6-x/
Add "EntityFramework.SqlServer.dll" into your bin folder. Problem will get resolved.
I think you have to include jQuery to use responseJSON
.
Without jQuery, you could try with responseText and try like eval("("+req.responseText+")");
UPDATE:Please read the comment regarding eval
, you can test with eval, but don't use it in working extension.
OR
use json_parse : it does not use eval
You should actually create a class:
class accum:
def __init__(self):
self.acc = 0
def accumulator(self, var2add, end):
if not end:
self.acc+=var2add
return self.acc
Use the toInteger()
method to convert a String
to an Integer
, e.g.
int value = "99".toInteger()
An alternative, which avoids using a deprecated method (see below) is
int value = "66" as Integer
If you need to check whether the String
can be converted before performing the conversion, use
String number = "66"
if (number.isInteger()) {
int value = number as Integer
}
In recent versions of Groovy one of the toInteger()
methods has been deprecated. The following is taken from org.codehaus.groovy.runtime.StringGroovyMethods
in Groovy 2.4.4
/**
* Parse a CharSequence into an Integer
*
* @param self a CharSequence
* @return an Integer
* @since 1.8.2
*/
public static Integer toInteger(CharSequence self) {
return Integer.valueOf(self.toString().trim());
}
/**
* @deprecated Use the CharSequence version
* @see #toInteger(CharSequence)
*/
@Deprecated
public static Integer toInteger(String self) {
return toInteger((CharSequence) self);
}
You can force the non-deprecated version of the method to be called using something awful like:
int num = ((CharSequence) "66").toInteger()
Personally, I much prefer:
int num = 66 as Integer
First of all, there are many, many ways of matching items within a HTML document. Start with this reference to see some of the available selectors/patterns which you can use to apply a style rule to an element(s).
http://www.w3.org/TR/selectors/
Match all div
s which are direct descendants of #main
.
#main > div
Match all div
s which are direct or indirect descendants of #main
.
#main div
Match the first div
which is a direct descendant of #sections
.
#main > div:first-child
Match a div
with a specific attribute.
#main > div[foo="bar"]
A couple of observations:
When you instantiate the second view controller, you are calling ViewControllerB()
. If that view controller programmatically creates its view (which is unusual) that would be fine. But the presence of the IBOutlet
suggests that this second view controller's scene was defined in Interface Builder, but by calling ViewControllerB()
, you are not giving the storyboard a chance to instantiate that scene and hook up all the outlets. Thus the implicitly unwrapped UILabel
is nil
, resulting in your error message.
Instead, you want to give your destination view controller a "storyboard id" in Interface Builder and then you can use instantiateViewController(withIdentifier:)
to instantiate it (and hook up all of the IB outlets). In Swift 3:
let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
You can now access this controller
's view
.
But if you really want to do addSubview
(i.e. you're not transitioning to the next scene), then you are engaging in a practice called "view controller containment". You do not just want to simply addSubview
. You want to do some additional container view controller calls, e.g.:
let controller = storyboard!.instantiateViewController(withIdentifier: "scene storyboard id")
addChild(controller)
controller.view.frame = ... // or, better, turn off `translatesAutoresizingMaskIntoConstraints` and then define constraints for this subview
view.addSubview(controller.view)
controller.didMove(toParent: self)
For more information about why this addChild
(previously called addChildViewController
) and didMove(toParent:)
(previously called didMove(toParentViewController:)
) are necessary, see WWDC 2011 video #102 - Implementing UIViewController Containment. In short, you need to ensure that your view controller hierarchy stays in sync with your view hierarchy, and these calls to addChild
and didMove(toParent:)
ensure this is the case.
Also see Creating Custom Container View Controllers in the View Controller Programming Guide.
By the way, the above illustrates how to do this programmatically. It is actually much easier if you use the "container view" in Interface Builder.
Then you don't have to worry about any of these containment-related calls, and Interface Builder will take care of it for you.
For Swift 2 implementation, see previous revision of this answer.
You are misusing the API.
Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).
This is managed by the ASP.NET SynchronizationContext
.
By default, when you await
a Task
, the method resumes on a captured SynchronizationContext
(or a captured TaskScheduler
, if there is no SynchronizationContext
). Normally, this is just what you want: an asynchronous controller action will await
something, and when it resumes, it resumes with the request context.
So, here's why test5
fails:
Test5Controller.Get
executes AsyncAwait_GetSomeDataAsync
(within the ASP.NET request context).AsyncAwait_GetSomeDataAsync
executes HttpClient.GetAsync
(within the ASP.NET request context).HttpClient.GetAsync
returns an uncompleted Task
.AsyncAwait_GetSomeDataAsync
awaits the Task
; since it is not complete, AsyncAwait_GetSomeDataAsync
returns an uncompleted Task
.Test5Controller.Get
blocks the current thread until that Task
completes.Task
returned by HttpClient.GetAsync
is completed.AsyncAwait_GetSomeDataAsync
attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get
.Here's why the other ones work:
test1
, test2
, and test3
): Continuations_GetSomeDataAsync
schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task
returned by Continuations_GetSomeDataAsync
to complete without having to re-enter the request context.test4
and test6
): Since the Task
is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync
to use the ASP.NET request context when it is ready to continue.And here's the best practices:
async
methods, use ConfigureAwait(false)
whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync
to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
Task
s; it's async
all the way down. In other words, use await
instead of GetResult
(Task.Result
and Task.Wait
should also be replaced with await
).That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync
method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async
(which doesn't block a request thread).
More information:
async
/await
intro post, which includes a brief description of how Task
awaiters use SynchronizationContext
.SynchronizationContext
restricts the request context to just one thread at a time.Update 2012-07-13: Incorporated this answer into a blog post.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
That's because the color
input only accepts three attributes: "primary"
, "accent"
or "warn"
. Hence, you'll have to style the icons the CSS way:
Add a class to style your icon:
.white-icon {
color: white;
}
/* Note: If you're using an SVG icon, you should make the class target the `<svg>` element */
.white-icon svg {
fill: white;
}
Add the class to your icon:
<mat-icon class="white-icon">menu</mat-icon>
This is the shortest way you can do that
list.push($('<li>', {text: blocks[i] }));
$('ul').append(list);
Where blocks in an array. and you need to loop through the array.
//How to start another application from the current application
Process runProg = new Process();
runProg.StartInfo.FileName = pathToFile; //the path of the application
runProg.StartInfo.Arguments = genArgs; //any arguments you want to pass
runProg.StartInfo.CreateNoWindow = true;
runProg.Start();
//How to end the same application from the current application
int IDstring = System.Convert.ToInt32(runProg.Id.ToString());
Process tempProc = Process.GetProcessById(IDstring);
tempProc.CloseMainWindow();
tempProc.WaitForExit();
In Spyder 2.3.8 on Ubuntu, I found several settings to do this - each one for a different part of the window... Seems that you can't make all areas dark though.
And the final result looks like this:
It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en
To make values empty you can do the following:
$("#element").val('');
To get the selected value you can do:
var value = $("#element").val();
Where #element
is the id of the element you wish to select.
Here's something I've just knocked up. It inspects the environment of the last-launched "gnome-session" process (DISPLAY is set correctly when VNC launches a session/window manager). Replace "gnome-session" with the name of whatever process your VNC server launches on startup.
PID=`pgrep -n -u $USER gnome-session`
if [ -n "$PID" ]; then
export DISPLAY=`awk 'BEGIN{FS="="; RS="\0"} $1=="DISPLAY" {print $2; exit}' /proc/$PID/environ`
echo "DISPLAY set to $DISPLAY"
else
echo "Could not set DISPLAY"
fi
unset PID
You should just be able to drop that in your .bashrc file.
The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.
So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:
public static String doPostSecureWithHeader(String url, String body, Map headers) throws Exception { log.info("start doPostSecureWithHeader " + url + " with param " + body); long startTime; long endTime; startTime = System.currentTimeMillis(); Client client; client = Client.create(); WebResource webResource; webResource = null; String output = null; try{ SSLContext sslContext = null; SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); sslContext = SSLContext.getInstance("SSL"); sslContext .init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); defaultClientConfig .getProperties() .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties( getHostnameVerifier(), sslContext)); client = Client.create(defaultClientConfig); webResource = client.resource(url); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ webResource.setProperty(entry.getKey(), entry.getValue()); } } WebResource.Builder builder = webResource.accept("application/json"); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ builder.header(entry.getKey(), entry.getValue()); } } ClientResponse response = builder .post(ClientResponse.class, body); output = response.getEntity(String.class); } catch(Exception e){ log.error(e.getMessage(),e); if(e.toString().contains("One or more of query value parameters are null")){ output="-1"; } if(e.toString().contains("401 Unauthorized")){ throw e; } } finally { if (client!= null) { client.destroy(); } } endTime = System.currentTimeMillis(); log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output); return output; }
Since 0.17, you have to use the explicit conversions:
pd.to_datetime, pd.to_timedelta and pd.to_numeric
(As mentioned below, no more "magic", convert_objects
has been deprecated in 0.17)
df = pd.DataFrame({'x': {0: 'a', 1: 'b'}, 'y': {0: '1', 1: '2'}, 'z': {0: '2018-05-01', 1: '2018-05-02'}})
df.dtypes
x object
y object
z object
dtype: object
df
x y z
0 a 1 2018-05-01
1 b 2 2018-05-02
You can apply these to each column you want to convert:
df["y"] = pd.to_numeric(df["y"])
df["z"] = pd.to_datetime(df["z"])
df
x y z
0 a 1 2018-05-01
1 b 2 2018-05-02
df.dtypes
x object
y int64
z datetime64[ns]
dtype: object
and confirm the dtype is updated.
OLD/DEPRECATED ANSWER for pandas 0.12 - 0.16: You can use convert_objects
to infer better dtypes:
In [21]: df
Out[21]:
x y
0 a 1
1 b 2
In [22]: df.dtypes
Out[22]:
x object
y object
dtype: object
In [23]: df.convert_objects(convert_numeric=True)
Out[23]:
x y
0 a 1
1 b 2
In [24]: df.convert_objects(convert_numeric=True).dtypes
Out[24]:
x object
y int64
dtype: object
Magic! (Sad to see it deprecated.)
Why not just the good ol' javascript?
$('#element')[0].click()
Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.
Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.
function rotCor(angle, length){
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newx = length*cos;
var newy = length*sin;
return {
x : newx,
y : newy
};
}
DATE_ADD
works correctly. 1 January plus 6 months is 1 July, just like 1 January plus 1 month is 1 of February.
Between operation is inclusive. So, you are getting everything up to, and including, 1 July. (see also MySQL "between" clause not inclusive?)
What you need to do is subtract 1 day or use < operator instead of between.
Did I mention Ruby has an EPIC community of developers. Ninja theme inspired by Object Oriented Ruby: Classes, Mixins and Jedi.
Ruby gets inheritance right with Single Inheritance! Needing to use multiple inheritance to express domain relationships is a symptom of an improperly designed system. The confusion multiple inheritance creates isn't worth the added functionality.
Say you have a method called kick:
def kick
puts "kick executed."
end
What if kick is defined in both class Ninjutsu and class Shaolin? Multiple Inheritance fails here and that's why Python fails:
class Mortal < Ninjutsu, Shaolin
def initialize
puts "mortal pwnage."
end
end
In Ruby if you need a Ninja, you create an instance of the Ninja class. If you need a Shaolin master, you create an instance of the Shaolin class.
ninja = Ninjutsu.new
ninja.kick
or
master = Shaolin.new
master.kick
There might be the off chance that both a Ninja and a Shaolin master share the same kick technique. Read that again - both share the same behavior - nothing else! Python would encourage you to roll a whole new class. Not with Ruby! In Ruby you simply use a Mixin:
module Katas
def kick
puts "Temporal Whip Kick."
end
end
and simply Mixin the Katas module into your Ruby Class:
require 'Katas'
class Moral < Ninjutsu
include Katas
def initialize
puts "mortal pwnage."
end
end
Then the behavior gets shared - which is what you were really going for. Not an entire class. That's the biggest difference between Ruby and Python - Ruby gets inheritance right!
To get unique values from your list use code below:
trends = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
output = set(trends)
output = list(output)
IMPORTANT: Approach above won't work if any of items in a list is not hashable which is case for mutable types, for instance list or dict.
trends = [{'super':u'nowplaying'}, u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
output = set(trends)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
That means that you have to be sure that trends
list would always contains only hashable items otherwise you have to use more sophisticated code:
from copy import deepcopy
try:
trends = [{'super':u'nowplaying'}, [u'PBS',], [u'PBS',], u'nowplaying', u'job', u'debate', u'thenandnow', {'super':u'nowplaying'}]
output = set(trends)
output = list(output)
except TypeError:
trends_copy = deepcopy(trends)
while trends_copy:
trend = trends_copy.pop()
if trends_copy.count(trend) == 0:
output.append(trend)
print output
You don't need to add '.' in your class name. This will do
document.getElementsByClassName('col1')
Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.
Here is a working example
firstOrCreate()
checks for all the arguments to be present before it finds
a match. If not all arguments match, then a new instance of the model will be created.
If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value'])
with only one item in the array. This will return the first item that matches, or create a new one if not matches are found.
The difference between firstOrCreate()
and firstOrNew()
:
firstOrCreate()
will automatically create a new entry in the database if there is not match found. Otherwise it will give you the matched item.firstOrNew()
will give you a new model instance to work with if not match was found, but will only be saved to the database when you explicitly do so (calling save()
on the model). Otherwise it will give you the matched item.Choosing between one or the other depends on what you want to do. If you want to modify the model instance before it is saved for the first time (e.g. setting a name
or some mandatory field), you should use firstOrNew()
. If you can just use the arguments to immediately create a new model instance in the database without modifying it, you can use firstOrCreate()
.
In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.
Thanks & Regards Vengat Maran
Just a small point, I see some of the answers using innerhtml. I have toyed with a similar idea but decided not too, In the latest version react version the same process is now called dangerouslyinnerhtml, as you are giving your client a way into your OS by presenting html in the app. This could lead to various attacks as well as SQL injection attempts
Not sure which guide you are following, but if you check out this page,
https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-14-04-lts
It uses another command
ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
and also indicates what result is expected.
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).
Usage (currently you'll need to use babel to use the export file):
$ npm install -g folder-module
$ folder-module my-cool-module/
Generates a file containing:
export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc
Then you can just consume the file:
import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()
While indexOf()
works perfectly, it only returns one index.
I was looking for an elegant way to get an array of indexes for elements which satisfy some condition.
Here is how it can be done:
Swift 3:
let array = ["apple", "dog", "log"]
let indexes = array.enumerated().filter {
$0.element.contains("og")
}.map{$0.offset}
print(indexes)
Swift 2:
let array = ["apple", "dog", "log"]
let indexes = array.enumerate().filter {
$0.element.containsString("og")
}.map{$0.index}
print(indexes)
I know this is an old thread, but runtime optimization is another important part of JIT compilation that doesn't seemed to be discussed here. Basically, the JIT compiler can monitor the program as it runs to determine ways to improve execution. Then, it can make those changes on the fly - during runtime. Google JIT optimization (javaworld has a pretty good article about it.)
Lodash has a function specifically written for this: _.truncate
const truncate = _.truncate
const str = 'The quick brown fox jumps over the lazy dog'
truncate(str, {
length: 30, // maximum 30 characters
separator: /,?\.* +/ // separate by spaces, including preceding commas and periods
})
// 'The quick brown fox jumps...'
Under [branch "master"]
, try adding the following to the repo's Git config file (.git/config
):
[branch "master"]
remote = origin
merge = refs/heads/master
This tells Git 2 things:
git pull
on the master branch, with no remote and branch specified, use the default remote (origin) and merge in the changes from the remote master branch.I'm not sure why this setup would've been removed from your configuration, though. You may have to follow the suggestions that other people have posted, too, but this may work (or help at least).
If you don't want to edit the config file by hand, you can use the command-line tool instead:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
Something like this should do it :
UPDATE table1
SET table1.Price = table2.price
FROM table1 INNER JOIN table2 ON table1.id = table2.id
You can also try this:
UPDATE table1
SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
Create a one line batch file GetFileSize.bat containing
GetFileSize=%~z1
then call it
call GetFileSize myfile.txt
if (%GetFileSize) == () goto No_File
if (%GetFileSize) == (0) goto No_Data
if (%GetFileSize) GTR 1000 goto Too_Much_Data
rem Etc.
You can even create your test file on the fly to eliminate the pesky required file, note the double percent in the echo statement:
echo set GetFileSize=%%~z1 > %temp%\GetFileSize.bat
call %temp%\GetFileSize myfile.txt
if (%GetFileSize) GTR 1000 goto Too_Much_Data
rem etc
This latter solution is antispaghetti. So nice. However, more disk writes. Check use count.
I use the Database.CompatibleWithModel method (available in EF5) to test if the model and DB match before I use it. I call this method just after creating the context...
// test the context to see if the model is out of sync with the db...
if (!MyContext.Database.CompatibleWithModel(true))
{
// delete the old version of the database...
if (File.Exists(databaseFileName))
File.Delete(databaseFileName);
MyContext.Database.Initialize(true);
// re-populate database
}
Try
private boolean hasKey(JSONObject jsonObject, String key) {
return jsonObject != null && jsonObject.has(key);
}
try {
JSONObject jsonObject = new JSONObject(yourJson);
if (hasKey(jsonObject, "labelData")) {
JSONObject labelDataJson = jsonObject.getJSONObject("LabelData");
if (hasKey(labelDataJson, "video")) {
String video = labelDataJson.getString("video");
}
}
} catch (JSONException e) {
}
Summary: Instead of a.f();
it should be a->f();
In main you have defined a as a pointer to object of A, so you can access functions using the ->
operator.
An alternate, but less readable way is (*a).f()
a.f()
could have been used to access f(), if a was declared as:
A a;
I have been in this position, especially with new hardware. I suggest you write a little hex dump routine of your own. You will be able to see the data, and the addresses they are at, shown all together. It's good practice and a confidence builder.
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.
See String Formatting Operations:
%d
is the format code for an integer. %f
is the format code for a float.
%s
prints the str()
of an object (What you see when you print(object)
).
%r
prints the repr()
of an object (What you see when you print(repr(object))
.
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
You're looking for the function strcmp
, or strncmp
from string.h
.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Further reading: strcmp at cplusplus.com
Checkboxes, by design, are meant to be toggled on or off. They are not dependent on other checkboxes, so you can turn as many on and off as you wish.
Radio buttons, however, are designed to only allow one element of a group to be selected at any time.
References:
Checkboxes: MDN Link
Radio Buttons: MDN Link
You can use CircleAvatar Widget with radius:
CircleAvatar(
radius: 50.0,
backgroundImage: AssetImage("assets/img1.jpeg"),
),
Actually the way of setting environment variables is different between different Operating System.
set PUBLIC_URL=http://xxxx.com&&npm start
(Note: the lack of whitespace is intentional.)
PUBLIC_URL=http://xxxx.com npm start
cross-env
{
"scripts": {
"serve": "cross-env PUBLIC_URL=http://xxxx.com npm start"
}
}
Motti is right about the order, but there are some other things to consider:
Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.
If you have a local static as above, and foo
is called from multiple threads, you may have race conditions causing plonk
to be initialized incorrectly or even multiple times. Also, in this case plonk
may get destructed by a different thread than the one which constructed it.
Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.
If you are not into Cygwin, you can use native Windows builds. Some are here: curl Download Wizard.
Caution that using alias in the Group By (for services that support it, such as postgres) can have unintended results. For example, if you create an alias that already exists in the inner statement, the Group By will chose the inner field name.
-- Working example in postgres
select col1 as col1_1, avg(col3) as col2_1
from
(select gender as col1, maritalstatus as col2,
yearlyincome as col3 from customer) as layer_1
group by col1_1;
-- Failing example in postgres
select col2 as col1, avg(col3)
from
(select gender as col1, maritalstatus as col2,
yearlyincome as col3 from customer) as layer_1
group by col1;
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
counts7 = full(sparse(M,1,1));
Guys am facing similar issue here is my full code
Do let me know where am i going wrong. Error message: syntax error (Missing operator) in query expression 'AutoID='
This only hapens when i click on login without entering any txt in either combobox and password field.
Option Compare Database
Option Explicit
Private Sub Login_Click()
If IsNull(Me.ComboUserSelect.Value) Then
MsgBox "Please select username", vbInformation, "Login ID Required"
Me.ComboUserSelect.SetFocus
ElseIf IsNull(Me.txtpassword.Value) Then
MsgBox "please enter password", vbInformation, "Password is Required"
Me.txtpassword.SetFocus
End If
'============= Declaring the variables ==========='
Dim passwordindatabase As String
Dim typedpassword As String
Dim useraccesstype As String
passwordindatabase = DLookup("Password", "LoginDB", "AutoID=" & ComboUserSelect.Value)
typedpassword = txtpassword.Value
useraccesstype = DLookup("AccessType", "LoginDB", "AutoID=" & ComboUserSelect.Value)
If typedpassword = passwordindatabase Then
If useraccesstype = "Admin" Then
DoCmd.OpenForm ("Cam Infra")
DoCmd.Close acForm, "Login_Form", acSaveNo
Else
If useraccesstype = "user" Then
DoCmd.OpenForm ("Custom_Search_Form")
DoCmd.Close acForm, "Login_Form", acSaveNo
End If
End If
End If
End Sub
CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;
Works for DB2 V 9.7
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
Add ID attributes with same values as name attributes and then you can do this:
$('#first_name').change(function () {
$('#firstname').val($(this).val());
});
You can use generated columns from MYSQL 5.7.
Example Usage:
ALTER TABLE tbl_test
ADD COLUMN calc_val INT
GENERATED ALWAYS AS (((`column1` - 1) * 16) + `column2`) STORED;
VIRTUAL / STORED
It should put java in your path, probably in /usr/bin/java. The easiest way to find it is to open a term and type "which java".
The plus operator converts operands to int first and then does the addition. So the result is the int. You need to cast it back to short explicitly because conversions from a "longer" type to "shorter" type a made explicit, so that you don't loose data accidentally with an implicit cast.
As to why int16 is cast to int, the answer is, because this is what is defined in C# spec. And C# is this way is because it was designed to closely match to the way how CLR works, and CLR has only 32/64 bit arithmetic and not 16 bit. Other languages on top of CLR may choose to expose this differently.
i use $().one()
for solve this;
When page loaded, I send ajax to server and wait to done.
Then pass result to function.$().one()
is important .Because force typehead.js to attach to input one time.
sorry for bad writing.
(($) => {_x000D_
_x000D_
var substringMatcher = function(strs) {_x000D_
return function findMatches(q, cb) {_x000D_
var matches, substringRegex;_x000D_
// an array that will be populated with substring matches_x000D_
matches = [];_x000D_
_x000D_
// regex used to determine if a string contains the substring `q`_x000D_
substrRegex = new RegExp(q, 'i');_x000D_
_x000D_
// iterate through the pool of strings and for any string that_x000D_
// contains the substring `q`, add it to the `matches` array_x000D_
$.each(strs, function(i, str) {_x000D_
if (substrRegex.test(str)) {_x000D_
matches.push(str);_x000D_
}_x000D_
});_x000D_
cb(matches);_x000D_
};_x000D_
};_x000D_
_x000D_
var states = [];_x000D_
$.ajax({_x000D_
url: 'https://baconipsum.com/api/?type=meat-and-filler',_x000D_
type: 'get'_x000D_
}).done(function(data) {_x000D_
$('.typeahead').one().typeahead({_x000D_
hint: true,_x000D_
highlight: true,_x000D_
minLength: 1_x000D_
},_x000D_
{_x000D_
name: 'states',_x000D_
source: substringMatcher(data)_x000D_
});_x000D_
})_x000D_
_x000D_
_x000D_
})(jQuery);
_x000D_
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
.tt-hint {_x000D_
width: 396px;_x000D_
height: 30px;_x000D_
padding: 8px 12px;_x000D_
font-size: 24px;_x000D_
line-height: 30px;_x000D_
border: 2px solid #ccc;_x000D_
border-radius: 8px;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */_x000D_
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);_x000D_
}_x000D_
_x000D_
.tt-hint {_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */_x000D_
width: 422px;_x000D_
margin-top: 12px;_x000D_
padding: 8px 0;_x000D_
background-color: #fff;_x000D_
border: 1px solid #ccc;_x000D_
border: 1px solid rgba(0, 0, 0, 0.2);_x000D_
border-radius: 8px;_x000D_
box-shadow: 0 5px 10px rgba(0,0,0,.2);_x000D_
}_x000D_
_x000D_
.tt-suggestion {_x000D_
padding: 3px 20px;_x000D_
font-size: 18px;_x000D_
line-height: 24px;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.tt-suggestion:hover {_x000D_
color: #f0f0f0;_x000D_
background-color: #0097cf;_x000D_
}_x000D_
_x000D_
.tt-suggestion p {_x000D_
margin: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>_x000D_
_x000D_
<input class="typeahead" type="text" placeholder="where ?">
_x000D_
Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html
Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html
Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm
Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html
In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).
If I'm not mistaken, this should match any valid JavaScript number value, excluding constants (Infinity
, NaN
) and the sign operators +
/-
(because they are not actually part of the number as far as I concerned, they are separate operators):
I needed this for a tokenizer, where sending the number to JavaScript for evaluation wasn't an option... It's definitely not the shortest possible regular expression, but I believe it catches all the finer subtleties of JavaScript's number syntax.
/^(?:(?:(?:[1-9]\d*|\d)\.\d*|(?:[1-9]\d*|\d)?\.\d+|(?:[1-9]\d*|\d))
(?:[e]\d+)?|0[0-7]+|0x[0-9a-f]+)$/i
Valid numbers would include:
- 0
- 00
- 01
- 10
- 0e1
- 0e01
- .0
- 0.
- .0e1
- 0.e1
- 0.e00
- 0xf
- 0Xf
Invalid numbers would be
- 00e1
- 01e1
- 00.0
- 00x0
- .
- .e0
In Excel 2003 you should be able to create a formatting rule like:
=A1<>""
and then drag/copy this to other cells as needed.
If that doesn't work, try =Len(A1)>0
.
If there may be spaces in the cell which you will consider blank, then do:
=Len(Trim(A1))>0
Let me know if you can't get any of these to work. I have an old machine running XP and Office 2003, I can fire it up to troubleshoot if needed.
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
I use this function in all my js projects
You call it: hideAndResetModals("#IdModalDialog")
You define if:
function hideAndResetModals(modalID)
{
$(modalID).modal('hide');
clearValidation(modalID); //You implement it if you need it. If not, you can remote this line
$(modalID).on('hidden.bs.modal', function ()
{
$(modalID).find('form').trigger('reset');
});
}
The code that you have would work, but is executed from the global context, which means that this
refers to the global object.
<script type="text/javascript">
var foo = function(param) {
param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>
You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this
.
<script type="text/javascript">
document.getElementById('bar').onclick = function() {
this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
Change the way you requested the method from POST to GET ..
Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:
document.querySelector('#selector').toggleAttribute('data-something');
This will add the attribute in all lowercase without a value or remove it if it already exists on the element.
https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute
A solution avoiding CASE WHEN
is to use COALESCE
.
SELECT
t1.Col2 AS t1Col2,
t2.Col2 AS t2Col2,
COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)) as NULL_IF_SAME
FROM @t1 AS t1
JOIN @t2 AS t2 ON t1.ColID = t2.ColID
NULL_IF_SAME
column will give NULL
for all rows where t1.col2 = t2.col2
(including NULL
).
Though this is not more readable than CASE WHEN
expression, it is ANSI SQL.
Just for the sake of fun, if one wants to have boolean bit values of 0 and 1 (though it is not very readable, hence not recommended), one can use (which works for all datatypes):
1/ISNULL(LEN(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+2,1) as BOOL_BIT_SAME.
Now if you have one of the numeric data types and want bits, in the above LEN
function converts to string first which may be problematic,so instead this should work:
1/(CAST(ISNULL(ABS(COALESCE(NULLIF(t1.Col2, t2.Col2),NULLIF(t2.Col2, t1.Col2)))+1,0)as bit)+1) as FAST_BOOL_BIT_SAME_NUMERIC
Above will work for Integers without CAST
.
NOTE: also in SQLServer 2012, we have IIF
function.
In your case use data==null
(which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
function test(data) {_x000D_
if (data != null) {_x000D_
console.log('Data: ', data);_x000D_
}_x000D_
}_x000D_
_x000D_
test(); // the data=undefined_x000D_
test(null); // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).
Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:
mail()
is horrible enough by itself)Surprisingly, that was the easy part. The hard part is actually sending it:
And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).
I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:
<blink>
is not your friend here, nor is <font color=...>
)and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.
If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.
20090320093349
SELECT CONVERT(VARCHAR,@date,112) +
LEFT(REPLACE(CONVERT(VARCHAR,@date,114),':',''),6)
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives.
The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods.
As an example, a very simple page (let's call it foo.jsp):
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
would end up looking something like this (with a lot of the detail ignored for clarity):
public final class foo_jsp
{
// This is where the request comes in
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// JspWriter instance is gotten from a factory
// This is why you can use 'out' directly in scriptlets
JspWriter out = ...;
// Snip
out.write("<html>");
out.write("<head/>");
out.write("<body>");
out.write(someOutput()); // i.e. write the results of the method call
out.write("</body>");
out.write("</html>");
}
// Directive gets translated as separate method - note
// there is no 'out' variable declared in scope
private String someOutput()
{
return "Some output";
}
}
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
onblur
is the opposite of onfocus
.
use this:
Notification mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(songName).build();
mBuilder.contentIntent= PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
contentIntent will take care of openning activity when notification clicked
awk, sed, pipe, that's heavy
set `cat /etc/*release`; echo $1
To restart a service with changes here are the steps that I performed:
docker-compose stop -t 1 worker
docker-compose build worker
docker-compose up --no-start worker
docker-compose start worker
Simplistically malloc
and free
work like this:
malloc
provides access to a process's heap. The heap is a construct in the C core library (commonly libc) that allows objects to obtain exclusive access to some space on the process's heap.
Each allocation on the heap is called a heap cell. This typically consists of a header that hold information on the size of the cell as well as a pointer to the next heap cell. This makes a heap effectively a linked list.
When one starts a process, the heap contains a single cell that contains all the heap space assigned on startup. This cell exists on the heap's free list.
When one calls malloc
, memory is taken from the large heap cell, which is returned by malloc
. The rest is formed into a new heap cell that consists of all the rest of the memory.
When one frees memory, the heap cell is added to the end of the heap's free list. Subsequent malloc
's walk the free list looking for a cell of suitable size.
As can be expected the heap can get fragmented and the heap manager may from time to time, try to merge adjacent heap cells.
When there is no memory left on the free list for a desired allocation, malloc
calls brk
or sbrk
which are the system calls requesting more memory pages from the operating system.
Now there are a few modification to optimize heap operations.
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You should extend the scope of the component-scan e.g. <context:component-scan base-package="at.naviclean" />
since you placed the entities in package at.naviclean.domain;
This should help you to get rid the exeption: Not an managed type: class at.naviclean.domain.Kassa
For further debugging you could try to dump the application context (see javadoc) to explore which classes have been detected by the component-scan if some are still no recognized check their annotation (@Service, @Component etc.)
EDIT:
You also need to add the classes to your persistence.xml
<persistence-unit>
<class>at.naviclean.domain.Kassa</class>
...
</persistence-unit>
BrixenDK is right.
.ajaxStop()
callback executed when all ajax call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState
:
(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)
For anyone want to replace your script.
update dbo.[TABLE_NAME] set COLUMN_NAME= replace(COLUMN_NAME, 'old_value', 'new_value') where COLUMN_NAME like %CONDITION%
If you want to get the selected language of your device, this might help you:
Locale.getDefault().getDisplayLanguage();
You can use flex:
@media (min-width: 768px) {
.row-fluid {
display: flex;
align-items: flex-end;
}
}
The problem with all these is they don't address if the lines of text are long and much wider that the div overflow:auto does not ad a scroll bar that works right. Here is the perfect solution I found:
Create two divs. An inner div that is wide enough to handle the widest line of text and then a smaller outer one which acts at the holder for the inner div:
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:500px;">
<div style="width:800px;">
now really long text like this can be put in the text area and it will really <br/>
look and act more like a real text area bla bla bla <br/>
</div>
</div>
<input id="name" data-upper type="text"/>
<input id="middle" data-upper type="text"/>
<input id="sur" data-upper type="text"/>
Upper the text on dynamically created element which has attribute upper and when keyup action happens
$(document.body).on('keyup', '[data-upper]', function toUpper() {
this.value = this.value.toUpperCase();
});
Thanks all who answered this question.
It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.
public abstract class Animal{
private static Animal[] animals= null;
public static Animal[] getAnimals(){
if (animals==null){
animals = new Animal[]{
new Dog(),
new Cat(),
new Lion()
};
}
return animals;
}
}
It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.
I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.
Thanks again!
Git lets you ignore those files by assuming they are unchanged. This is done by running the
git update-index --assume-unchanged path/to/file.txt
command. Once marking a file as such, git will completely ignore any changes on that file; they will not show up when running git status or git diff, nor will they ever be committed.
(From https://help.github.com/articles/ignoring-files)
Hence, not deleting it, but ignoring changes to it forever. I think this only works locally, so co-workers can still see changes to it unless they run the same command as above. (Still need to verify this though.)
Note: This isn't answering the question directly, but is based on follow up questions in the comments of the other answers.
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
I think you are asking two things which are not necessarily the same
I want to extract every 6th element of the original
You can do this by indexing a sequence:
foo <- 1:120
foo[1:20*6]
I would like to create a vector in which each element is the i+6th element of another vector.
An easy way to do this is to supplement a logical factor with FALSEs until i+6
:
foo <- 1:120
i <- 1
foo[1:(i+6)==(i+6)]
[1] 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119
i <- 10
foo[1:(i+6)==(i+6)]
[1] 16 32 48 64 80 96 112
I updated my cocoa pods and added new supported architectures in build settings and that fixed it.
Right click on the project in solution explorer or class view window --> "View" --> "View Class Diagram"
The clearest answer. Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.
nodeName will give you the tag name in uppercase, while localName will give you the lower case.
$("yourelement")[0].localName
will give you : yourelement instead of YOURELEMENT
GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.
Previous answers were insufficient in my case, probably because I'm on Debian 8, while they were referred to some previous distribution.
On Debian 8 modify the service script normally place in /usr/lib/systemd/system/elasticsearch.service
, and add Environment=ES_HEAP_SIZE=8G
just below the other "Environment=*" lines.
Now reload the service script with systemctl daemon-reload
and restart the service. The job should be done!
The simplest way is to test whether a number is an integer is int(x) == x
. Otherwise, what David Heffernan said.
You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.
Here are some other options:
I have used xml2js
and it has worked fine for me. The rest you might have to try out for yourself.
int min = 65;
int max = 80;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
Note that nextInt(int max)
returns an int
between 0 inclusive and max exclusive. Hence the +1
.
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
The easiest way is:
F6
to build itMy Documents\Visual Studio 200x\Projects\my_project\
)bin\Release\
and copy the executable from there to wherever you want to store itWith a BufferedReader, but the function should be asynchronous:
var load = function (file, cb){
var lines = [];
new BufferedReader (file, { encoding: "utf8" })
.on ("error", function (error){
cb (error, null);
})
.on ("line", function (line){
lines.push (line);
})
.on ("end", function (){
cb (null, lines);
})
.read ();
};
load ("file", function (error, lines){
if (error) return console.log (error);
console.log (lines);
});
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
How about this?
val Delimeter = ","
val textFile = sc.textFile("data.csv").map(line => line.split(Delimeter))
In my case of using ViewPager 2 alpha 2 the below snippet works
viewPager.isUserInputEnabled = false
Ability to disable user input (setUserInputEnabled, isUserInputEnabled)
refer to this for more changes in viewpager2 1.0.0-alpha02
Also some changes were made latest version ViewPager 2 alpha 4
orientation and isUserScrollable attributes are no longer part of SavedState
refer to this for more changes in viewpager2#1.0.0-alpha04
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the GC.GetTotalMemory
method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
See Find out how much memory is being used by an object in C#? for a similar question.
If your merge was not too complicated another option would be to:
After that you are left with only the changes from the stash you dropped too early.
If you are using Google fonts I would suggest the following.
If you want the fonts to run from your localhost or server you need to download the files.
Instead of downloading the ttf packages in the download links, use the live link they provide, for example:
http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,300italic,400italic,600italic
Paste the URL in your browser and you should get a font-face declaration similar to the first answer.
Open the URLs provided, download and rename the files.
Stick the updated font-face declarations with relative paths to the woff files in your CSS, and you are done.
You can achieve what you want with the mysql console with the -s (--silent) option passed in.
It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.
mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"
EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)
Disconnecting and reconnecting to the current network worked for me.
The actual .box
file is deleted by Vagrant once the download and box installation is complete. As mentioned in other answers, whilst downloading, the .box file is stored as:
~/.vagrant.d/tmp/boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
where the file name is 'box' followed by a 40 byte hexadecimal hash. A temporary file on my system for example, is:
~/.vagrant.d/tmp/boxc74a85fe4af3197a744851517c6af4d4959db77f
As far as I can tell, this file is never saved with a *.box
extension, which explains why the searches above failed to locate it. There are two ways to retrieve the actual box file:
Download the .box file from vagrantcloud.com
vagrantcloud.com
. So https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1
becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box./providers/virtualbox.box
to the end of that URL. So https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1 becomes https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.boxconfig.vm.box_url
to the URL. ORGet the .box directly from Vagrant
This requires you to modify the ruby source to prevent Vagrant from deleting the box after successful download.
/Applications/Vagrant/embedded/gems/gems/vagrant-1.5.2/lib/vagrant/action/builtin/box_add.rb
box_add
function, there is a block that reads:
ensure # Make sure we delete the temporary file after we add it, # unless we were interrupted, in which case we keep it around # so we can resume the download later. if !@download_interrupted @logger.debug("Deleting temporary box: #{box_url}") begin box_url.delete if box_url rescue Errno::ENOENT # Not a big deal, the temp file may not actually exist end end
vagrant add box <boxname>
.~/.vagrant.d/tmp/
directory as a boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
file. mv boxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX trusty64.box
.For me, this has been useful to retrieve the .box file so it can be hosted on local, fast infrastructure as opposed to downloading from HashiCorp's Atlas box catalog or another box provider.
This really should be part of the default Vagrant functionality as it has a very definitive use case.
... and getting back to easy ... for simple scripts you can use:
import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor
later in your code
try:
assert pvi >= needs
except:
print("will fail!")
# etc.
In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
Use defaultdict
from collections import defaultdict
a = {}
a = defaultdict(lambda:0,a)
a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
a['count'] += v['count']
a['pass_count'] += v['pass_count']
For dynamic cells, rowHeight set on the UITableView always overrides the individual cells' rowHeight. Just calculate the dynamic height if the content inside the row.
public ActionResult CreatePerson (string id)
window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID",id);
public ActionResult CreatePerson (int id)
window.location.href = '@Url.Action("CreatePerson", "Person" , new {id = "ID"})'.replace("ID", parseInt(id));
Open Project properties by selecting project then go to
View>Properties Windows
and make sure Anonymous Authentication is Enabled
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5
df.withColumnRenamed('age', 'age2')