I'll add vote for Eigen: I ported a lot of code (3D geometry, linear algebra and differential equations) from different libraries to this one - improving both performance and code readability in almost all cases.
One advantage that wasn't mentioned: it's very easy to use SSE with Eigen, which significantly improves performance of 2D-3D operations (where everything can be padded to 128 bits).
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
Let:
>>> n = 1000
>>> x = np.arange(n)
>>> reps = 10000
Zero-cost allocations
A view does not take any additional memory. Thus, these declarations are instantaneous:
# New axis
x[np.newaxis, ...]
# Broadcast to specific shape
np.broadcast_to(x, (reps, n))
Forced allocation
If you want force the contents to reside in memory:
>>> %timeit np.array(np.broadcast_to(x, (reps, n)))
10.2 ms ± 62.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit np.repeat(x[np.newaxis, :], reps, axis=0)
9.88 ms ± 52.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit np.tile(x, (reps, 1))
9.97 ms ± 77.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
All three methods are roughly the same speed.
Computation
>>> a = np.arange(reps * n).reshape(reps, n)
>>> x_tiled = np.tile(x, (reps, 1))
>>> %timeit np.broadcast_to(x, (reps, n)) * a
17.1 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit x[np.newaxis, :] * a
17.5 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
>>> %timeit x_tiled * a
17.6 ms ± 240 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
All three methods are roughly the same speed.
Conclusion
If you want to replicate before a computation, consider using one of the "zero-cost allocation" methods. You won't suffer the performance penalty of "forced allocation".
You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.
You can also simply surround the chart with container (according to official doc http://www.chartjs.org/docs/latest/general/responsive.html#important-note)
<div class="chart-container">
<canvas id="myCanvas"></canvas>
</div>
CSS
.chart-container {
width: 1000px;
height:600px
}
and with options
responsive:true
maintainAspectRatio: false
Add this in your css file:
.custom_class
{
background-image: url(../img/beach.jpg);
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
and then, in your .html (or .php) file call this class like that:
<div class="custom_class">
...
</div>
From Git documentation:
-m <msg>
--message=<msg>
Use the given <msg> as the commit message. If multiple-m
options are given, their values are concatenated as separate paragraphs.
So, if you are looking for grouping multiple commit messages this should do the work:
git commit -m "commit message1" -m "commit message2"
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"
To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:
=INDEX(named_range,ROW(A1),COLUMN(A1))
Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.
var jsonStringNoQuotes = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
it will create json object. no need to parse.
jsonStringQuotes = "'" + jsonStringNoQuotes + "'";
will return '[object]'
thats why it(below) is causing error
var myData = JSON.parse(jsonStringQuotes);
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
The RFC is just trying to say that a signed integer is a normal 4-byte integer with bytes ordered in a big-endian way.
Now, you are most probably working on a little-endian machine and BitConverter.GetBytes()
will give you the byte[]
reversed. So you could try:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
Array.Reverse(intBytes);
byte[] result = intBytes;
For the code to be most portable, however, you can do it like this:
int intValue;
byte[] intBytes = BitConverter.GetBytes(intValue);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
You can use either - which means most people opt for "+" as it's more human readable.
This code works too:
$("input[reference=12345].myclass").css('border', '#000 solid 1px');
Sync Programming
Programming languages like C, C#, Java are sync programming, what so ever you write will be execute in order of your writing.
-GET DATA FROM SQL.
//Suppose fetching data take 500 msec
-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other
//task start only when fetching of sql data done (i.e some other function
//can execute only after first in process job finishes).
-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time)
msec
Async
NodeJs comes up with async feature, it's non-blocking in nature, suppose in any I/O task which is taking time (fetching, writing, reading), nodejs won't kept idle and wait for the task to be finish, it'll start executing next tasks in the queue, and whenever that time taking task completed it will notify using callback. Following example will help:
//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example
//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
//GET DATA FROM SQL
getDataFromSql(params, function(error, results){
if(error){
callback(error);
}
else{
callback(null, results);
}
})
}
//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
//some other task
console.log('Some Task 1');
console.log('Some Task 2');
}
console.log('Execution Start');
//Start With this function
timeConsumingFunction(params, function(error, results){
if(error){
console.log('Error')
}
else{
console.log('Successfull');
}
})
//As (suppose) timeConsumingFunction took 500 msec,
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start
//execute following function immediately
someOtherTask();
In Short, Output is as:
Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution
Difference is clear where sync will definitely take more than 600 (500 + 100 + processing time) msec, async saves time.
Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.
public static void main(String[] args) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://stackoverflow.com/");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
}
je : Jump if equal:
399 3fb: 64 48 33 0c 25 28 00 xor %fs:0x28,%rcx
400 402: 00 00
401 404: 74 05 je 40b <sims_get_counter+0x51>
If your Internal Server Error information doesn't show up in log files, you probably need to restart the Apache service.
I've found that Apache 2.4 (at least on Windows platform) tends to stubbornly refuse to flush log files—instead, logged data remains in memory for quite a while. It's a good idea from the performance point of view but it can be confusing when developing.
I had a similar issue using the JAXB reference implementation and JBoss AS 7.1. I was able to write an integration test that confirmed JAXB worked outside of the JBoss environment (suggesting the problem might be the class loader in JBoss).
This is the code that was giving the error (i.e. not working):
private static final JAXBContext JC;
static {
try {
JC = JAXBContext.newInstance("org.foo.bar");
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
and this is the code that worked (ValueSet is one of the classes marshaled from my XML).
private static final JAXBContext JC;
static {
try {
ClassLoader classLoader = ValueSet.class.getClassLoader();
JC = JAXBContext.newInstance("org.foo.bar", classLoader);
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
In some cases I got the Class nor any of its super class is known to this context. In other cases I also got an exception of org.foo.bar.ValueSet cannot be cast to org.foo.bar.ValueSet (similar to the issue described here: ClassCastException when casting to the same class).
That happens because you're setting the src of the ImageView
instead of the background.
Use this instead:
qImageView.setBackgroundResource(R.drawable.thumbs_down);
Here's a thread that talks about the differences between the two methods.
Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.
Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.
ssh kev@server1 './test/foo.sh'
Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).
For swift 4.0.
In your AppDelegate.swift file in didfinishedlaunchingWithOptions method, put the following code.
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let rootVC = MainViewController() // your custom viewController. You can instantiate using nib too. UIViewController(nib name, bundle)
//let rootVC = UIViewController(nibName: "MainViewController", bundle: nil) //or MainViewController()
let navController = UINavigationController(rootViewController: rootVC) // Integrate navigation controller programmatically if you want
window?.rootViewController = navController
return true
}
Hope it will work just fine.
You may want to consider placing the customer's name in the From
header and your address in the Sender
header:
From: Company A <[email protected]>
Sender: [email protected]
Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To
of Company A's address won't seem out of sorts.
From RFC 5322:
The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.
Try with:
@Scheduled(cron = "0 1 1 * * ?")
Below you can find the example patterns from the spring forum:
* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight
Cron expression is represented by six fields:
second, minute, hour, day of month, month, day(s) of week
(*)
means match any
*/X
means "every X"
?
("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.
PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support
In case above-accepted answer did not work, try below solution. You can use it for port 8080 or for any other ports.
sudo lsof -i tcp:3000
Replace 3000 with whichever port you want. Run below command to kill that process.
sudo kill -9 PID
PID is process ID you want to kill.
Below is the output of commands on mac Terminal.
r stands for a raw string, so things like \ will be automatically escaped by Python.
Normally, if you wanted your pattern to include something like a backslash you'd need to escape it with another backslash. raw strings eliminate this problem.
In your case, it does not matter much but it's a good habit to get into early otherwise something like \b will bite you in the behind if you are not careful (will be interpreted as backspace character instead of word boundary)
As per re.match vs re.search here's an example that will clarify it for you:
>>> import re
>>> testString = 'hello world'
>>> re.match('hello', testString)
<_sre.SRE_Match object at 0x015920C8>
>>> re.search('hello', testString)
<_sre.SRE_Match object at 0x02405560>
>>> re.match('world', testString)
>>> re.search('world', testString)
<_sre.SRE_Match object at 0x015920C8>
So search will find a match anywhere, match will only start at the beginning
There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:
Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.
If you're a programmer who edits a lot of text, then it's important to learn an A Serious Text Editor. Which Serious Text Editor you learn is not terribly important and is largely dependent on the types of environments you expect to be editing in.
The reason is that these editors are highly optimized to perform the kinds of tasks that you will be doing a lot. For example, consider adding the same bit of text to the end of every line. This is trivial in A Serious Text Editor, but ridiculously cumbersome otherwise.
Usually vim's killer features are considered: A) that it's available on pretty much every Unix you'll ever encounter and B) your fingers very rarely have to leave the home row, which means you'll be able to edit text very, very quickly. It's also usually very fast and lightweight even when editing huge files.
There are plenty of alternatives, however. Emacs is the most common example, of course, and it's much more than just an advanced text editor if you really dig into it. I'm personally a very happy TextMate user now after years of using vim/gvim.
The trick to switching to any of these is to force yourself to use them the way they were intended. For example, in vim, if you're manually performing every step in a multi-step process or if you're using the arrow keys or the mouse then there's probably a better way to do it. Stop what you're doing and look it up.
If you do nothing else, learn the basic navigation controls for both vim and Emacs since they pop up all over the place. For example, you can use Emacs-style controls in any text input field in Mac OS, in most Unix shells, in Eclipse, etc. You can use vim-style controls in the less(1) command, on Slashdot, on gmail, etc.
Have fun!
Markdown gets converted into HTML/XHMTL.
John Gruber created the Markdown language in 2004 in collaboration with Aaron Swartz on the syntax, with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format, and optionally convert it to structurally valid HTML (or XHTML).
HTML is completely based on using
for adding extra spaces if it doesn't externally define/use JavaScript or CSS for elements.
Markdown is a lightweight markup language with plain text formatting syntax. It is designed so that it can be converted to HTML and many other formats using a tool by the same name.
If you want to use »
only one space » either use
or just hit Spacebar
(2nd one is good choice in this case)
more than one space » use
+space (for 2 consecutive spaces)
eg. If you want to add 10 spaces contiguously then you should use
space
space
space
space
space
instead of using 10
one after one as the below one
For more details check
try this:
a = new Array();
a.push(10);
a.push(60);
a.push(20);
a.push(30);
a.push(100);
a.sort(Test)
document.write(a);
function Test(a,b)
{
return a > b ? true : false;
}
guppy3 is quite simple to use. At some point in your code, you have to write the following:
from guppy import hpy
h = hpy()
print(h.heap())
This gives you some output like this:
Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 35144 27 2140412 26 2140412 26 str
1 38397 29 1309020 16 3449432 42 tuple
2 530 0 739856 9 4189288 50 dict (no owner)
You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.
There is a graphical browser as well, written in Tk.
For Python 2.x, use Heapy.
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
The best way doing this - especially if you're adding more than one condition - is:
$values = array(...); // array of your values
$qb->andWhere('where', $qb->expr()->in('r.winner', $values));
If your array of values contains strings, you can't use the setParameter method with an imploded string, because your quotes will be escaped!
It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the onclick
call a call to a function library (a function calling other functions).
Like:
elm.onclick = myFunctionList;
function myFunctionList(){
myFunc1();
myFunc2();
}
This means we never have to change the onclick
call just alter the function myFunctionList()
to do whatever we want, but this leaves us without control of bubbling/catching phases so should be avoided for newer browsers.
NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];
timeInterval
is the difference between start and now, in seconds, with sub-millisecond precision.
You coud try java.net.URLClassloader with the url of the folder/jar where your updated class resides and use it instead of the default classloader when creating a new thread.
The easiest way i found to solve that problem was to select a label and then send:
label.sendKeys(Keys.PAGE_DOWN);
Hope it works!
I used to do it with the dennis.sheppard solution:
viewToUse.setImageResource(0);
it works but it is not documented so it isn't really clear if it effects something else in the view (you can check the ImageView code if you like, i didn't).
I think the best solution is:
viewToUse.setImageResource(android.R.color.transparent);
I like this solution the most cause there isn't anything tricky in reverting the state and it's also clear what it is doing.
I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.
I faced this same error while because I was using parameters in my php file path like this:
/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234
But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:
/usr/bin/php -q /home/**/public_html/cron/job.php id=1234
Just replace the "?"
with a space " "
.
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
Using ES6 syntax in React does not bind this
to user-defined functions however it will bind this
to the component lifecycle methods.
So the function that you declared will not have the same context as the class and trying to access this
will not give you what you are expecting.
For getting the context of class you have to bind the context of class to the function or use arrow functions.
Method 1 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
Update: You can also create the properties on class without constructor:
class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
try
<img src="https://cdn.glitch.com/0e4d1ff3-5897-47c5-9711-d026c01539b8%2Fbddfd6e4434f42662b009295c9bab86e.gif?v=1573157191712" alt="this slowpoke moves" width="250" alt="404 image"/>
_x000D_
and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.
The best and the easiest way, for me was this..
->Simply create a thread with Handler containing sleep().
private ImageView myImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shape_count); myImageView= (ImageView)findViewById(R.id.shape1);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fadein);
myImageView.startAnimation(myFadeInAnimation);
new Thread(new Runnable() {
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Log.w("hendler", "recived");
Animation myFadeOutAnimation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.fadeout);
myImageView.startAnimation(myFadeOutAnimation);
myImageView.setVisibility(View.INVISIBLE);
}
};
@Override
public void run() {
try{
Thread.sleep(2000); // your fadein duration
}catch (Exception e){
}
handler.sendEmptyMessage(1);
}
}).start();
}
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement
public class RecipeComparator implements Comparator<Recipe> {
public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;
private int compare_mode = COMPARE_BY_NAME;
public RecipeComparator() {
}
public RecipeComparator(int compare_mode) {
this.compare_mode = compare_mode;
}
@Override
public int compare(Recipe o1, Recipe o2) {
switch (compare_mode) {
case COMPARE_BY_ID:
return o1.getId().compareTo(o2.getId());
default:
return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
}
}
}
Actually for numbers you need to handle them separately check below
public static void main(String[] args) {
String string1 = "1";
String string2 = "2";
String string11 = "11";
System.out.println(string1.compareTo(string2));
System.out.println(string2.compareTo(string11));// expected -1 returns 1
// to compare numbers you actually need to do something like this
int number2 = Integer.valueOf(string1);
int number11 = Integer.valueOf(string11);
int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
System.out.println(compareTo);// prints -1
}
Strongly recommend this article.
I just plugged it in and it worked
http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html
You don't need to use array_push() function, you can assign new value with new key directly to the array like..
$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);
Output:
Array(
[color1] => red
[color2] => blue
[color3] => green
)
I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:
conda create -n Python27 python=2.7
This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate
(windows) or source deactivate
(linux, osx) in the command line. To activate in the future type activate Python27
(windows) or source activate Python27
(linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.
Update
As of conda
version 4.6 you can now use conda activate
and conda deactivate
. The use of source
is now deprecated and will eventually be removed.
Also, do you have another example (beside the Wikipedia one) where
nullptr
is superior to good old 0?
Yes. It's also a (simplified) real-world example that occurred in our production code. It only stood out because gcc was able to issue a warning when crosscompiling to a platform with different register width (still not sure exactly why only when crosscompiling from x86_64 to x86, warns warning: converting to non-pointer type 'int' from NULL
):
Consider this code (C++03):
#include <iostream>
struct B {};
struct A
{
operator B*() {return 0;}
operator bool() {return true;}
};
int main()
{
A a;
B* pb = 0;
typedef void* null_ptr_t;
null_ptr_t null = 0;
std::cout << "(a == pb): " << (a == pb) << std::endl;
std::cout << "(a == 0): " << (a == 0) << std::endl; // no warning
std::cout << "(a == NULL): " << (a == NULL) << std::endl; // warns sometimes
std::cout << "(a == null): " << (a == null) << std::endl;
}
It yields this output:
(a == pb): 1
(a == 0): 0
(a == NULL): 0
(a == null): 1
Expanding on @Kiran's answer, which I agree is more succinct and Pythonic, this adds codecs to support the reading and writing of UTF-8:
import codecs
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG
support for sorl thumbnails.
from PIL import Image
png = Image.open(object.logo.path)
png.load() # required for png.split()
background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel
background.save('foo.jpg', 'JPEG', quality=80)
Result @80%
Result @ 50%
I've been using Typescript in my current angular project for about a year and a half and while there are a few issues with definitions every now and then the DefinitelyTyped project does an amazing job at keeping up with the latest versions of most popular libraries.
Having said that there is a definite learning curve when transitioning from vanilla JavaScript to TS and you should take into account the ability of you and your team to make that transition. Also if you are going to be using angular 1.x most of the examples you will find online will require you to translate them from JS to TS and overall there are not a lot of resources on using TS and angular 1.x together right now.
If you plan on using angular 2 there are a lot of examples using TS and I think the team will continue to provide most of the documentation in TS, but you certainly don't have to use TS to use angular 2.
ES6 does have some nice features and I personally plan on getting more familiar with it but I would not consider it a production-ready language at this point. Mainly due to a lack of support by current browsers. Of course, you can write your code in ES6 and use a transpiler to get it to ES5, which seems to be the popular thing to do right now.
Overall I think the answer would come down to what you and your team are comfortable learning. I personally think both TS and ES6 will have good support and long futures, I prefer TS though because you tend to get language features quicker and right now the tooling support (in my opinion) is a little better.
If you changed height of tableView's headerView, just reset headerView's frame, then, reset headerView of tableView:
self.headerView.frame = newFrame;
self.tableView.tableHeaderView = self.headerView;
In my case, it was the problem when I setup my time manually two month earlier on my iPhone. But when I changed to set time automatically, it worked fine.
Setting
-> General
-> Date & Time
-> set time automatically
If it does not work then set time automatically of both mac & iPhone, it may work fine.
use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them
Because the PermGen space was removed. Memory management has changed a bit.
but I need results where r.text is not duplicated
Sounds as if you want this:
table1.GroupBy(x => x.Text)
.Where(g => g.Count() == 1)
.Select(g => g.First());
This will select rows where the Text
is unique.
Although its too late to answer this question, but still for those guys who came here to see the solution of same problem just like me and didn't get a satisfactory answer on this page, The reason is that you don't have your file in the form of .rb extension. You most probably have it in simple text mode. Let me elaborate. Binding up the whole solution on the page, here you go (assuming you filename is abc.rb or at least you created abc):
Type in terminal window:
cd ~/to/the/program/location
ruby abc.rb
and you are done
If the following error occurs
ruby: No such file or directory -- abc.rb (LoadError)
Then go to the directory in which you have the abc file, rename it as abc.rb Close gedit and reopen the file abc.rb. Apply the same set of commands and success!
int retries = 3;
while (true)
{
try
{
//Do Somthing
break;
}
catch (Exception ex)
{
if (--retries == 0)
return Request.BadRequest(ApiUtil.GenerateRequestResponse(false, "3 Times tried it failed do to : " + ex.Message, new JObject()));
else
System.Threading.Thread.Sleep(100);
}
Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:
No the most glamorous of options but could also work if the receiving app has can accept code-formatting.
Late to the party, but this may help anyone looking for a quick solution:
you can use bin(ord('b')).replace('b', '')
bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.
Cheers
The DateFormat
class has a parse
method.
See DateFormat for more information.
Simplest solution: Use Unicode Characters
No expression
or other packages needed.
Not sure if this is a newer feature for ggplot, but it works.
It also makes it easy to mix Greek and regular text (like adding '*' to the ticks)
Just use unicode characters within the text string. seems to work well for all options I can think of. Edit: previously it did not work in facet labels. This has apparently been fixed at some point.
library(ggplot2)
ggplot(mtcars,
aes(mpg, disp, color=factor(gear))) +
geom_point() +
labs(title="Title (\u03b1 \u03a9)", # works fine
x= "\u03b1 \u03a9 x-axis title", # works fine
y= "\u03b1 \u03a9 y-axis title", # works fine
color="\u03b1 \u03a9 Groups:") + # works fine
scale_x_continuous(breaks = seq(10, 35, 5),
labels = paste0(seq(10, 35, 5), "\u03a9*")) + # works fine; to label the ticks
ggrepel::geom_text_repel(aes(label = paste(rownames(mtcars), "\u03a9*")), size =3) + # works fine
facet_grid(~paste0(gear, " Gears \u03a9"))
Created on 2019-08-28 by the reprex package (v0.3.0)
You can also install Git Credential Manager for Windows to save Git passwords in Windows credentials manager instead of _netrc
. This is a more secure way to store passwords.
It is not good practice to save the value that is returned from JSON.stringify(userData)
to a cookie; it can lead to a bug in some browsers.
Before using it, you should convert it to base64 (using btoa
), and when reading it, convert from base64 (using atob
).
val = JSON.stringify(userData)
val = btoa(val)
write_cookie(val)
Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
I would not recommend using --no-cache
in your case.
You are running a couple of installations from step 3 to 9 (I would, by the way, prefer using a one liner) and if you don't want the overhead of re-running these steps each time you are building your image you can modify your Dockerfile
with a temporary step prior to your wget
instruction.
I use to do something like RUN ls .
and change it to RUN ls ./
then RUN ls ./.
and so on for each modification done on the tarball retrieved by wget
You can of course do something like RUN echo 'test1' > test && rm test
increasing the number in 'test1
for each iteration.
It looks dirty, but as far as I know it's the most efficient way to continue benefiting from the cache system of Docker, which saves time when you have many layers...
This will remove it - short and clean:
.btn {
outline: none !important;
}
A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys()
on it when you want to actual array. That way you don't need to use array_search
to find your element.
The solution with copying 32-bit libs over to 64-bit did not work for me. What worked was unchecking Target Platform Prefer 32-bit check mark in project properties.
The nproc command shows the number of processing units available:
$ nproc
Sample outputs: 4
lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu
Sample outputs:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7
Try this code for to trim
a String
Public Function AllTrim(ByVal GeVar As String) As String
Dim i As Integer
Dim e As Integer
Dim NewStr As String = ""
e = Len(GeVar)
For i = 1 To e
If Mid(GeVar, i, 1) <> " " Then
NewStr = NewStr + Mid(GeVar, i, 1)
End If
Next i
AllTrim = NewStr
' MsgBox("alltrim = " & NewStr)
End Function
$array = array('Item 1');
array_push($array,'Item 2');
or
$array[] = 'Item 2';
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
Sould look like:
<td colspan ='4'><img src="\Pics\H.gif" alt="" border='3' height='100' width='100' /></td>
.
<td>
need to be closed with </td>
<img />
is (in most case) an empty tag. The closing tag is replacede by />
instead... like for br's
<br/>
Your html structure is plain worng (sorry), but this will probably turn into a really bad cross-brwoser compatibility. Also, Encapsulate the value of your attributes with quotes and avoid using upercase in tags.
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
Assuming you have a field for DateTime
, you could have your query look like this:
SELECT *
FROM TABLE
WHERE DateTime > (GetDate() + 90)
I've found a workaround. At first it seemed it would take up more time, but it actually makes everything work smoother and faster due to less swapping and more memory available. This is not a scientific approach and it needs some testing before it works.
In the code, make Excel save the workbook every now and then. I had to loop through a sheet with 360 000 lines and it choked badly. After every 10 000 I made the code save the workbook and now it works like a charm even on a 32-bit Excel.
If you start Task Manager at the same time you can see the memory utilization go down drastically after each save.
Just want to add my take here, as the other answers do provide reasonable explanations, but not ones that fully satisfy me.
Optional parameters are syntactic sugar for compile-time injection of the default value at the call site. This doesn't have anything to do with interfaces/implementations, and it can be seen as purely a side-effect of methods with optional parameters. So, when you call the method,
public void TestMethod(bool value = false) { /*...*/ }
like SomeClass.TestMethod()
, it is actually SomeClass.TestMethod(false)
. If you call this method on an interface, from static type-checking, the method signature has the optional parameter. If you call this method on a deriving class's instance that doesn't have the optional parameter, from static type-checking, the method signature does not have the optional parameter, and must be called with full arguments.
Due to how optional parameters are implemented, this is the natural design result.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
There are very few cases where you want to use except:
. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit
and KeyboardInterupt
, which can make your program annoying to use..
At the very simplest, you would catch urllib2.URLError
:
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
raise MyException("There was an error: %r" % e)
The following should capture the specific error raised when the connection times out:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError, e:
# For Python 2.6
if isinstance(e.reason, socket.timeout):
raise MyException("There was an error: %r" % e)
else:
# reraise the original error
raise
except socket.timeout, e:
# For Python 2.7
raise MyException("There was an error: %r" % e)
You can simply ignore all of them by adding .idea/*
to the .gitignore
file.
You need to read the file in chunks of suitable size:
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
def generate_file_md5(rootdir, filename, blocksize=2**20):
m = hashlib.md5()
with open( os.path.join(rootdir, filename) , "rb" ) as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation
I cross-checked the results using the 'jacksum' tool.
jacksum -a md5 <filename>
Previous answer can be shortened and be more readable.
$('#commentForm').submit(function () {
$(this).append($.map(params, function (param) {
return $('<input>', {
type: 'hidden',
name: param.name,
value: param.value
})
}))
});
Make sure that your Spring form mentions the modelAttribute="<Model Name"
.
Example:
@Controller
@RequestMapping("/greeting.html")
public class GreetingController {
@ModelAttribute("greeting")
public Greeting getGreetingObject() {
return new Greeting();
}
/**
* GET
*
*
*/
@RequestMapping(method = RequestMethod.GET)
public String handleRequest() {
return "greeting";
}
/**
* POST
*
*
*/
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(@ModelAttribute("greeting") Greeting greeting, BindingResult result){
ModelAndView mv = new ModelAndView();
mv.addObject("greeting", greeting);
return mv;
}
}
In your JSP :
<form:form modelAttribute="greeting" method="POST" action="greeting.html">
%TIME% is in the format H:MM:SS,CS after midnight and hence conversion to centiseconds >doesn't work. Seeing Patrick Cuff's post with 6:46am it seems that it is not only me.
But with this lines bevor you should will fix that problem easy:
if " "=="%StartZeit:~0,1%" set StartZeit=0%StartZeit:~-10%
if " "=="%EndZeit:~0,1%" set EndZeit=0%EndZeit:~-10%
Thanks for your nice inspiration! I like to use it in my mplayer, ffmpeg, sox Scripts to pimp my mediafiles for old PocketPlayers just for fun.
As I commented, there are a few places on this site that write the contents of a worksheet out to a CSV. This one and this one to point out just two.
Below is my version
UsedRange
- because you want to get all of the contents in the worksheetThe code ...
Sub makeCSV(theSheet As Worksheet)
Dim iFile As Long, myPath As String
Dim myArr() As Variant, outStr As String
Dim iLoop As Long, jLoop As Long
myPath = Application.ActiveWorkbook.Path
iFile = FreeFile
Open myPath & "\myCSV.csv" For Output Lock Write As #iFile
myArr = theSheet.UsedRange
For iLoop = LBound(myArr, 1) To UBound(myArr, 1)
outStr = ""
For jLoop = LBound(myArr, 2) To UBound(myArr, 2) - 1
If InStr(1, myArr(iLoop, jLoop), ",") Then
outStr = outStr & """" & myArr(iLoop, jLoop) & """" & ","
Else
outStr = outStr & myArr(iLoop, jLoop) & ","
End If
Next jLoop
If InStr(1, myArr(iLoop, jLoop), ",") Then
outStr = outStr & """" & myArr(iLoop, UBound(myArr, 2)) & """"
Else
outStr = outStr & myArr(iLoop, UBound(myArr, 2))
End If
Print #iFile, outStr
Next iLoop
Close iFile
Erase myArr
End Sub
This solution uses a RandomAccessFile
to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String
you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void remove(String text, File file) throws IOException {
try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
long remainderStartPos = scanForString + text.getBytes().length;
rafile.seek(remainderStartPos);
int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
byte[] bytes = new byte[remainderSize];
rafile.read(bytes);
rafile.seek(scanForString);
rafile.write(bytes);
rafile.setLength(rafile.length() - (text.length()));
}
}
File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call: remove("ABC", new File("Drive:/Path/File.extension"));
Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ
This solution could easily be modified to remove with a certain, specifiable cacheSize
, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize
. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180
and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.
This evening I ran into a situation in which I thought I was going to have to check against the str
type, but it turned out I did not.
My approach to solving the problem will probably work in many situations, so I offer it below in case others reading this question are interested (Python 3 only).
# NOTE: fields is an object that COULD be any number of things, including:
# - a single string-like object
# - a string-like object that needs to be converted to a sequence of
# string-like objects at some separator, sep
# - a sequence of string-like objects
def getfields(*fields, sep=' ', validator=lambda f: True):
'''Take a field sequence definition and yield from a validated
field sequence. Accepts a string, a string with separators,
or a sequence of strings'''
if fields:
try:
# single unpack in the case of a single argument
fieldseq, = fields
try:
# convert to string sequence if string
fieldseq = fieldseq.split(sep)
except AttributeError:
# not a string; assume other iterable
pass
except ValueError:
# not a single argument and not a string
fieldseq = fields
invalid_fields = [field for field in fieldseq if not validator(field)]
if invalid_fields:
raise ValueError('One or more field names is invalid:\n'
'{!r}'.format(invalid_fields))
else:
raise ValueError('No fields were provided')
try:
yield from fieldseq
except TypeError as e:
raise ValueError('Single field argument must be a string'
'or an interable') from e
Some tests:
from . import getfields
def test_getfields_novalidation():
result = ['a', 'b']
assert list(getfields('a b')) == result
assert list(getfields('a,b', sep=',')) == result
assert list(getfields('a', 'b')) == result
assert list(getfields(['a', 'b'])) == result
You make one div somewhere on the page and put this code:
<div id="winSize"></div>
<script>
var WindowsSize=function(){
var h=$(window).height(),
w=$(window).width();
$("#winSize").html("<p>Width: "+w+"<br>Height: "+h+"</p>");
};
$(document).ready(WindowsSize);
$(window).resize(WindowsSize);
</script>
Here is a snippet:
var WindowsSize=function(){_x000D_
var h=$(window).height(),_x000D_
w=$(window).width();_x000D_
$("#winSize").html("<p>Width: "+w+"<br>Height:"+h+"</p>");_x000D_
};_x000D_
$(document).ready(WindowsSize); _x000D_
$(window).resize(WindowsSize);
_x000D_
#winSize{_x000D_
position:fixed;_x000D_
bottom:1%;_x000D_
right:1%;_x000D_
border:rgba(0,0,0,0.8) 3px solid;_x000D_
background:rgba(0,0,0,0.6);_x000D_
padding:5px 10px;_x000D_
color:#fff;_x000D_
text-shadow:#000 1px 1px 1px,#000 -1px 1px 1px;_x000D_
z-index:9999_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="winSize"></div>
_x000D_
Of course, adapt it to fit your needs! ;)
Solved this with recursion:
def get(d,l):
if len(l)==1: return d[l[0]]
return get(d[l[0]],l[1:])
Using your example:
dataDict = {
"a":{
"r": 1,
"s": 2,
"t": 3
},
"b":{
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
maplist1 = ["a", "r"]
maplist2 = ["b", "v", "y"]
print(get(dataDict, maplist1)) # 1
print(get(dataDict, maplist2)) # 2
Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.
I spent a lot of time to understand all the steps. So lets describe step by step:
ssh-keygen -t rsa
. Give it an alternative like proj1.id_rsa
and hit with no doubt because you don't need a passphrase.Add new section in .ssh/config
:
Host proj1.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/proj1.id_rsa
Take into account the first section and note that proj1.github.com
we will back to the section later.
ssh-add ~/.ssh/proj1.id_rsa
proj1.github.com
(exactly the host from the config file).
git clone [email protected]
.Don't mess up with hosts
I had a similar problem.
I wanted to set the state of where the 2nd level key was stored in a variable.
e.g. this.setState({permissions[perm.code]: e.target.checked})
However this isn't valid syntax.
I used the following code to achieve this:
this.setState({
permissions: {
...this.state.permissions,
[perm.code]: e.target.checked
}
});
on android folder cmd run
chmod +x gradlew
and run
./gradlew clean
and root project run
react-native run-android
If you really want to, you can check it manually by using null
:
public MyParameterizedFunction(String param1, int param2, boolean param3)
{
if(param3 == null) {
param3 = false;
}
}
However i heavily recommend using something else, like overloading or a static factory. Maybe you can get away with this, but it can lead to unexcspected behavior. For example you could have an error in your code, so that your boolean never gets a value. In this case you would not get a NullPointerException
. Instead it will look like it was set to false, which can be very confusing to debug.
You can copy all contents of myhtml
to String
as follows:
Scanner myScanner = null;
try
{
myScanner = new Scanner(myhtml);
String contents = myScanner.useDelimiter("\\Z").next();
}
finally
{
if(myScanner != null)
{
myScanner.close();
}
}
Ofcourse, you can add a catch
block to handle exceptions properly.
Building on this question, I use the following code to indent my messages:
String prefix1 = "short text:";
String prefix2 = "looooooooooooooong text:";
String msg = "indented";
/*
* The second string begins after 40 characters. The dash means that the
* first string is left-justified.
*/
String format = "%-40s%s%n";
System.out.printf(format, prefix1, msg);
System.out.printf(format, prefix2, msg);
This is the output:
short text: indented looooooooooooooong text: indented
This is documented in section "Flag characters" in man 3 printf
.
how about using the CSS :first-child pseudo-class:
.MyClass td:first-child { border: solid 1px red; }
There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,
select length(to_json('Some "text"'::TEXT) ::TEXT);
is 15,
The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>
.
select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );
will return 11.
Try this code
var x = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
let index = x.findIndex(x => x.prop1 === 'zxvz')
You're looking in the wrong place. You should look up Windows Communication Framework.
WCF is used both on the client and on the server.
Another answer I would have for this would be to take a pragmatic approach and keep your REST API contract simple. In my case I had refactored my REST API to make things more testable without resorting to JavaScript or XHR, just simple HTML forms and links.
So to be more specific on your question above, I'd just use return code 200
and have the returned message contain a JSON message that your application can understand. Depending on your needs it may require the ID of the object that is newly created so the web application can get the data in another call.
One note, in my refactored API contract, POST responses should not contain any cacheable data as POSTs are not really cachable, so limit it to IDs that can be requested and cached using a GET request.
None of the above methods worked for me so i'm posting the way i did
DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN
DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID int;
SELECT BrandID = BrandID FROM tblBrand
WHERE BrandName = BrandName;
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (CategoryID, BrandID);
END$$
First install pygments
then
echo '<some json>' | python -m json.tool | pygmentize -l json
If you are looking for readability, I believe that this is that code:
print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
'kg': var1,
'lb': var2,
'gal': var3,
'l': var4,
}
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
You can also try this:
<a href="" onclick="if (confirm('Delete selected item?')){return true;}else{event.stopPropagation(); event.preventDefault();};" title="Link Title">
Link Text
</a>
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
I'd argue that most of the solutions shown here suffer from being over-engineerd. Probably the most simple way to check if a value is of type [object Object]
is to check against the .constructor
property of it:
function isObject (a) { return a != null && a.constructor === Object; }
or even shorter with arrow-functions:
const isObject = a => a != null && a.constructor === Object;
The a != null
part is necessary because one might pass in null
or undefined
and you cannot extract a constructor property from either of these.
It works with any object created via:
Object
constructor{}
Another neat feature of it, is it's ability to give correct reports for custom classes which make use of Symbol.toStringTag
. For example:
class MimicObject {
get [Symbol.toStringTag]() {
return 'Object';
}
}
The problem here is that when calling Object.prototype.toString
on an instance of it, the false report [object Object]
will be returned:
let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]
But checking against the constructor gives a correct result:
let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false
Since Internet Explorer 11 (IE11+) came out and is not using the tag name of MSIE
anymore I came up with a variance of an older detection function:
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
// if IE11+
if (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(ua) !== null) {
var M= ["Internet Explorer"];
if(M && (tem= ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/))!= null) M[2]= tem[1];
M= M? [M[0], M[2]]: [N, navigator.appVersion,'-?'];
return M;
}
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
})();
Invoke-Expression
should work perfectly, just make sure you are using it correctly. For your case it should look like this:
Invoke-Expression "$scriptPath $argumentList"
I tested this approach with Get-Service and seems to be working as expected.
A bit different from (but mostly like) @lesmana's answer
stty -echo
read password
stty echo
simply: hide echo do your stuff show echo
git config --list
to check current username & email in your local repo.git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
.git/config
manually instead.When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
Here is how it look on windows
Troubleshooting? Learn more
docker ps -a | grep training/webapp | cut -d ' ' -f 1 | xargs docker rm
- ps -a: list all containers
- grep training/webapp : filter out everything but the containers started from the training/webapp image
- cut -d ' ' -f 1: list only the container ids (first field when delimited by space)
- xargs docker rm : send the container id list output to the docker rm command to remove the container
I have a similar problem. I try to run an example in tensorflow/models/objective_detection and met the same message. Try to change Python3 to Python2
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
It seems like Jetbrains made some renaming and moved settings around so the accepted answer is no longer 100% valid anymore.
Intellij 2018.3:
hard wrap
- idea will automatically wrap the line as you type, this is not what the OP was asking for
visual guide
- just a vertical line indicating a characters limit, default is 120
If you just want to change the visual guide
from the default 120
to lets say 80
in my example:
Also you can change the color or the visual guide
by clicking on the Foreground
:
Lastly, you can also set the visual guide
for all file types (unless specified) here:
There is way without requiring user to do changes on his PC. Runtime.getRuntime.exec() allows us to start cmd.exe and execute commands inside of it. So, it's possible for java program to run itself in command prompt when user clicks .jar file.
public static void main(String[] args) throws IOException {
if(args.length == 0) {
Process p = Runtime.getRuntime().exec("cmd.exe /c start java -jar " + (new File(NameOfClass.class.getProtectionDomain().getCodeSource().getLocation().getPath())).getAbsolutePath() + " cmd");
} else {
//code to be executed
}
}
This would be a clean, readable and reusable solution using grep
and echo
to add a line to a file only if it doesn't already exist:
LINE='include "/configs/projectname.conf"'
FILE='lighttpd.conf'
grep -qF -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
If you need to match the whole line use grep -xqF
Add -s
to ignore errors when the file does not exist, creating a new file with just that line.
In Jenkins 2.138.3 there are two different types of pipelines.
Declarative and Scripted pipelines.
"Declarative pipelines is a new extension of the pipeline DSL (it is basically a pipeline script with only one step, a pipeline step with arguments (called directives), these directives should follow a specific syntax. The point of this new format is that it is more strict and therefore should be easier for those new to pipelines, allow for graphical editing and much more. scripted pipelines is the fallback for advanced requirements."
jenkins pipeline: agent vs node?
Here is an example of using environment and global variables in a Declarative Pipeline. From what I can tell enviroment are static after they are set.
def browser = 'Unknown'
pipeline {
agent any
environment {
//Use Pipeline Utility Steps plugin to read information from pom.xml into env variables
IMAGE = readMavenPom().getArtifactId()
VERSION = readMavenPom().getVersion()
}
stages {
stage('Example') {
steps {
script {
browser = sh(returnStdout: true, script: 'echo Chrome')
}
}
}
stage('SNAPSHOT') {
when {
expression {
return !env.JOB_NAME.equals("PROD") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "SNAPSHOT"
echo "${browser}"
}
}
stage('RELEASE') {
when {
expression {
return !env.JOB_NAME.equals("TEST") && !env.VERSION.contains("RELEASE")
}
}
steps {
echo "RELEASE"
echo "${browser}"
}
}
}//end of stages
}//end of pipeline
There is another solution you can try by using only the css here is the answer i posted in another post: jQuery Accordion change font awesome icon class on click
I faced the same problem due to illegal spaces in my entire code.
I fixed it by selecting one of these spaces and use find and replace
to replace all matches with regular spaces.
Try deleting your ASO files.
ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.
This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.
I solved this error by installing the browser driver:
Reference: search YouTube.com for the error
Platform: macOS High Sierra 10.13.3
There are various ways to do this and various redirects, I've listed them below:
301 (Permanent) Redirect: Point an entire site to a different URL on a permanent basis. This is the most common type of redirect and is useful in most situations. In this example, we are redirecting to the "example.com" domain:
# This allows you to redirect your entire website to any other domain
Redirect 301 / http://example.com/
302 (Temporary) Redirect: Point an entire site to a different temporary URL. This is useful for SEO purposes when you have a temporary landing page and plan to switch back to your main landing page at a later date:
# This allows you to redirect your entire website to any other domain
Redirect 302 / http://example.com/
Redirect index.html to a specific subfolder:
# This allows you to redirect index.html to a specific subfolder
Redirect /index.html http://example.com/newdirectory/
Redirect an old file to a new file path:
# Redirect old file path to new file path
Redirect /olddirectory/oldfile.html http://example.com/newdirectory/newfile.html
Redirect to a specific index page:
# Provide Specific Index Page (Set the default handler)
DirectoryIndex index.html
react-router v6
Update for 2021
The upcoming v6 will have nested Route
components that Just Work™
See example code in this blog post
The question is about v4/v5, but when v6 ships the correct answer will be just use that if you can.
react-router v4 & v5
It's true that in order to nest Routes you need to place them in the child component of the Route.
However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render
prop of the Route you want to nest under.
<BrowserRouter>
<Route path="/" component={Frontpage} exact />
<Route path="/home" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route
path="/admin"
render={({ match: { url } }) => (
<>
<Route path={`${url}/`} component={Backend} exact />
<Route path={`${url}/home`} component={Dashboard} />
<Route path={`${url}/users`} component={UserPage} />
</>
)}
/>
</BrowserRouter>
If you're interested in why the render
prop should be used, and not the component
prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.
Note that the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div>
instead.
git init
git add .
git commit -m "Initial commit"
After this, make a new GitHub repository and follow on-screen instructions.
On my machine mysqld service stopped that's why it was giving me the same problem.
1:- Go to terminal and type
sudo service mysqld restart
This will restart the mysqld service and create a new sock file on the required location.
I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.
Here you can add to sDom
element to your code, top search bar is hidden.
$(document).ready(function() {
$('#example').dataTable( {
"sDom": '<"top">rt<"bottom"flp><"clear">'
} );
} );
Indeed, it is O(n^2). See also a very similar example with the same runtime here.
If this still isn't working try unchecking "Enable Protected Mode" in IE.
Add your site to Local Intranet in
Tools -> Internet Option -> Security Tab
Then uncheck "Enable Protected Mode"
Restart IE
have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?
<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
<span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>
Use this <div [ngStyle]="{'background-image':'url('+imageUrl+')'}"></div>
this solved the problem for me.
Ok, finally got it.
Change this line in %windir%\System32\inetsrv\Config\ApplicationHost.config
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
To
<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler,runtimeVersionv2.0" />
If this is not enough
Add this following line to the Web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
Dim
have had different meanings attributed to it.
I've found references about Dim
meaning "Declare In Memory", the more relevant reference is a document on Dim Statement published Oracle as part of the Siebel VB Language Reference. Of course, you may argue that if you do not declare the variables in memory where do you do it? Maybe "Declare in Module" is a good alternative considering how Dim
is used.
In my opinion, "Declare In Memory" is actually a mnemonic, created to make easier to learn how to use Dim
. I see "Declare in Memory" as a better meaning as it describes what it does in current versions of the language, but it is not the proper meaning.
In fact, at the origins of Basic Dim
was only used to declare arrays. For regular variables no keyword was used, instead their type was inferred from their name. For instance, if the name of the variable ends with $
then it is a string (this is something that you could see even in method names up to VB6, for example Mid$
). And so, you used Dim
only to give dimension to the arrays (notice that ReDim
resizes arrays).
Really, Does It Matter? I mean, it is a keyword it has its meaning inside an artificial language. It doesn't have to be a word in English or any other natural language. So it could just mean whatever you want, all that matters is that it works.
Anyhow, that is not completely true. As BASIC is part of our culture, and understanding why it came to be as it is - I hope - will help improve our vision of the world.
I sit in from of my computer with a desire to help preserve this little piece of our culture that seems lost, replaced by our guessing of what it was. And so, I have dug MSDN both current and the old CDs from the 1998 version. I have also searched the documention for the old QBasic [Had to use DOSBox] and managed to get some Darthmouth manual, all to find how they talk about Dim
. For my disappointment, they don't say what does Dim
stand for, and only say how it is used.
But before my hope was dim, I managed to find this BBC Microcomputer System Used Guide (that claims to be from 1984, and I don't want to doubt it). The BBC Microcomputer used a variant of BASIC called BBC BASIC and it is described in the document. Even though, it doesn't say what does Dim
stand for, it says (on page 104):
... you can dimension N$ to have as many entries as you want. For example, DIM N$(1000) would create a string array with space for 1000 different names.
As I said, it doesn't say that Dim
stands for dimension, but serves as proof to show that associating Dim
with Dimension
was a common thing at the time of writing that document.
Now, I got a rewarding surprise later on (at page 208), the title for the section that describes the DIM keyword (note: that is not listed in the contents) says:
DIM dimension of an array
So, I didn't get the quote "Dim stands for..." but I guess it is clear that any decent human being that is able to read those document will consider that Dim
means dimension.
With renewed hope, I decided to search about how Dim
was chosen. Again, I didn't find an account on the subject, still I was able to find a definitive quote:
Before you can use an array, you must define it in a DIM (dimension) statement.
You can find this as part of the True BASIC Online User's Guides at the web page of True BASIC inc, a company founded by Thomas Eugene Kurtz, co-author of BASIC.
So, In reallity, Dim
is a shorthand for DIMENSION
, and yes. That existed in FORTRAN before, so it is likely that it was picked by influence of FORTRAN as Patrick McDonald said in his answer.
Dim sum as string = "this is not a chinese meal" REM example usage in VB.NET ;)
Add cast RemoteWebDriver
to driver
initialize and you will have the .setLogLevel
method:
import java.util.logging.Level;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class PrintLogTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/Users/.../chromedriver");
WebDriver driver = new ChromeDriver();
//here
((RemoteWebDriver) driver).setLogLevel(Level.INFO);
driver.get("https://google.com/");
driver.findElement(By.name("q")).sendKeys("automation test");
driver.quit();
}
}
Example output:
Jun 15, 2020 4:27:04 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: get [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, get {url=https://google.com/}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executing: findElement [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
Jun 15, 2020 4:27:06 PM org.openqa.selenium.remote.RemoteWebDriver log
INFO: Executed: [430aec21a9beb6340a4185c4ea6a693d, findElement {using=name, value=q}]
...
...
At least I've tried it on ChromeDriver()
and FirefoxDriver()
and it working fine.
There is not much point in declaring an array without size. An array is about size. When you declare an array of specific size, you specify the fixed number of slots available in a collection that can hold things, and accordingly memory is allocated. To add something to it, you will need to anyway reinitialize the existing array (even if you're resizing the array, see this thread). One of the rare cases where you would want to initialise an empty array would be to pass array as an argument.
If you want to define a collection when you do not know what size it could be of possibly, array is not your choice, but something like a List<T>
or similar.
That said, the only way to declare an array without specifying size is to have an empty array of size 0. hemant and Alex Dn provides two ways. Another simpler alternative is to just:
string[] a = { };
[The elements inside the bracket should be implicitly convertible to type defined, for instance, string[] a = { "a", "b" };
]
Or yet another:
var a = Enumerable.Empty<string>().ToArray();
Here is a more declarative way:
public static class Array<T>
{
public static T[] Empty()
{
return Empty(0);
}
public static T[] Empty(int size)
{
return new T[size];
}
}
Now you can call:
var a = Array<string>.Empty();
//or
var a = Array<string>.Empty(5);
The following solution seems to be a much shorter version for that:
<div id="imageDiv"></div>
In Javascript:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';
To add ANDROID_HOME value permanently,
gedit ~/.bashrc
and add the following lines
export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
Save the file and you need not update ANDROID_HOME value everytime.
You need to chain the method like this:
$('#input').val('test').change();
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.
''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task
''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task
''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource
''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
Me._ActionTask = Task.Run(taskAction)
Await Me.ActionTask ' Task.Run(streamEntitiesAction)
Try
Me.ActionTask?.Wait()
Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
Catch ex As AggregateException
Me.OnExceptionOccurred(ex)
Finally
Me.TaskCancellationSource.Dispose()
End Try
End Function
''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey"> The bucket key. </param>
''' <param name="timeout"> The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
If Me.IsTaskActive Then
Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
Else
Me._TaskCancellationSource = New Threading.CancellationTokenSource
Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
Me.TaskCancellationSource.CancelAfter(timeout)
' the action class is created withing the Async/Await function
Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
End If
End Sub
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
You can make an AJAX request like any other requests:
$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
alert(data);
}
})
1- close the project
2- close Android Studio
IDE
3- delete the .idea
directory
4- delete all .iml
files
5- open Android Studio
IDE and import the project
Answer from here
I'm running Ubuntu 14.04; and apt still couldn't find package; I tried all the answers above and more. The URL that worked for me is this:
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Source: http://www.liquidweb.com/kb/how-to-install-mongodb-on-ubuntu-14-04/
Another possible way is to delete the project from Eclipse (but don't delete the project contents from disk!) and then use the New Java Project wizard to create a project in-place. That wizard will detect the Java code and set up build paths automatically.
First thing, you should not do any DOM manipulation in controller function. Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.
AngularJS Docs : Creating a Directive that Manipulates the DOM
app.directive('buttonDirective', function($timeout) {
return {
scope: {
change: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
// triggering callback
scope.change();
});
});
}
};
});
change callback can be used as listener for click event.
See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).
The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o)
.
After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)
l = []
for x in range(0, 50):
for y in range(0, 50):
if hash((x,y)) in l:
print "Fail: ", (x,y)
l.append(hash((x,y)))
print "Test Finished"
CodePad (Available for 24 hours)
You can also just enter the website and:
The same limitation applies here: the folder must contain at least one file inside it.
Hello guys i am using this technique to get the values from the selected dropdown list and it is working like charm.
var methodvalue = $("#method option:selected").val();
The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:
Html code:
<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>
Js:
function resizeIframe(obj) {
alert(obj.contentWindow.location.pathname);
}
It happens when you don't properly close the code block:
if (condition){
// your code goes here*
{ // This doesn't close the code block
Correct way:
if (condition){
// your code goes here
} // Close the code block
import random
random.shuffle(array)
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response. If you want isolation for robustness, you probably want a process.
Here are some utility functions that allow you to determine if two files (or two streams) contain identical data.
I have provided a "fast" version that is multi-threaded as it compares byte arrays (each buffer filled from what's been read in each file) in different threads using Tasks.
As expected, it's much faster (around 3x faster) but it consumes more CPU (because it's multi threaded) and more memory (because it needs two byte array buffers per comparison thread).
public static bool AreFilesIdenticalFast(string path1, string path2)
{
return AreFilesIdentical(path1, path2, AreStreamsIdenticalFast);
}
public static bool AreFilesIdentical(string path1, string path2)
{
return AreFilesIdentical(path1, path2, AreStreamsIdentical);
}
public static bool AreFilesIdentical(string path1, string path2, Func<Stream, Stream, bool> areStreamsIdentical)
{
if (path1 == null)
throw new ArgumentNullException(nameof(path1));
if (path2 == null)
throw new ArgumentNullException(nameof(path2));
if (areStreamsIdentical == null)
throw new ArgumentNullException(nameof(path2));
if (!File.Exists(path1) || !File.Exists(path2))
return false;
using (var thisFile = new FileStream(path1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var valueFile = new FileStream(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (valueFile.Length != thisFile.Length)
return false;
if (!areStreamsIdentical(thisFile, valueFile))
return false;
}
}
return true;
}
public static bool AreStreamsIdenticalFast(Stream stream1, Stream stream2)
{
if (stream1 == null)
throw new ArgumentNullException(nameof(stream1));
if (stream2 == null)
throw new ArgumentNullException(nameof(stream2));
const int bufsize = 80000; // 80000 is below LOH (85000)
var tasks = new List<Task<bool>>();
do
{
// consumes more memory (two buffers for each tasks)
var buffer1 = new byte[bufsize];
var buffer2 = new byte[bufsize];
int read1 = stream1.Read(buffer1, 0, buffer1.Length);
if (read1 == 0)
{
int read3 = stream2.Read(buffer2, 0, 1);
if (read3 != 0) // not eof
return false;
break;
}
// both stream read could return different counts
int read2 = 0;
do
{
int read3 = stream2.Read(buffer2, read2, read1 - read2);
if (read3 == 0)
return false;
read2 += read3;
}
while (read2 < read1);
// consumes more cpu
var task = Task.Run(() =>
{
return IsSame(buffer1, buffer2);
});
tasks.Add(task);
}
while (true);
Task.WaitAll(tasks.ToArray());
return !tasks.Any(t => !t.Result);
}
public static bool AreStreamsIdentical(Stream stream1, Stream stream2)
{
if (stream1 == null)
throw new ArgumentNullException(nameof(stream1));
if (stream2 == null)
throw new ArgumentNullException(nameof(stream2));
const int bufsize = 80000; // 80000 is below LOH (85000)
var buffer1 = new byte[bufsize];
var buffer2 = new byte[bufsize];
var tasks = new List<Task<bool>>();
do
{
int read1 = stream1.Read(buffer1, 0, buffer1.Length);
if (read1 == 0)
return stream2.Read(buffer2, 0, 1) == 0; // check not eof
// both stream read could return different counts
int read2 = 0;
do
{
int read3 = stream2.Read(buffer2, read2, read1 - read2);
if (read3 == 0)
return false;
read2 += read3;
}
while (read2 < read1);
if (!IsSame(buffer1, buffer2))
return false;
}
while (true);
}
public static bool IsSame(byte[] bytes1, byte[] bytes2)
{
if (bytes1 == null)
throw new ArgumentNullException(nameof(bytes1));
if (bytes2 == null)
throw new ArgumentNullException(nameof(bytes2));
if (bytes1.Length != bytes2.Length)
return false;
for (int i = 0; i < bytes1.Length; i++)
{
if (bytes1[i] != bytes2[i])
return false;
}
return true;
}
with lombak 1.8.12, this worked for me
@Getter(value = lombok.AccessLevel.NONE)
@Setter(value = lombok.AccessLevel.NONE)
private int password;
Update
As of jQuery 3.0, the new syntax is just .on:
see this answer here and the code:
$('iframe').on('load', function() {
// do stuff
});
The simplest way I found is using @JsonFormat.Shape.OBJECT annotation for the enum.
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum{
....
}
My main idea is creating a tempDiv above the view which we want to scroll to. It work well without lagging in my project.
scrollToView = (element, offset) => {
var rect = element.getBoundingClientRect();
var targetY = rect.y + window.scrollY - offset;
var tempDiv;
tempDiv = document.getElementById("tempDiv");
if (tempDiv) {
tempDiv.style.top = targetY + "px";
} else {
tempDiv = document.createElement('div');
tempDiv.id = "tempDiv";
tempDiv.style.background = "#F00";
tempDiv.style.width = "10px";
tempDiv.style.height = "10px";
tempDiv.style.position = "absolute";
tempDiv.style.top = targetY + "px";
document.body.appendChild(tempDiv);
}
tempDiv.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
Example using
onContactUsClick = () => {
this.scrollToView(document.getElementById("contact-us"), 48);
}
Hope it help
Make sure first that you have certificates installed on your Debian in /etc/ssl/certs
.
If not, reinstall them:
sudo apt-get install --reinstall ca-certificates
Since that package does not include root certificates, add:
sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates
Make sure your git does reference those CA:
git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt
Jason C mentions another potential cause (in the comments):
It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.
The header file limits.h
defines macros that expand to various limits and parameters of the standard integer types.
$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;
After checking catalina.sh (for windows use the .bat versions of everything mentioned below)
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
Also this
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc
So create a setenv.sh under CATALINA_BASE/bin (same dir where the catalina.sh resides). Edit the file and set the arguments to CATALINA_OPTS
For e.g. the file would look like this if you wanted to change the heap size
CATALINA_OPTS=-Xmx512m
Or in your case since you're using windows setenv.bat would be
set CATALINA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
To clear the added options later just delete setenv.bat/sh
Object.values() method is now supported. This will give you an array of values of an object.
Object.values(dataObject)
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
Here's a nice semi cross-browser way to have gradient borders that fade out half way down. Simply by setting the color-stop to rgba(0, 0, 0, 0)
.fade-out-borders {
min-height: 200px; /* for example */
-webkit-border-image: -webkit-gradient(linear, 0 0, 0 50%, from(black), to(rgba(0, 0, 0, 0))) 1 100%;
-webkit-border-image: -webkit-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-moz-border-image: -moz-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
-o-border-image: -o-linear-gradient(black, rgba(0, 0, 0, 0) 50%) 1 100%;
border-image: linear-gradient(to bottom, black, rgba(0, 0, 0, 0) 50%) 1 100%;
}
<div class="fade-out-border"></div>
Usage explained:
Formal grammar: linear-gradient( [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )
\---------------------------------/ \----------------------------/
Definition of the gradient line List of color stops
More here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
This is an old thread, but I thought I would post this link, as it helped me quite a bit on this issue. Essentially what it's saying is the server configuration can override the php config. From the article:
For example mod_fastcgi has an option called "-idle-timeout" which controls the idle time of the script. So if the script does not output anything to the fastcgi handler for that many seconds then fastcgi would terminate it. The setup is somewhat like this:
Apache <-> mod_fastcgi <-> php processes
The article has other examples and further explanation. Hope this helps somebody else.
The Ternary operator is just written as a boolean expression followed by a questionmark and then two further expressions separated by a colon.
The first thing that I can see that you have got wrong is that your first expression isn't returning a boolean or anything sensible that could be converted to a boolean. Your first expression is always going to return a jQuery object that has no sensible interpretation as a boolean and what it does convert to is probably an unchanging interpretation. You are always best off returning something that has a well known boolean interpretation, if nothign else for the sake of readability.
The second thing is that you are putting a semicolon after each of your expressions which is wrong. In effect this is saying "end of construct" and so is breaking your ternary operator.
In this situation though you probably can do this a more easy way. If you use classes and the toggleClass method then you can easily get it to switch a class on and off and then you can put your styles in that class definition (Kudos to @yoavmatchulsky for suggesting use of classes up there in comments).
A fiddle of this is found here: http://jsfiddle.net/chrisvenus/wSMnV/ (based on the original)
rsync -rvc --delete --size-only --dry-run source dir target dir
#for sorting along column 1
indexofsort=np.argsort(dataset[:,0],axis=-1,kind='stable')
dataset = dataset[indexofsort,:]
JavaScript has a Number
type which is a 64 bit floating point number*.
If you're looking to convert a string to a number, use
parseInt
or parseFloat
. If using parseInt
, I'd recommend always passing the radix too.+
operator e.g. +"123456"
Number
constructor e.g. var n = Number("12343")
*there are situations where the number will internally be held as an integer.
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}
Test-Path may give odd answer. E.g. "Test-Path c:\temp\ -PathType leaf" gives false, but "Test-Path c:\temp* -PathType leaf" gives true. Sad :(
A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code
Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.
The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.
The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.
One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.
A simpler version of your code would be:
dict(zip(names, d.values()))
If you want to keep the same structure, you can change it to:
vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}
(You can just as easily put list(d.values())
inside the comprehension instead of vlst
; it's just wasteful to do so since it would be re-generating the list every time).
While this is essentially just @Brad's answer again, I thought it might be worth including a slightly modified function which will return the index of the item you're searching for if it exists in the array. If the item is not in the array, it returns -1
instead.
The output of this can be checked just like the "in string" function, If InStr(...) > 0 Then
, so I made a little test function below it as an example.
Option Explicit
Public Function IsInArrayIndex(stringToFind As String, arr As Variant) As Long
IsInArrayIndex = -1
Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
If arr(i) = stringToFind Then
IsInArrayIndex = i
Exit Function
End If
Next i
End Function
Sub test()
Dim fruitArray As Variant
fruitArray = Array("orange", "apple", "banana", "berry")
Dim result As Long
result = IsInArrayIndex("apple", fruitArray)
If result >= 0 Then
Debug.Print chr(34) & fruitArray(result) & chr(34) & " exists in array at index " & result
Else
Debug.Print "does not exist in array"
End If
End Sub
Then I went a little overboard and fleshed out one for two dimensional arrays because when you generate an array based on a range it's generally in this form.
It returns a single dimension variant array with just two values, the two indices of the array used as an input (assuming the value is found). If the value is not found, it returns an array of (-1, -1)
.
Option Explicit
Public Function IsInArray2DIndex(stringToFind As String, arr As Variant) As Variant
IsInArray2DIndex= Array(-1, -1)
Dim i As Long
Dim j As Long
For i = LBound(arr, 1) To UBound(arr, 1)
For j = LBound(arr, 2) To UBound(arr, 2)
If arr(i, j) = stringToFind Then
IsInArray2DIndex= Array(i, j)
Exit Function
End If
Next j
Next i
End Function
Here's a picture of the data that I set up for the test, followed by the test:
Sub test2()
Dim fruitArray2D As Variant
fruitArray2D = sheets("Sheet1").Range("A1:B2").value
Dim result As Variant
result = IsInArray2DIndex("apple", fruitArray2D)
If result(0) >= 0 And result(1) >= 0 Then
Debug.Print chr(34) & fruitArray2D(result(0), result(1)) & chr(34) & " exists in array at row: " & result(0) & ", col: " & result(1)
Else
Debug.Print "does not exist in array"
End If
End Sub
Byterbit solution is problematic because:
for cookies, setting expiration via session.cookie_lifetime is the right solution design-wise and security-wise! for expiring the session, you can use session.gc_maxlifetime.
expiring the cookies by calling session_destroy might yield unpredictable results because they might have already been expired.
making the change in php.ini is also a valid solution but it makes the expiration global for the entire domain which might not be what you really want - some pages might choose to keep some cookies more than others.
Your module is not yet loaded by the Angular Server in node
ng serve
, so restart your server so the server loads the module that you just added in @NgModule app.module.ts
The object, method, and property names in the .NET language bindings do not exactly correspond to those in the Java bindings. One of the principles of the project is that each language binding should "feel natural" to those comfortable coding in that language. In C#, the code you'd want for executing JavaScript is as follows
IWebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("return document.title");
Note that the complete documentation of the WebDriver API for .NET can be found at this link.
You could use an immutable struct
public struct Data
{
public Data(int intValue, string strValue)
{
IntegerData = intValue;
StringData = strValue;
}
public int IntegerData { get; private set; }
public string StringData { get; private set; }
}
var list = new List<Data>();
Or a KeyValuePair<int, string>
using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));
Simply do,
df = df[['mean'] + df.columns[:-1].tolist()]
To get a list of all childs of a specific type you can use:
private static IEnumerable<DependencyObject> FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
if (obj.GetType() == type)
{
yield return obj;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
foreach (var child in FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type))
{
if (child != null)
{
yield return child;
}
}
}
}
yield break;
}
http://www.sqlite.org/lang_altertable.html
As you can see in the diagram, only ADD COLUMN is supported. There is a (kinda heavy) workaround, though: http://www.sqlite.org/faq.html#q11
.parent {
width: 500px;
height: 200px;
border: 2px solid #000;
display: table-cell;
vertical-align: middle;
}
#kid {
width:70%; /* 70% of the parent */
margin:auto;
border:2px solid #F00;
height: 70%;
}
This does solve the problem very well (tested in all new browsers), where the parent div has class="parent" and the child div has id="kid".
That style centers both horizontally and vertically. Vertical center can only be done using complicated tricks--or by making the parent div function as a table-cell, which is one of the only elements in HTML that properly supports vertical alignment.
Simply set the height of the kid, margin auto, and middle vertical alignment, and it will work. It's the easiest solution that I know.
create database if not exists `test`;
USE `test`;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*Table structure for table `test` */
***CREATE TABLE IF NOT EXISTS `tblsample` (
`id` int(11) NOT NULL auto_increment,
`recid` int(11) NOT NULL default '0',
`cvfilename` varchar(250) NOT NULL default '',
`cvpagenumber` int(11) NULL,
`cilineno` int(11) NULL,
`batchname` varchar(100) NOT NULL default '',
`type` varchar(20) NOT NULL default '',
`data` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
);***
You need to find file devenv.exe.config
in C:\Users\{user_name}\AppData\Local\Microsoft\VisualStudio\14.0\
and update it. (Or C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\
, depending on the location of your devenv.exe
file.)
For this particular case, you should find rows that setup redirects for System.Collections.Immutable
and change newVersion from 1.1.36.0 to 1.1.37.0.
The original article is How to restore Visual Studio 2015 after the Update 1 (dependency dance).
if(isset($variable)){
$isTouch = $variable;
}
OR
if(!isset($variable)){
$isTouch = "";//
}
It is just simple.
Use this pattern: \b((ftp|https?)://)?([\w-\.]+\.(com|net|org|gov|mil|int|edu|info|me)|(\d+\.\d+\.\d+\.\d+))(:\d+)?(\/[\w-\/]*(\?\w*(=\w+)*[&\w-=]*)*(#[\w-]+)*)?
It matches any link contains:
Allowed Protocols: http, https and ftp
Allowed Domains: *.com, *.net, *.org, *.gov, *.mil, *.int, *.edu, *.info and *.me OR IP
Allowed Ports: true
Allowed Parameters: true
Allowed Hashes: true
The application has to be both compiled and linked with -g
option. I.e. you need to put -g
in both CPPFLAGS
and LDFLAGS
.
try jquery,
<div>
<a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
<legend class="majorpointslegend">Expand</legend>
<div id="data" style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
$('#data').css("display","inherit");
$(".majorpointslegend").html("Collapse");
}
else
{
$('#data').css("display","none");
$(".majorpointslegend").html("Expand");
}
}
BookTitle
have a Composite key. so if the key of BookTitle
is referenced as a foreign key
you have to bring the complete composite key.
So to resolve the problem you need to add the complete composite key in the BookCopy
. So add ISBN
column as well. and they at the end.
foreign key (ISBN, Title) references BookTitle (ISBN, Title)
I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
Since nobody so far felt fit to point out why what you're trying doesn't work:
NA == NA
doesn't return TRUE
, it returns NA
(since comparing to undefined values should yield an undefined result). apply
on an atomic vector. You can't use apply
to loop over the elements in a column. a$x
, which is just the column (an atomic vector).I'd fix up 3. to get to a$x[is.na(a$x)] <- 0
IF you are using Gradle you can use the build.gradle file to programmatically add value to the xml resources at compile time.
Example Code extracted from: https://medium.com/@manas/manage-your-android-app-s-versioncode-versionname-with-gradle-7f9c5dcf09bf
buildTypes {
debug {
versionNameSuffix ".debug"
resValue "string", "app_version", "${defaultConfig.versionName}${versionNameSuffix}"
}
release {
resValue "string", "app_version", "${defaultConfig.versionName}"
}
}
now use @string/app_version
as needed in XML
It will add .debug
to the version name as describe in the linked article when in debug mode.