First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
You can use a simple regex (updated version from user viriathus as eregi
is deprecated)
if (preg_match('#^http#', $url) === 1) {
// Starts with http (case sensitive).
}
or if you want a case insensitive search
if (preg_match('#^http#i', $url) === 1) {
// Starts with http (case insensitive).
}
Regexes allow to perform more complex tasks
if (preg_match('#^https?://#i', $url) === 1) {
// Starts with http:// or https:// (case insensitive).
}
Performance wise, you don't need to create a new string (unlike with substr) nor parse the whole string if it doesn't start with what you want. You will have a performance penalty though the 1st time you use the regex (you need to create/compile it).
This extension maintains a global per-thread cache of compiled regular expressions (up to 4096). http://www.php.net/manual/en/intro.pcre.php
Clojure, the decode function assumes frame is sent as map of {:data byte-array-buffer :size int-size-of-buffer}
, because the actual size may not be the same size as the byte-array depending on chunk size of your inputstream.
Code posted here: https://gist.github.com/viperscape/8918565
(defn ws-decode [frame]
"decodes websocket frame"
(let [data (:data frame)
dlen (bit-and (second data) 127)
mstart (if (== dlen 127) 10 (if (== dlen 126) 4 2))
mask (drop 2 (take (+ mstart 4) data))
msg (make-array Byte/TYPE (- (:size frame) (+ mstart 4)))]
(loop [i (+ mstart 4), j 0]
(aset-byte msg j (byte (bit-xor (nth data i) (nth mask (mod j 4)))))
(if (< i (dec(:size frame))) (recur (inc i) (inc j))))
msg))
(defn ws-encode [data]
"takes in bytes, return websocket frame"
(let [len (count data)
blen (if (> len 65535) 10 (if (> len 125) 4 2))
buf (make-array Byte/TYPE (+ len blen))
_ (aset-byte buf 0 -127) ;;(bit-or (unchecked-byte 0x80)
(unchecked-byte 0x1)
_ (if (= 2 blen)
(aset-byte buf 1 len) ;;mask 0, len
(do
(dorun(map #(aset-byte buf %1
(unchecked-byte (bit-and (bit-shift-right len (*(- %2 2) 8))
255)))
(range 2 blen) (into ()(range 2 blen))))
(aset-byte buf 1 (if (> blen 4) 127 126))))
_ (System/arraycopy data 0 buf blen len)]
buf))
This will do:
/^(apple|banana)$/
to exclude from captured strings (e.g. $1
,$2
):
(?:apple|banana)
I used this more concisely :
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);
it works perfectly. :)
The Registry locations
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
give the location for the executable.
But if you need the location where to save the Task extensions, it's on
%ProgramFiles%\MSBuild
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
This is what I'm using at the moment:
import os, shutil
path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = moveto+f
shutil.move(src,dst)
Now fully functional. Hope this helps you.
I've turned this into a function, that accepts a source and destination directory, making the destination folder if it doesn't exist, and moves the files. Also allows for filtering of the src files, for example if you only want to move images, then you use the pattern '*.jpg'
, by default, it moves everything in the directory
import os, shutil, pathlib, fnmatch
def move_dir(src: str, dst: str, pattern: str = '*'):
if not os.path.isdir(dst):
pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
for f in fnmatch.filter(os.listdir(src), pattern):
shutil.move(os.path.join(src, f), os.path.join(dst, f))
For SQL Server 2005 and 2008, if we want a random sample of individual rows (from Books Online):
SELECT * FROM Sales.SalesOrderDetail
WHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)
/ CAST (0x7fffffff AS int)
I think that doing this might be easier than most people think!
Try this:
var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.
if (yourTextArea.length < 10 || yourTextArea.length > 400) {
alert("The field must have no less than 10 and no more than 400 characters.");
return false;
}
Please let me know it this was useful. And if so, vote up! Thx!
Daniel
The CSS property touch-action may get you what you are looking for, though it may not work in all your target browsers.
html, body {
width: 100%; height: 100%;
overflow: hidden;
touch-action: none;
}
Using PDO:[1]
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
$statement = $pdo->prepare($select);
$statement->execute($ids);
Using MySQLi [2]
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
$statement = $mysqli->prepare($select);
$statement->bind_param(str_repeat('i', count($ids)), ...$ids);
$statement->execute();
$result = $statement->get_result();
Explanation:
IN()
operator to check if a value exists in a given list.In general it looks like this:
expr IN (value,...)
We can build an expression to place inside the ()
from our array. Note that there must be at least one value inside the parenthesis or MySQL will return an error; this equates to making sure that our input array has at least one value. To help prevent against SQL injection attacks, first generate a ?
for each input item to create a parameterized query. Here I assume that the array containing your ids is called $ids
:
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
Given an input array of three items $select
will look like:
SELECT *
FROM galleries
WHERE id IN (?, ?, ?)
Again note that there is a ?
for each item in the input array. Then we'll use PDO or MySQLi to prepare and execute the query as noted above.
IN()
operator with stringsIt is easy to change between strings and integers because of the bound parameters. For PDO there is no change required; for MySQLi change str_repeat('i',
to str_repeat('s',
if you need to check strings.
[1]: I've omitted some error checking for brevity. You need to check for the usual errors for each database method (or set your DB driver to throw exceptions).
[2]: Requires PHP 5.6 or higher. Again I've omitted some error checking for brevity.
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
int segundo = 0;
DateTime dt = new DateTime();
private void timer1_Tick(object sender, EventArgs e){
segundo++;
label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}
If what you are needing is an array of arrays, you can do this way:
key:
- [ 'value11', 'value12', 'value13' ]
- [ 'value21', 'value22', 'value23' ]
I made a simple wrapper for the Fullscreen API, called screenfull.js, to smooth out the prefix mess and fix some inconsistencies in the different implementations. Check out the demo to see how the Fullscreen API works.
Recommended reading:
i added some exception handling to @Aaron's answer.
import subprocess
import sys
try:
import pandas as pd
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", 'pandas'])
finally:
import pandas as pd
You may obtain the stream key via the API: https://github.com/justintv/twitch-api
Why not simply use a range
and os.walk
combined with the zip
? Is not the best solution, but would work too.
For example like this:
# your part before
for count, (root, dirs, files) in zip(range(0, 1), os.walk(dir_name)):
# logic stuff
# your later part
Works for me on python 3.
Also: A break
is simpler too btw. (Look at the answer from @Pieter)
All of the information you are looking for can be found here and here (thanks Reed Copsey):
From the first link:
Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
...
The access level for class members and struct members, including nested classes and structs, is private by default.
...
interfaces default to internal access.
...
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
From the second link:
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.
And for nested types:
Members of Default member accessibility ---------- ---------------------------- enum public class private interface public struct private
Check out angular-ui, specifically, route checking: http://angular-ui.github.io/ui-utils/
If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.
SourceTree version used is 1.6.14.0
Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with.
For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes:
.^$*+?()[{\|
and these inside character classes:
^-]\
For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE):
.^$*+?()[{\|
Escaping any other characters is an error with POSIX ERE.
Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.:
[]^-]
In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning:
.^$*[\
Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs.
Inside character classes, BREs follow the same rule as EREs.
If all this makes your head spin, grab a copy of RegexBuddy. On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.
I have used both JXL (now "JExcel") and Apache POI. At first I used JXL, but now I use Apache POI.
First, here are the things where both APIs have the same end functionality:
However, there are many differences:
Additionally, POI contains not just the main "usermodel" API, but also an event-based API if all you want to do is read the spreadsheet content.
In conclusion, because of the better documentation, more features, active development, and Excel 2007+ format support, I use Apache POI.
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
You may use Apache Commons IO:
try (OutputStream outputStream = ...) {
IOUtils.write("data", outputStream, "UTF-8");
}
According to the spec for locating Schemas
there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy
(thanks for being unambiguous, spec!)
and
in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.
So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation
attribute), depending on your "community." If you specify a specific schemaLocation
, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation
or noNamespaceSchemaLocation
attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).
Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation
xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd"
typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd
(so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.
I had the same problem when setting the center of the map with map.setCenter()
. Using Number()
solved for me. Had to use parseFloat
to truncate the data.
code snippet:
var centerLat = parseFloat(data.lat).toFixed(0);
var centerLng = parseFloat(data.long).toFixed(0);
map.setCenter({
lat: Number(centerLat),
lng: Number(centerLng)
});
In PHP, you'll need to either use the multibyte functions, or turn on mbstring.func_overload. That way things like strlen will work if you have characters that take more than one byte.
You'll also need to identify the character set of your responses. You can either use AddDefaultCharset, as above, or write PHP code that returns the header. (Or you can add a META tag to your HTML documents.)
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
UPDATE: DO NOT use this old answer, better use this: https://stackoverflow.com/a/39266840/4031815
Ok after some hours of research I found svg-android to be quite easy to use, so I'm leaving here step by step instructions:
download lib from: https://code.google.com/p/svg-android/downloads/list
Latest version at the moment of writing this is: svg-android-1.1.jar
Put jar in lib
dir.
Save your *.svg file in res/drawable
dir (In illustrator is as easy as pressing Save as and select svg)
Code the following in your activity using the svg library:
ImageView imageView = (ImageView) findViewById(R.id.imgView);
SVG svg = SVGParser.getSVGFromResource(getResources(), R.drawable.example);
//The following is needed because of image accelaration in some devices such as samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
Very easy I made a simple class to contain past code and reduce boilerplate code, like this:
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
public class SvgImage {
private static ImageView imageView;
private Activity activity;
private SVG svg;
private int xmlLayoutId;
private int drawableId;
public SvgImage(Activity activity, int layoutId, int drawableId) {
imageView = (ImageView) activity.findViewById(layoutId);
svg = SVGParser.getSVGFromResource(activity.getResources(), drawableId);
//Needed because of image accelaration in some devices such as samsung
imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
imageView.setImageDrawable(svg.createPictureDrawable());
}
}
Now I can call it like this in activity:
SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain);
SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder);
SvgImage oceanSVG = new SvgImage(MainActivity.this, R.id.oceanImageView, R.drawable.ocean);
SvgImage fireSVG = new SvgImage(MainActivity.this, R.id.fireImageView, R.drawable.fire);
SvgImage windSVG = new SvgImage(MainActivity.this, R.id.windImageView,R.drawable.wind);
SvgImage universeSVG = new SvgImage(MainActivity.this, R.id.universeImageView,R.drawable.universe);
Your currently selected backend, 'agg' does not support show().
AGG
backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.
ImportError: No module named _backend_gdk
For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.
Do you call the show()
method inside a terminal or application that has access to a graphical environment?
Try other GUI backends, in this order:
TkAgg
WX
QTAgg
QT4Agg
u want select all data from database then u can try this:-
dbclassDataContext dc= new dbclassDataContext()
List<tableName> ObjectName= dc.tableName.ToList();
otherwise You can try this:-
var Registration = from reg in dcdc.GetTable<registration>() select reg;
and method Syntex :-
var Registration = dc.registration.Select(reg => reg);
If pip doesn't come with your installation of python 3.6, this may work:
wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py
then you can python -m install
This is how I do it, useful for simple custom objects to which you keep adding attributes:
Given an object created with obj = type("Obj",(object,),{})
, or by simply:
class Obj: pass
obj = Obj()
Add some attributes:
obj.name = 'gary'
obj.age = 32
then, to obtain a dictionary with only the custom attributes:
{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}
# {'name': 'gary', 'age': 32}
You could also use POSIX regular expressions, like
SELECT id FROM groups where name ~* 'administrator'
SELECT 'asd' ~* 'AsD'
returns t
As much as people like to say "order doesn't matter its just convention" this breaks down when entering cross domain interfaces, IE transfer from C ordering to Fortran ordering or some other ordering scheme. There, precisely how your data is layed out and how shape is represented in numpy is very important.
By default, numpy uses C ordering, which means contiguous elements in memory are the elements stored in rows. You can also do FORTRAN ordering ("F"), this instead orders elements based on columns, indexing contiguous elements.
Numpy's shape further has its own order in which it displays the shape. In numpy, shape is largest stride first, ie, in a 3d vector, it would be the least contiguous dimension, Z, or pages, 3rd dim etc... So when executing:
np.zeros((2,3,4)).shape
you will get
(2,3,4)
which is actually (frames, rows, columns)
. doing np.zeros((2,2,3,4)).shape
instead would mean (metaframs, frames, rows, columns)
. This makes more sense when you think of creating multidimensional arrays in C like langauges. For C++, creating a non contiguously defined 4D array results in an array [ of arrays [ of arrays [ of elements ]]]
. This forces you to de reference the first array that holds all the other arrays (4th dimension) then the same all the way down (3rd, 2nd, 1st) resulting in syntax like:
double element = array4d[w][z][y][x]
;
In fortran, this indexed ordering is reversed (x is instead first array4d[x][y][z][w]
), most contiguous to least contiguous and in matlab, it gets all weird.
Matlab tried to preserve both mathematical default ordering (row, column) but also use column major internally for libraries, and not follow C convention of dimensional ordering. In matlab, you order this way:
double element = array4d[y][x][z][w]
;
which deifies all convention and creates weird situations where you are sometimes indexing as if row ordered and sometimes column ordered (such as with matrix creation).
In reality, Matlab is the unintuitive one, not Numpy.
The systemd
way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|
You might be able to do something inline like
ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'
or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here
in an ExecStartPost
Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.
(May want to increase TimeoutStartSec from the default 90s as well)
I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.
<iframe src="http://docs.google.com/gview?url=http://path.com/to/your/pdf.pdf&embedded=true"
style="width:600px; height:500px;" frameborder="0"></iframe>
Conditional Forms
Simple
conditional-directive
text-if-true
endif
Moderately Complex
conditional-directive
text-if-true
else
text-if-false
endif
More Complex
conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif
Conditional Directives
If Equal Syntax
ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"
If Not Equal Syntax
ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"
If Defined Syntax
ifdef variable-name
If Not Defined Syntax
ifndef variable-name
foreach Function
foreach Function Syntax
$(foreach var, list, text)
foreach Semantics
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.
The most correct and modern form is to use IoC
to put dependencies into the endpoint method, like the thymeleaf Model
instance...
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greeting(
@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
// returns the already proccessed model from src/main/resources/templates/greeting.html
}
}
See complete example at: https://spring.io/guides/gs/serving-web-content/
If you're trying to do this in a MiniTest unit test, you can use assert_includes
. Example:
pets = ['Cat', 'Dog', 'Bird']
assert_includes(pets, 'Dog') # -> passes
assert_includes(pets, 'Zebra') # -> fails
If you want to add a column to your table which is automatically updated to half of some other column, you can do that with a trigger.
But I think the already proposed answer are a better way to do this.
Dry coded trigger :
CREATE TRIGGER halfcolumn_insert AFTER INSERT ON table
FOR EACH ROW BEGIN
UPDATE table SET calculated = value / 2 WHERE id = NEW.id;
END;
CREATE TRIGGER halfcolumn_update AFTER UPDATE ON table
FOR EACH ROW BEGIN
UPDATE table SET calculated = value / 2 WHERE id = NEW.id;
END;
I don't think you can make only one trigger, since the event we must respond to are different.
>>> text = 'lipsum'
>>> text[3:]
'sum'
See the official documentation on strings for more information and this SO answer for a concise summary of the notation.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
On some CPUs, there is a dedicated set of registers for the stack. When a call instruction is executed, one register is loaded with the program counter at the same time as a second register is loaded with the contents of the first, a third register is be loaded with the second, and a fourth with the third, etc. When a return instruction is executed, the program counter is latched with the contents of the first stack register and the same time as that register is latched from the second; that second register is loaded from a third, etc. Note that such hardware stacks tend to be rather small (many the smaller PIC series micros, for example, have a two-level stack).
While a hardware stack does have some advantages (push and pop don't add any time to a call/return, for example) having registers which can be loaded with two sources adds cost. If the stack gets very big, it will be cheaper to replace the push-pull registers with an addressable memory. Even if a small dedicated memory is used for this, it's cheaper to have 32 addressable registers and a 5-bit pointer register with increment/decrement logic, than it is to have 32 registers each with two inputs. If an application might need more stack than would easily fit on the CPU, it's possible to use a stack pointer along with logic to store/fetch stack data from main RAM.
I just changed 2 parameters:
.wrap {
display: block;
width:661px;
}
You can write a query as follows:
IF OBJECT_ID('ProcedureName','P') IS NOT NULL
DROP PROC ProcedureName
GO
CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....
To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P
This query will find the procedure and if it is available it will drop it and create new one.
For detailed information about OBJECT_ID and Object types please visit : SYS.Objects
Sometimes, even if you install rimraf
globally you can have a local rimraf
dependency (SASS usually have it). In this case I would run following commands:
Follow first 2 steps as usagidon recommended, if you have issues or errors try
npm uninstall rimraf & rimraf node_modules
this will delete local rimraf
and use the global one
As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.
Stored procedures are for executing by an outside program, or on a timed interval.
The answers here will explain it better than I can:
If you have the freedom to choose the hostname, then you can just add your host to a dynanmic DNS service, like dyndns.org. Then you can rely on the iPad's normal resolution mechanisms to resolve the address.
Your method signature is:
- (void) myTest:(NSString *)
withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).
If you call the function in this manner:
[self performSelector:@selector(myTest:) withObject:myString];
It will work.
But, as the other posters have suggested, you may want to rename the method:
- (void)myTestWithAString:(NSString*)aString;
And call:
[self performSelector:@selector(myTestWithAString:) withObject:myString];
However there are very good answers already available for this. Here is my answer:
1. set.stream().forEach(System.out::println); // It simply uses stream to display set values
2. set.forEach(System.out::println); // It uses Enhanced forEach to display set values
Also, if this Set is of Custom class type, for eg: Customer.
Set<Customer> setCust = new HashSet<>();
Customer c1 = new Customer(1, "Hena", 20);
Customer c2 = new Customer(2, "Meena", 24);
Customer c3 = new Customer(3, "Rahul", 30);
setCust.add(c1);
setCust.add(c2);
setCust.add(c3);
setCust.forEach((k) -> System.out.println(k.getId()+" "+k.getName()+" "+k.getAge()));
// Customer class:
class Customer{
private int id;
private String name;
private int age;
public Customer(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} // Getter, Setter methods are present.}
If you want to update the user interface with activity result, you can't to use this.runOnUiThread(new Runnable() {}
Doing this the UI won't refresh with new value. Instead, you can do this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
global_lat = data.getDoubleExtra("LATITUDE", 0);
global_lng = data.getDoubleExtra("LONGITUDE", 0);
new_latlng = true;
}
@Override
protected void onResume() {
super.onResume();
if(new_latlng)
{
PhysicalTagProperties.this.setLocation(global_lat, global_lng);
new_latlng=false;
}
}
This seems silly but works pretty well.
C++ virtual constructor is not possible.For example you can not mark a constructor as virtual.Try this code
#include<iostream.h>
using namespace std;
class aClass
{
public:
virtual aClass()
{
}
};
int main()
{
aClass a;
}
It causes an error.This code is trying to declare a constructor as virtual. Now let us try to understand why we use virtual keyword. Virtual keyword is used to provide run time polymorphism. For example try this code.
#include<iostream.h>
using namespace std;
class aClass
{
public:
aClass()
{
cout<<"aClass contructor\n";
}
~aClass()
{
cout<<"aClass destructor\n";
}
};
class anotherClass:public aClass
{
public:
anotherClass()
{
cout<<"anotherClass Constructor\n";
}
~anotherClass()
{
cout<<"anotherClass destructor\n";
}
};
int main()
{
aClass* a;
a=new anotherClass;
delete a;
getchar();
}
In main a=new anotherClass;
allocates a memory for anotherClass
in a pointer a
declared as type of aClass
.This causes both the constructor (In aClass
and anotherClass
) to call automatically.So we do not need to mark constructor as virtual.Because when an object is created it must follow the chain of creation (i.e first the base and then the derived classes).
But when we try to delete a delete a;
it causes to call only the base destructor.So we have to handle the destructor using virtual keyword. So virtual constructor is not possible but virtual destructor is.Thanks
You can.
package test;
public class Test {
public static void main(String[] args) {
B b = new B();
}
}
class B {
// Essentially package-private - cannot be accessed anywhere else but inside the `test` package
}
try this:
struct Pos{
int x;
int y;
inline Pos& operator=(const Pos& other){
x=other.x;
y=other.y;
return *this;
}
inline Pos operator+(const Pos& other) const {
Pos res {x+other.x,y+other.y};
return res;
}
const inline bool operator==(const Pos& other) const {
return (x==other.x and y == other.y);
}
};
//My Form
<form id="someform">
<div class="input-group">
<textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea>
<span class="input-group-addon">
<button type="submit" name="post_comment" class="btn btn-primary">
Post
</button>
</span>
</div>
</form>
//your text area get value to URL
<?php
if(isset($_POST['post_comment']))
{
echo htmlspecialchars($_POST['post']);
}
?>
//print the value using get
echo $_GET['post'];
//url must be like this
http://localhost/blog/home.php?post=asdasdsad&post_comment=
//post value has asdasdsad so it will print to your page
What format are you wanting the output?
If you're happy with a string then consider the following C# code:
double num = 3.12345;
num.ToString("G3");
The result will be "3.12".
This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.
So if you go to
-> Setting -> Project:My_project -> Project Structure,
Just the directory in which the source code is available and mark it as "Sources" (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.
You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;
05/12/2015
This has been covered here before.
The concept of first does not apply to object properties, and the order of a for...in loop is not guaranteed by the specs, however in practice it is reliably FIFO except critically for chrome (bug report). Make your decisions accordingly.
To apply an ORDER BY or LIMIT clause to an individual SELECT, parenthesize the SELECT and place the clause inside the parentheses:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
As @user3483203 pointed out, numpy.select is the best approach
Store your conditional statements and the corresponding actions in two lists
conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])
actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']
You can now use np.select using these lists as its arguments
df['label_race'] = np.select(conds,actions,default='Other')
Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html
As soon as there is only method Long.valueOf(long)
, cast from int
to long
will be done implicitly in case of using Long.valueOf(intValue)
.
The more clear way to do this is
Integer.valueOf(intValue).longValue()
For me, this problem began when I hosted a VPN-connection on my Windows 8 computer.
Simply deleting the connection from "Control Panel\Network and Internet\Network Connections" solved the problem.
For anyone who is looking to enable this on the Mac version, it is not available. Developers of Visual Studio stated they will include in their roadmap.
So many complicated methods... Just find all "Titled" group and join its lower cased variant with underscore.
>>> import re
>>> def camel_to_snake(string):
... groups = re.findall('([A-z0-9][a-z]*)', string)
... return '_'.join([i.lower() for i in groups])
...
>>> camel_to_snake('ABCPingPongByTheWay2KWhereIsOurBorderlands3???')
'a_b_c_ping_pong_by_the_way_2_k_where_is_our_borderlands_3'
If you don't want make numbers like first character of group or separate group - you can use ([A-z][a-z0-9]*)
mask.
These are few things which will help you in understanding everything... using iloc
In iloc, [initial row:ending row, initial column:ending column]
case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:]
this means that you want only the last column...
case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1]
this means that you want all columns and all rows except the last column...
case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:]
this means that you want only the last row...
case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:]
this means that you want all columns and all rows except the last column...
case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1]
this means that you want all columns and all rows except the last column and last row...
I didn't see the bootstrap answer, so for what's it's worth:
<div class="col-xs-4">Left Div</div>
<div class="col-xs-4">Middle Div</div>
<div class="col-xs-4">Right Div</div>
<br style="clear: both;" />
let Bootstrap figure out the percentages. I like to clear both, just in case.
It looks like this question has been answered all ready, but I'll post my input anyway.
I know when I like to use self-executing functions.
var myObject = {
childObject: new function(){
// bunch of code
},
objVar1: <value>,
objVar2: <value>
}
The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...
object: {
childObject: {
childObject: {<value>, <value>, <value>}
},
objVar1: <value>,
objVar2: <value>
}
Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.
// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
class HexToDecimal
{
static void Main()
{
while (true)
{
Console.Write("Enter digit number to convert: ");
int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number
Console.Write("Enter hexadecimal number: ");
string str = Console.ReadLine();
str.Reverse();
char[] ch = str.ToCharArray();
int[] intarray = new int[n];
decimal decimalval = 0;
for (int i = ch.Length - 1; i >= 0; i--)
{
if (ch[i] == '0')
intarray[i] = 0;
if (ch[i] == '1')
intarray[i] = 1;
if (ch[i] == '2')
intarray[i] = 2;
if (ch[i] == '3')
intarray[i] = 3;
if (ch[i] == '4')
intarray[i] = 4;
if (ch[i] == '5')
intarray[i] = 5;
if (ch[i] == '6')
intarray[i] = 6;
if (ch[i] == '7')
intarray[i] = 7;
if (ch[i] == '8')
intarray[i] = 8;
if (ch[i] == '9')
intarray[i] = 9;
if (ch[i] == 'A')
intarray[i] = 10;
if (ch[i] == 'B')
intarray[i] = 11;
if (ch[i] == 'C')
intarray[i] = 12;
if (ch[i] == 'D')
intarray[i] = 13;
if (ch[i] == 'E')
intarray[i] = 14;
if (ch[i] == 'F')
intarray[i] = 15;
decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);
}
Console.WriteLine(decimalval);
}
}
}
PermGen stands for Permanent Generation.
Here is a brief blurb on DDJ
Take a look at your code :
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
Try to follow the guide in link that I provided. You should be just fine when you study it carefully.
---EDIT----
First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!
Try to do it like this:
getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
See where the console.log(...) is!
Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.
Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.
@Override
protected void onPostExecute(final Boolean success) {
mProgressDialog.dismiss();
mProgressDialog = null;
setting the value null works for me
Try this link.... horizontal rule
That should do the trick.
The code below is xml.
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:background="#FF00FF00" />
Below code lets observe any size change for any given div in Angular.
<div #observed-div>
</div>
then in the Component:
oldWidth = 0;
oldHeight = 0;
@ViewChild('observed-div') myDiv: ElementRef;
ngAfterViewChecked() {
const newWidth = this.myDiv.nativeElement.offsetWidth;
const newHeight = this.myDiv.nativeElement.offsetHeight;
if (this.oldWidth !== newWidth || this.oldHeight !== newHeight)
console.log('resized!');
this.oldWidth = newWidth;
this.oldHeight = newHeight;
}
you use this as txtView.setText("hello");
I found this link helpful
$scope.loadSkillTags = function (query) {
var data = {qData: query};
return SkillService.querySkills(data).then(function(response) {
return response.data;
});
};
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.
Here the simples
a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
You can't call a non-static method without first creating an instance of its parent class.
So from the static method, you would have to instantiate a new object...
Vehicle myCar = new Vehicle();
... and then call the non-static method.
myCar.Drive();
Instead of subclassing threading.Thread
, one can modify the function to allow
stopping by a flag.
We need an object, accessible to running function, to which we set the flag to stop running.
We can use threading.currentThread()
object.
import threading
import time
def doit(arg):
t = threading.currentThread()
while getattr(t, "do_run", True):
print ("working on %s" % arg)
time.sleep(1)
print("Stopping as you wish.")
def main():
t = threading.Thread(target=doit, args=("task",))
t.start()
time.sleep(5)
t.do_run = False
t.join()
if __name__ == "__main__":
main()
The trick is, that the running thread can have attached additional properties. The solution builds on assumptions:
True
False
.Running the code, we get following output:
$ python stopthread.py
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.
Other alternative is to use threading.Event
as function argument. It is by
default False
, but external process can "set it" (to True
) and function can
learn about it using wait(timeout)
function.
We can wait
with zero timeout, but we can also use it as the sleeping timer (used below).
def doit(stop_event, arg):
while not stop_event.wait(1):
print ("working on %s" % arg)
print("Stopping as you wish.")
def main():
pill2kill = threading.Event()
t = threading.Thread(target=doit, args=(pill2kill, "task"))
t.start()
time.sleep(5)
pill2kill.set()
t.join()
Edit: I tried this in Python 3.6. stop_event.wait()
blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set()
works instead.
Advantage of pill to kill is better seen, if we have to stop multiple threads at once, as one pill will work for all.
The doit
will not change at all, only the main
handles the threads a bit differently.
def main():
pill2kill = threading.Event()
tasks = ["task ONE", "task TWO", "task THREE"]
def thread_gen(pill2kill, tasks):
for task in tasks:
t = threading.Thread(target=doit, args=(pill2kill, task))
yield t
threads = list(thread_gen(pill2kill, tasks))
for thread in threads:
thread.start()
time.sleep(5)
pill2kill.set()
for thread in threads:
thread.join()
The SQL in your SP is wrong. You probably want
Select @code = RecItemCode from Receipt where RecTransaction = @id
In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException
when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.
The other issue is that your SQL statement if rewritten as
Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id
It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements
Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id
This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.
If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery();
and then read the output parameter value.
Another issue with your SP and code. In your SP, you have declared @code as varchar
. In your code, you specify the parameter type as Int
. Either change your SP or your code to make the types consistent.
Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write
Select RecItemCode from Receipt where RecTransaction = @id
And then use object obj = cmd.ExecuteScalar();
to get the result, no need for an output parameter in the SP or in your code.
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
all answers are great
, and it seems that no
more answer is needed
but I just wonted to point out something about &&
operator called dependent condition
In expressions using operator &&, a condition—we’ll call this the dependent condition
—may require another condition to be true for the evaluation of the dependent condition to be meaningful.
In this case, the dependent condition should be placed after the && operator to prevent errors.
Consider the expression (i != 0) && (10 / i == 2)
. The dependent condition (10 / i == 2)
must appear after
the &&
operator to prevent the possibility of division by zero.
another example (myObject != null) && (myObject.getValue() == somevaluse)
and another thing: &&
and ||
are called short-circuit evaluation because the second argument is executed or evaluated only if
the first
argument does not suffice
to determine
the value
of the expression
References: Java™ How To Program (Early Objects), Tenth Edition
A good solution can be one provided by @Elias Van Ootegan
in a comment that is:
$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";
I tried it and worked for me, thanks buddy.
Edited
Note: It will work in PHP 5.5+
Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.
Slug can create using SlugField
Ex:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
If you want to use title as slug, django has a simple function called slugify
from django.template.defaultfilters import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
def slug(self):
return slugify(self.title)
If it needs uniqueness, add unique=True
in slug field.
for instance, from the previous example:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug
My 2p solution:
#include <random>
#include <string>
std::string random_string(std::string::size_type length)
{
static auto& chrs = "0123456789"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
thread_local static std::mt19937 rg{std::random_device{}()};
thread_local static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);
std::string s;
s.reserve(length);
while(length--)
s += chrs[pick(rg)];
return s;
}
The paths for msysgit are:
Windows XP -C:\Documents and Settings\<user_name>\.gitconfig
Windows Vista+ C:\Users\<user_name>\.gitconfig
I just ran into this the other day.
What I did, which seems easier than the above, is to set the pattern on a variable on the scope and refer to it in ng-pattern in the view.
When "the checkbox is unchecked" I simply set the regex value to /.*/ on the onChanged callback (if going to unchecked). ng-pattern picks that change up and says "OK, your value is fine". Form is now valid. I would also remove the bad data from the field so you don't have an apparent bad phone # sitting there.
I had additional issues around ng-required, and did the same thing. Worked like a charm.
It does not use the -f
option in readlink, and it should therefore work on BSD/Mac OS X.
.
dot operator)foo->dir1/dir2/bar bar->./../doe doe->script
I am looking for corner cases where this code does not work. Please let me know.
pushd . > /dev/null
SCRIPT_PATH="${BASH_SOURCE[0]}";
while([ -h "${SCRIPT_PATH}" ]); do
cd "`dirname "${SCRIPT_PATH}"`"
SCRIPT_PATH="$(readlink "`basename "${SCRIPT_PATH}"`")";
done
cd "`dirname "${SCRIPT_PATH}"`" > /dev/null
SCRIPT_PATH="`pwd`";
popd > /dev/null
echo "srcipt=[${SCRIPT_PATH}]"
echo "pwd =[`pwd`]"
The script must be on disk somewhere. Let it be over a network. If you try to run this script from a PIPE it will not work
wget -o /dev/null -O - http://host.domain/dir/script.sh |bash
Technically speaking, it is undefined. Practically speaking, there is no sane way to detect this. (A co-process can not access the environment of the parent.)
Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.
I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:
for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)
I believe the last one also looks at inheritance (e.g. Dog is Animal == true), which is better in most cases.
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
It can be solved in more simple way: in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
After that use any controllers that your want to process index.htm with @RequestMapping("index.htm"). Or just use index controller
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</bean>
I have found a solution of git bash command when you try to build war using git mvn clean install for “java.lang.OutOfMemoryError: PermGen space” in Maven build error come
use below command first
$ export MAVEN_OPTS="-Xmx512m -Xss32m"
then use your mvn command to clean install /build war file
$ mvn clean install
NOTE: you don't need -XX:MaxPermSize argument in MAVEN_OPTS when your are using jdk1.8
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=XXXm; support was removed in 8.0
Clean Docker by using the following command:
docker images --no-trunc | grep '<none>' | awk '{ print $3 }' \
| xargs docker rmi
You need to declare the prototype of your writeFile
function, before actually using it:
int writeFile( void );
int main( void )
{
...
Here try this it works 100%
<html>
<body>
<script>
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}
$('form').submit(function() {
window.onbeforeunload = null;
});
</script>
</body>
</html>
You copy and paste the following code. It will display all the tables with Name and Created Date
SELECT object_name,created FROM user_objects
WHERE object_name LIKE '%table_name%'
AND object_type = 'TABLE';
Note: Replace '%table_name%' with the table name you are looking for.
Just to reconcile the difference between sandeepmistry's answer and davidgyoung's answer:
02 01 1a 1a ff 4C 00
Is part of the advertising data format specification [1]
02 # length of following AD structure
01 # <<Flags>> AD Structure [2]
1a # read as b00011010.
# In this case, LE General Discoverable,
# and simultaneous BR/EDR but this may vary by device!
1a # length of following AD structure
FF # Manufacturer specific data [3]
4C00 # Apple Inc [4]
0215 # ?? some 2-byte header
Missing from the AD is a Service [5] definition. I think the iBeacon protocol itself has no relationship to the GATT and standard service discovery. If you download RedBearLab's iBeacon program, you'll see that they happen to use the GATT for configuring the advertisement parameters, but this seems to be specific to their implementation, and not part of the spec. The AirLocate program doesn't seem to use the GATT for configuration, for instance, according to LightBlue and or other similar programs I tried.
References:
My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.
As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)
As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE()
. This WILL use the index on the log_timestamp column.
SELECT *
FROM some_table
WHERE
log_timestamp
BETWEEN
timestamp(CURRENT_DATE())
AND # Adds 23.9999999 HRS of seconds to the current date
timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));
I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:
SELECT *
FROM some_table
WHERE
log_timestamp >= timestamp(CURRENT_DATE()) AND
log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));
Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
Your selector looks for the descendant of a input:radio[name=cols]
element that has the id of newcol
(well the value of that variable).
Try this instead (since you're selecting by ID anyway):
$('#' + newcol).prop('checked',true);
Here is a demo: http://jsfiddle.net/jasper/n8CdM/1/
Also, as of jQuery 1.6 the perferred method of altering a property is .prop()
: http://api.jquery.com/prop
After reading all of the previous answers, I still wanted more clarity. This blog at the official git website http://git-scm.com/blog gave me what I was looking for:
The HEAD in Git is the pointer to the current branch reference, which is in turn a pointer to the last commit you made or the last commit that was checked out into your working directory. That also means it will be the parent of the next commit you do. It's generally simplest to think of it as HEAD is the snapshot of your last commit.
I know many have already posted some good answers. However I want to suggest one nice and easy method without importing any library.
l = [(2, 3), (3, 4), (2, 4)]
l.sort(key = lambda x: (-x[0], -x[1]) )
print(l)
l.sort(key = lambda x: (x[0], -x[1]) )
print(l)
Output will be
[(3, 4), (2, 4), (2, 3)]
[(2, 4), (2, 3), (3, 4)]
The output will be sorted based on the order of the parameters we provided in the tuple format
What I did when trying to send some data from several selected rows in DataTable to MVC action:
HTML At the beginning of a page:
@Html.AntiForgeryToken()
(just a row is shown, bind from model):
@foreach (var item in Model.ListOrderLines)
{
<tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
<td>@item.OrderId</td>
<td>@item.OrderDate</td>
<td>@item.RequestedDeliveryDate</td>
<td>@item.ProductName</td>
<td>@item.Ident</td>
<td>@item.CompanyName</td>
<td>@item.DepartmentName</td>
<td>@item.ProdAlias</td>
<td>@item.ProducerName</td>
<td>@item.ProductionInfo</td>
</tr>
}
Button which starts the JavaScript function:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript function:
function ProcessMultipleRows() {
if ($(".dataTables_scrollBody>tr.selected").length > 0) {
var list = [];
$(".dataTables_scrollBody>tr.selected").each(function (e) {
var element = $(this);
var orderid = element.data("orderid");
var iscustom = element.data("iscustom");
var orderlineid = element.data("orderlineid");
var folderPath = "";
var fileName = "";
list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
});
$.ajax({
url: '@Url.Action("StartWorkflow","OrderLines")',
type: "post", //<------------- this is important
data: { model: list }, //<------------- this is important
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
showPreloader();
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function () {
hidePreloader();
}
});
}
}
MVC action:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
And MODEL in C#:
public class WorkflowModel
{
public int OrderId { get; set; }
public int OrderLineId { get; set; }
public bool IsCustomOrderLine { get; set; }
public string FolderPath { get; set; }
public string FileName { get; set; }
}
CONCLUSION:
The reason for ERROR:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
Is attribute: [ValidateAntiForgeryToken]
for the MVC action StartWorkflow
Solution in Ajax call:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
To send List of objects you need to form data like in example (populating list object) and:
data: { model: list },
type: "post",
If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.
Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself
body
parameter within the mailto
string%0D%0A
as newlineThe mailto
URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:
[...] line breaks in the body of a message MUST be encoded with
"%0D%0A"
.
Implementations MAY add a final line break to the body of a message even if there is no trailing"%0D%0A"
in the body [...]
See also in section 6 the example from the same RFC:
<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>
The above mailto
body corresponds to:
send current-issue
send index
First, ordinary logic is helpful.
If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.
class GetOutOfLoop( Exception ):
pass
try:
done= False
while not done:
isok= False
while not (done or isok):
ok = get_input("Is this ok? (y/n)")
if ok in ("y", "Y") or ok in ("n", "N") :
done= True # probably better
raise GetOutOfLoop
# other stuff
except GetOutOfLoop:
pass
For this specific example, an exception may not be necessary.
On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.
add it in your index.php file, and it will work on all over your site
if ( function_exists( 'date_default_timezone_set' ) ) {
date_default_timezone_set('Asia/Kolkata');
}
After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here")))
really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.
Here's an example with mutate
. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=
, to do this.
## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
mtcars %>%
mutate(UQ(rlang::sym(new_name)) := UQ(rlang::sym(name1)) + UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')
The pattern works with other dplyr
functions as well. Here's filter
:
## filter a column by a value
filter_values <- function(name, value){
mtcars %>%
filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)
Or arrange
:
## transform a variable and then sort by it
arrange_values <- function(name, transform){
mtcars %>%
arrange(UQ(rlang::sym(name)) %>% UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')
For select
, you don't need to use the pattern. Instead you can use !!
:
## select a column
select_name <- function(name){
mtcars %>%
select(!!name)
}
select_name('mpg')
Handle the Worksheet_Change
event or the Workbook_SheetChange
event.
The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.
This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...
<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...
In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A
's hello to a property on B
. After __init__
, hello will be attached to B as self.hello
, which is actually a reference to A's hello:
class A:
def hello(self, msg):
print(f"Hello {msg}")
class B:
hello = A.hello
print(A.hello)
print(B.hello)
b = B()
b.hello("good looking!")
Prints:
<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!
While you can do this with brute casting and suppressed warnings
Map<String,Object> map = new HashMap<String,Object>();
// Two casts in a row. Note no "new"!
@SuppressWarnings("unchecked")
Map<String,String> newMap = (HashMap<String,String>)(Map)map;
that's really missing the whole point. :)
An attempt to convert a narrow generic type to a broader generic type means you're using the wrong type in the first place.
As an analogy: Imagine you have a program that does volumous text processing. Imagine that you do first half of the processing using Objects
(!!) and then decide to do the second half with correct-typing as a String
, so you narrow-cast from Object
to String
. Fortunately, you can do this is java (easily in this case) - but it's just masking the fact you're using weak-typing in the first half. Bad practice, no argument.
No difference here (just harder to cast). You should always use strong typing. At minimum use some base type - then generics wildcards can be used ("? extends BaseType" or "? super BaseType") to give type-compatability and automatic casting. Even better, use the correct known type. Never use Object unless you have 100% generalised code that can really be used with any type.
Hope that helps! :) :)
Note: The generic strong typing and type-casting will only exist in .java code. After compilation to .class we are left with raw types (Map and HashMap) with no generic type parameters plus automatic type casting of keys and values. But it greatly helps because the .java code itself is strongly-typed and concise.
I got this after downgrading a project from .net 4.5 to .net 3.5.
To resolve I had to go in to the project - properties - settings window and delete all my settings, save the project, exit and restart visual studio, go back into project - properties -settings window and re-enter all my settings and their default values
This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)
turning it back to 1.0.7 solved the problem instantly.
have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.
anyway, this problem is fixed when using AngularJS vs 1.0.7.
You can use the following SQL to compare both date and time -
Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');
Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-
It should work perfect.
You're confusing the size of the array list with its capacity:
When you call new ArrayList<Integer>(10)
, you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.
One way to add ten elements to the array list is by using a loop:
for (int i = 0; i < 10; i++) {
arr.add(0);
}
Having done this, you can now modify elements at indices 0..9.
Apart from calling java -jar myjar.jar com.mycompany.Myclass
, you can also make the main class in your Manifest a Dispatcher class.
Example:
public class Dispatcher{
private static final Map<String, Class<?>> ENTRY_POINTS =
new HashMap<String, Class<?>>();
static{
ENTRY_POINTS.put("foo", Foo.class);
ENTRY_POINTS.put("bar", Bar.class);
ENTRY_POINTS.put("baz", Baz.class);
}
public static void main(final String[] args) throws Exception{
if(args.length < 1){
// throw exception, not enough args
}
final Class<?> entryPoint = ENTRY_POINTS.get(args[0]);
if(entryPoint==null){
// throw exception, entry point doesn't exist
}
final String[] argsCopy =
args.length > 1
? Arrays.copyOfRange(args, 1, args.length)
: new String[0];
entryPoint.getMethod("main", String[].class).invoke(null,
(Object) argsCopy);
}
}
Please remove call to trustSrc
function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}.
Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview
src
url. Have a look on the following code.
Before:
Javascript
scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;
Html
<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"
But for security reason they are recommending following method
Javascript
var baseUrl = "page";
scope.getIframeSrc = function() {
// One should think about their particular case and sanitize accordingly
var qs = ["a", "b"].map(function(value, name) {
return encodeURIComponent(name) + "=" +
encodeURIComponent(value);
}).join("&");
// `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
return baseUrl + "?" + qs;
};
Html
<iframe src="{{getIframeSrc()}}">
install.packages("ggplot2movies")
data(movies, package="ggplot2movies")
Plot average Length vs Rating
rating_by_len = tapply(movies$length,
movies$rating,
mean)
plot(names(rating_by_len), rating_by_len, ylim=c(0, 200)
,xlab = "Rating", ylab = "Length", main="Average Rating by Movie Length", pch=21)
Add error bars to the plot: mean - sd, mean + sd
sds = tapply(movies$length, movies$rating, sd)
upper = rating_by_len + sds
lower = rating_by_len - sds
segments(x0=as.numeric(names(rating_by_len)),
y0=lower,
y1=upper)
Hope that helps.
Printing a specific element is
list.get(INDEX)
I think the best way to print the whole list in one go and this will also avoid putting a loop
Arrays.toString(list.toArray())
Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT
clause). You can only select one column from such a query in this context.
Consider joining to the users
table instead; this will give you more flexibility when selecting what columns you want from users
.
SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id
FROM topics
LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by
WHERE topics.cat_id = :cat
GROUP BY topics.id
I'm using typescript, for me it got resolved with checking "Tslint integration" flag under prettier settings (in vscode preferences):
UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).
I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.
Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."
Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.
The actual dialog text you have marked above definitely relates to the Zone.Identifier
alternate data stream with a value of 3
that is added to any file that is downloaded from the Internet (see linked answer above for more details).
I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).
It is n for next and N for previous.
And if you use reverse search with ?
(for example, ?cake
) instead of /
, it is the other way round.
If it is installed on your system, you should try to run vimtutor
command from your terminal, which will start a tutorial of the basic Vim commands.
Rob Wells advice about * and # is also very pertinent.
This is just a version mismatch. You have compiled your code using java version 9 and your current JRE is version 8. Try upgrading your JRE to 9.
49 = Java 5
50 = Java 6
51 = Java 7
52 = Java 8
53 = Java 9
54 = Java 10
55 = Java 11
56 = Java 12
57 = Java 13
58 = Java 14
To my mind, the question ought to be the other way round whenever you see an inner class - does it really need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?
Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
Perform rotation using transform: rotate(xdeg)
and also apply overflow: hidden
to the parent component to avoid overlapping effect
.div-parent {
overflow: hidden
}
.div-child {
transform: rotate(270deg);
}
Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
A. Grab file data from the file field
The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
This saves the file data to a file variable for later use.
B. Handle the file upload on submit
When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:
C. Upload the files
Quick and dirty php script to upload the files and pass back some info:
<?php // You need to add server side validation and better error handling here
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
$uploaddir = './uploads/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
IMP: Don't use this, write your own.
D. Handle the form submit
The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:
function submitForm(event, data)
{
// Create a jQuery object from the form
$form = $(event.target);
// Serialize the form data
var formData = $form.serialize();
// You should sterilise the file names
$.each(data.files, function(key, value)
{
formData = formData + '&filenames[]=' + value;
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
console.log('SUCCESS: ' + data.success);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
},
complete: function()
{
// STOP LOADING SPINNER
}
});
}
Final note
This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
For me, the problem was that I wasn't including bootstrap.min.css (I was only including bootstrap-responsive.min.css).
You can see a lot of screen sizes on this site.
From http://www.emirweb.com/ScreenDeviceStatistics.php
####################################################################################################
# Filter out same-sized same-dp screens and width/height swap.
####################################################################################################
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
Size: 640 x 360 px (426 x 240 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
Size: 280 x 280 px (186 x 186 dp) hdpi
####################################################################################################
# Sorted by smallest width.
####################################################################################################
sw800dp:
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
sw720dp:
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
sw600dp:
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
sw480dp:
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
sw320dp:
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
sw240dp:
Size: 640 x 360 px (426 x 240 dp) hdpi
lower:
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 280 x 280 px (186 x 186 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
####################################################################################################
# Different size in px only.
####################################################################################################
2560 x 1600 px
2048 x 1536 px
1920 x 1200 px
1920 x 1152 px
1920 x 1080 px
1600 x 1200 px
1600 x 900 px
1440 x 904 px
1366 x 768 px
1360 x 768 px
1280 x 960 px
1280 x 800 px
1280 x 768 px
1280 x 720 px
1279 x 720 px
1152 x 720 px
1080 x 607 px
1024 x 960 px
1024 x 770 px
1024 x 768 px
1024 x 600 px
960 x 640 px
960 x 600 px
960 x 540 px
864 x 480 px
854 x 480 px
800 x 600 px
800 x 480 px
768 x 576 px
640 x 480 px
640 x 360 px
480 x 320 px
432 x 240 px
400 x 240 px
320 x 240 px
280 x 280 px
####################################################################################################
# Different size in dp only.
####################################################################################################
1920 x 1080 dp
1600 x 900 dp
1442 x 901 dp
1366 x 768 dp
1365 x 1024 dp
1365 x 800 dp
1360 x 768 dp
1280 x 800 dp
1280 x 768 dp
1280 x 720 dp
1152 x 720 dp
1066 x 800 dp
1066 x 640 dp
1024 x 960 dp
1024 x 770 dp
1024 x 768 dp
1024 x 600 dp
961 x 600 dp
961 x 540 dp
960 x 602 dp
960 x 600 dp
960 x 540 dp
853 x 533 dp
853 x 480 dp
800 x 480 dp
768 x 576 dp
720 x 404 dp
682 x 400 dp
640 x 480 dp
640 x 400 dp
640 x 384 dp
640 x 360 dp
639 x 360 dp
600 x 360 dp
576 x 320 dp
569 x 320 dp
533 x 320 dp
512 x 384 dp
480 x 320 dp
426 x 320 dp
426 x 240 dp
320 x 213 dp
266 x 160 dp
186 x 186 dp
I drop a lot of same-sized same-dp screens, ignore height/width swap and include some sorting results.
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();
you should give permission on your db
grant execute on (packageName or tableName) to user;
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Another use of in_array in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('blur', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
Specifying pointer-events: none
in CSS disables mouse input but doesn't disable keyboard input. For example, the user can still tab to the link and "click" it by pressing the Enter key or (in Windows) the ? Menu key. You could disable specific keystrokes by intercepting the keydown
event, but this would likely confuse users relying on assistive technologies.
Probably the best way to disable a link is to remove its href
attribute, making it a non-link. You can do this dynamically with a conditional href
attribute binding:
<a *ngFor="let link of links"
[attr.href]="isDisabled(link) ? null : '#'"
[class.disabled]="isDisabled(link)"
(click)="!isDisabled(link) && onClick(link)">
{{ link.name }}
</a>
Or, as in Günter Zöchbauer's answer, you can create two links, one normal and one disabled, and use *ngIf
to show one or the other:
<ng-template ngFor #link [ngForOf]="links">
<a *ngIf="!isDisabled(link)" href="#" (click)="onClick(link)">{{ link.name }}</a>
<a *ngIf="isDisabled(link)" class="disabled">{{ link.name }}</a>
</ng-template>
Here's some CSS to make the link look disabled:
a.disabled {
color: gray;
cursor: not-allowed;
text-decoration: underline;
}
sc queryex type= service state= all | find /i "NATION"
/i
for case insensitive searchtype=
is deliberate and requiredHere's how you do it.
First, decorate your list this way:
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
<div class="p">
<div class="text-bullet-centered">⁕</div>
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
text text text text text text text text text text text text text text text text
</div>
Add this CSS:
.p {
position: relative;
margin: 20px;
margin-left: 50px;
}
.text-bullet-centered {
position: absolute;
left: -40px;
top: 50%;
transform: translate(0%,-50%);
font-weight: bold;
}
And voila, it works. Resize a window, to see that it indeed works.
As a bonus, you can easily change font and color of bullets, which is very hard to do with normal lists.
.p {_x000D_
position: relative;_x000D_
margin: 20px;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
.text-bullet-centered {_x000D_
position: absolute;_x000D_
left: -40px;_x000D_
top: 50%;_x000D_
transform: translate(0%, -50%);_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>_x000D_
<div class="p">_x000D_
<div class="text-bullet-centered">⁕</div>_x000D_
text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text_x000D_
text text text text text text text text text text text text text_x000D_
</div>
_x000D_
Based on Wikipedia's articles.
A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many problems, a greedy strategy does not in general produce an optimal solution, but nonetheless a greedy heuristic may yield locally optimal solutions that approximate a global optimal solution in a reasonable time.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one.
The idea behind dynamic programming is quite simple. In general, to solve a given problem, we need to solve different parts of the problem (subproblems), then combine the solutions of the subproblems to reach an overall solution. Often when using a more naive method, many of the subproblems are generated and solved many times. The dynamic programming approach seeks to solve each subproblem only once, thus reducing the number of computations: once the solution to a given subproblem has been computed, it is stored or "memo-ized": the next time the same solution is needed, it is simply looked up. This approach is especially useful when the number of repeating subproblems grows exponentially as a function of the size of the input.
We can make whatever choice seems best at the moment and then solve the subproblems that arise later. The choice made by a greedy algorithm may depend on choices made so far but not on future choices or all the solutions to the subproblem. It iteratively makes one greedy choice after another, reducing each given problem into a smaller one. In other words, a greedy algorithm never reconsiders its choices.
This is the main difference from dynamic programming, which is exhaustive and is guaranteed to find the solution. After every stage, dynamic programming makes decisions based on all the decisions made in the previous stage, and may reconsider the previous stage's algorithmic path to solution.
For example, let's say that you have to get from point A to point B as fast as possible, in a given city, during rush hour. A dynamic programming algorithm will look into the entire traffic report, looking into all possible combinations of roads you might take, and will only then tell you which way is the fastest. Of course, you might have to wait for a while until the algorithm finishes, and only then can you start driving. The path you will take will be the fastest one (assuming that nothing changed in the external environment).
On the other hand, a greedy algorithm will start you driving immediately and will pick the road that looks the fastest at every intersection. As you can imagine, this strategy might not lead to the fastest arrival time, since you might take some "easy" streets and then find yourself hopelessly stuck in a traffic jam.
In mathematical optimization, greedy algorithms solve combinatorial problems having the properties of matroids.
Dynamic programming is applicable to problems exhibiting the properties of overlapping subproblems and optimal substructure.
I agree with Hugh W post "I conclude that the same error code is used to indicate multiple unrelated problems"
Other posts have not mentioned that this error occurs frequently if the worksheet is locked. While I haven't tested every scenario, it seems that anything that you can not do in excel when a worksheet is locked with throw this error if you attempt to do it via VSTO/Com while the sheet is locked. E.G. Changing any style artifact (font, font size, colour, underline), changing the Excel Validation, changing the column widths, row heights, formulas
Regular expression to get a string between two strings in JavaScript
The most complete solution that will work in the vast majority of cases is using a capturing group with a lazy dot matching pattern. However, a dot .
in JavaScript regex does not match line break characters, so, what will work in 100% cases is a [^]
or [\s\S]
/[\d\D]
/[\w\W]
constructs.
In JavaScript environments supporting ECMAScript 2018, s
modifier allows .
to match any char including line break chars, and the regex engine supports lookbehinds of variable length. So, you may use a regex like
var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any
// Or
var result = s.match(/(?<=cow\s*).*?(?=\s*milk)/gs); // Same but whitespaces are optional
In both cases, the current position is checked for cow
with any 1/0 or more whitespaces after cow
, then any 0+ chars as few as possible are matched and consumed (=added to the match value), and then milk
is checked for (with any 1/0 or more whitespaces before this substring).
This and all other scenarios below are supported by all JavaScript environments. See usage examples at the bottom of the answer.
cow (.*?) milk
cow
is found first, then a space, then any 0+ chars other than line break chars, as few as possible as *?
is a lazy quantifier, are captured into Group 1 and then a space with milk
must follow (and those are matched and consumed, too).
cow ([\s\S]*?) milk
Here, cow
and a space are matched first, then any 0+ chars as few as possible are matched and captured into Group 1, and then a space with milk
are matched.
If you have a string like >>>15 text>>>67 text2>>>
and you need to get 2 matches in-between >>>
+number
+whitespace
and >>>
, you can't use />>>\d+\s(.*?)>>>/g
as this will only find 1 match due to the fact the >>>
before 67
is already consumed upon finding the first match. You may use a positive lookahead to check for the text presence without actually "gobbling" it (i.e. appending to the match):
/>>>\d+\s(.*?)(?=>>>)/g
See the online regex demo yielding text1
and text2
as Group 1 contents found.
Also see How to get all possible overlapping matches for a string.
Lazy dot matching pattern (.*?
) inside regex patterns may slow down script execution if very long input is given. In many cases, unroll-the-loop technique helps to a greater extent. Trying to grab all between cow
and milk
from "Their\ncow\ngives\nmore\nmilk"
, we see that we just need to match all lines that do not start with milk
, thus, instead of cow\n([\s\S]*?)\nmilk
we can use:
/cow\n(.*(?:\n(?!milk$).*)*)\nmilk/gm
See the regex demo (if there can be \r\n
, use /cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm
). With this small test string, the performance gain is negligible, but with very large text, you will feel the difference (especially if the lines are long and line breaks are not very numerous).
Sample regex usage in JavaScript:
_x000D__x000D__x000D__x000D__x000D_//Single/First match expected: use no global modifier and access match[1] console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]); // Multiple matches: get multiple matches with a global modifier and // trim the results if length of leading/trailing delimiters is known var s = "My cow always gives milk, thier cow also gives milk"; console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);})); //or use RegExp#exec inside a loop to collect all the Group 1 contents var result = [], m, rx = /cow (.*?) milk/g; while ((m=rx.exec(s)) !== null) { result.push(m[1]); } console.log(result);
Using the modern
String#matchAll
method_x000D__x000D__x000D__x000D__x000D_const s = "My cow always gives milk, thier cow also gives milk"; const matches = s.matchAll(/cow (.*?) milk/g); console.log(Array.from(matches, x => x[1]));
Check This Example
Html:
<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
Javascript:
$('#showall').click(function(){
$('div').show();
});
$('#showdiv1').click(function(){
$('div[id^=div]').hide();
$('#div1').show();
});
$('#showdiv2').click(function(){
$('div[id^=div]').hide();
$('#div2').show();
});
$('#showdiv3').click(function(){
$('div[id^=div]').hide();
$('#div3').show();
});
$('#showdiv4').click(function(){
$('div[id^=div]').hide();
$('#div4').show();
});
According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:
Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]
You can get his full slides here.
Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.
So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP ? XML ? DOM ? SQL ? …" which "passes all the data through the cache".
Immediately Invoked Async Arrow Function:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression:
(async function () {
console.log(await asyncFunction());
})();
Please use .size() function instead of .length and also specify li tag in selector.
Change your code like.
if ( $('#menu ul li').size() > 1 ) {
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.
Based on First answer here is the complete image selection options:
Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
|PNG|*.PNG;*.png
|JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
|Bitmap(.BMP,.bmp)|*.BMP;*.bmp
|GIF|*.GIF;*.gif
|TIF|*.tif;*.tiff
|ICO|*.ico;*.ICO";
NB This answer is factually incorrect; as pointed out by a comment below, success() does return the original promise. I'll not change; and leave it to OP to edit.
The major difference between the 2 is that .then()
call returns a promise (resolved with a value returned from a callback) while .success()
is more traditional way of registering callbacks and doesn't return a promise.
Promise-based callbacks (.then()
) make it easy to chain promises (do a call, interpret results and then do another call, interpret results, do yet another call etc.).
The .success()
method is a streamlined, convenience method when you don't need to chain call nor work with the promise API (for example, in routing).
In short:
.then()
- full power of the promise API but slightly more verbose.success()
- doesn't return a promise but offeres slightly more convienient syntax<form onsubmit="return false;">
...
</form>
add android:focusableInTouchMode="true" in root layout, when edit text will be clicked at that time cursor will be shown.
To stage modified and deleted files
git add -u
You can use the object_hook
parameter for json.loads
to pass in a converter. You don't have to do the conversion after the fact. The json
module will always pass the object_hook
dicts only, and it will recursively pass in nested dicts, so you don't have to recurse into nested dicts yourself. I don't think I would convert unicode strings to numbers like Wells shows. If it's a unicode string, it was quoted as a string in the JSON file, so it is supposed to be a string (or the file is bad).
Also, I'd try to avoid doing something like str(val)
on a unicode
object. You should use value.encode(encoding)
with a valid encoding, depending on what your external lib expects.
So, for example:
def _decode_list(data):
rv = []
for item in data:
if isinstance(item, unicode):
item = item.encode('utf-8')
elif isinstance(item, list):
item = _decode_list(item)
elif isinstance(item, dict):
item = _decode_dict(item)
rv.append(item)
return rv
def _decode_dict(data):
rv = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = key.encode('utf-8')
if isinstance(value, unicode):
value = value.encode('utf-8')
elif isinstance(value, list):
value = _decode_list(value)
elif isinstance(value, dict):
value = _decode_dict(value)
rv[key] = value
return rv
obj = json.loads(s, object_hook=_decode_dict)
In this particular case (assuming that the Class#forName()
didn't throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException
means that Driver#acceptsURL()
has returned false
for any of the loaded drivers.
And indeed, your JDBC URL is wrong:
String url = "'jdbc:mysql://localhost:3306/mysql";
Remove the singlequote:
String url = "jdbc:mysql://localhost:3306/mysql";
Easy as this:
string[] folders = System.IO.Directory.GetDirectories(@"C:\My Sample Path\","*", System.IO.SearchOption.AllDirectories);
onchange
only occurs when the change to the input element is committed by the user, most of the time this is when the element loses focus.
if you want your function to fire everytime the element value changes you should use the oninput
event - this is better than the key up/down events as the value can be changed with the user's mouse ie pasted in, or auto-fill etc
Apart from the accepted answer, you can also initialise your rows in the following manner -
matrix[i] = [0]*n
Therefore, the following piece of code will work -
m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
matrix += [0]
# initialize the matrix
for i in range (0,m):
matrix[i] = [0]*n
for i in range (0,m):
for j in range (0,n):
print ('entry in row: ',i+1,' column: ',j+1)
matrix[i][j] = int(input())
print (matrix)
if it doesnt exist load default image or handle error
$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
if (status == "error")
$(this).attr('src', 'images/DEFAULT.JPG');
else
$(this).attr('src', imgurl);
});
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
sum up each row using rowSums
(rowwise
works for any aggreation, but is slower)
df %>%
replace(is.na(.), 0) %>%
mutate(sum = rowSums(across(where(is.numeric))))
sum down each column
df %>%
summarise(across(everything(), ~ sum(., is.na(.), 0)))
sum up each row
df %>%
replace(is.na(.), 0) %>%
mutate(sum = rowSums(.[1:5]))
sum down each column using superseeded summarise_all
:
df %>%
replace(is.na(.), 0) %>%
summarise_all(funs(sum))
As most of the answers highlighted, we could use setMonth() method together with getMonth() method to add specific number of months to a given date.
Example: (as mentioned by @ChadD in his answer. )
var x = 12; //or whatever offset var CurrentDate = new Date(); CurrentDate.setMonth(CurrentDate.getMonth() + x);
But we should carefully use this solution as we will get trouble with edge cases.
To handle edge cases, answer which is given in following link is helpful.
https://stackoverflow.com/a/13633692/3668866
What is wrong with List<T>.Sort()
?
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort#overloads
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/
To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:
from IPython import get_ipython
ipython = get_ipython()
ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")
public class ListElementAdapter extends BaseAdapter{
String[] data;
Context context;
LayoutInflater layoutInflater;
public ListElementAdapter(String[] data, Context context) {
super();
this.data = data;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return data.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= layoutInflater.inflate(R.layout.item, null);
TextView txt=(TextView)convertView.findViewById(R.id.text);
txt.setText(data[position]);
return convertView;
}
}
Just call ListElementAdapter in your Main Activity and set Adapter to ListView.
If you have Microsoft Windows 10:
Now you should be able to connect to your pc-name\SQLEXPRESS
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.
One book not yet suggested but very important is "Linkers and Loaders" by John Levine. If you're not using an external assembler, you'll need a way to output a object file that can be linked into your final program. Even if you're using an external assembler, you'll probably need to understand relocations and how the whole program loading process works to make a working tool. This book collects a lot of the random lore around this process for various systems, including Win32 and Linux.
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
You need to escape the double-quotes inside the search string, like this:
string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");
Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res
will have the replacements.
I do not recommend keeping bad data in the database and then only correcting it on the output. We have a database where phone numbers are entered in variously as :
Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules. I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.
I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.
You could check out JBoss Tools plugin.
xmp
is the way to go, i.e.:
<xmp>
# your code...
</xmp>
In a SQL CASE clause, the first successfully matched condition is applied and any subsequent matching conditions are ignored.
JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));
Here is a solution that waits for all resource requests to complete. Once complete it will log the page content to the console and generate a screenshot of the rendered page.
Although this solution can serve as a good starting point, I have observed it fail so it's definitely not a complete solution!
I didn't have much luck using document.readyState
.
I was influenced by the waitfor.js example found on the phantomjs examples page.
var system = require('system');
var webPage = require('webpage');
var page = webPage.create();
var url = system.args[1];
page.viewportSize = {
width: 1280,
height: 720
};
var requestsArray = [];
page.onResourceRequested = function(requestData, networkRequest) {
requestsArray.push(requestData.id);
};
page.onResourceReceived = function(response) {
var index = requestsArray.indexOf(response.id);
if (index > -1 && response.stage === 'end') {
requestsArray.splice(index, 1);
}
};
page.open(url, function(status) {
var interval = setInterval(function () {
if (requestsArray.length === 0) {
clearInterval(interval);
var content = page.content;
console.log(content);
page.render('yourLoadedPage.png');
phantom.exit();
}
}, 500);
});
If 'config/config.json' file is used then add 'logging': false to the config.json in this case under development configuration section.
// file config/config.json
{
{
"development": {
"username": "username",
"password": "password",
"database": "db_name",
"host": "127.0.0.1",
"dialect": "mysql",
"logging": false
},
"test": {
...
}
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
Microsoft has also implemented the operators '<' and '>'. So you use these to compare two dates.
if (date1 < DateTime.Now)
Console.WriteLine("Less than the current time!");
Just use cd /d %root%
to switch driver letters and change directories.
Alternatively, use pushd %root%
to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd
to switch back.
Note that pushd
will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd
for that directory.
Here is a query which you can use to search for anything in from your database as a search result ,
SELECT * FROM tbl_customer
WHERE CustomerName LIKE '%".$search."%'
OR Address LIKE '%".$search."%'
OR City LIKE '%".$search."%'
OR PostalCode LIKE '%".$search."%'
OR Country LIKE '%".$search."%'
Using this code will help you search in for multiple columns easily