Keep in mind that unless you're writing your own data structure (e.g. linked list in C), it can depend dramatically on the implementation of data structures in your language/framework of choice. As an example, take a look at the benchmarks of Apple's CFArray over at Ridiculous Fish. In this case, the data type, a CFArray from Apple's CoreFoundation framework, actually changes data structures depending on how many objects are actually in the array - changing from linear time to constant time at around 30,000 objects.
This is actually one of the beautiful things about object-oriented programming - you don't need to know how it works, just that it works, and the 'how it works' can change depending on requirements.
to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php
$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");
$json_object = json_decode($unparsed_json);
then json_decode() parses JSON into a PHP object, or an array if you pass true
to the second parameter.
http://php.net/manual/en/function.json-decode.php
For example:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json)); // Object
var_dump(json_decode($json, true)); // Associative array
If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?
So, you are saying that the following two queries produce correct results:
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))
DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'
SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat
INNER JOIN PubAdvertiser AS pa
ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))
Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.
For example,
import pandas as pd
df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)
df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)
df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)
The linked comment is incorrect : 'L' to '1' will produce a rising edge.
In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk)
will (correctly) not trigger while (clk'event and clk = '1')
(incorrectly) will.
Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.
By closing and opening, the main form usually runs all related queries (including the subform related ones). I had a similar problem and resolved it by adding the following to Save Command button on click event.
DoCmd.Close acForm, "formname", acSaveYes
DoCmd.OpenForm "formname"
Length of characters to be matched.
{n,m} n <= length <= m
{n} length == n
{n,} length >= n
And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.
If you want the engine returns when length of 2 matched, use \d{2,5}?
we can use
element[role="ourRole"] {
requried style !important; /*for overriding the old css styles */
}
Another way of doing this with(out) preserving keys:
$test_array = [
"first_key" => "first_value",
"second_key" => "second_value"
];
$f = function($ar) {
return array_map(
function($key, $val) {
return "{$key} - {$val}";
},
array_keys($ar),
$ar
);
};
#-- WITHOUT preserving keys
$res = $f($test_array);
#-- WITH preserving keys
$res = array_combine(
array_keys($test_array),
$f($test_array)
);
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
this.removeEventListener('click',arguments.callee,false);
}
Should do it.
yes it's possible to print a string to the console.
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string strMytestString("hello world");
cout << strMytestString;
return 0;
}
stdafx.h isn't pertinent to the solution, everything else is.
This is for setting PATH on Mac OS X Version 10.9.5.
I have tried to add $HOME because I use user profile :
echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc
When you do not use user profile:
echo 'export PATH="$PATH:~/.composer/vendor/bin"' >> ~/.bashrc
Then reload:
source ~/.bashrc
I hope this help you.
For people having a startTime
(like 12h:30:30) and a duration
(value in minutes like 120), you can guess the endTime
like so:
const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"
Added windows support
def which(program):
path_ext = [""];
ext_list = None
if sys.platform == "win32":
ext_list = [ext.lower() for ext in os.environ["PATHEXT"].split(";")]
def is_exe(fpath):
exe = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
# search for executable under windows
if not exe:
if ext_list:
for ext in ext_list:
exe_path = "%s%s" % (fpath,ext)
if os.path.isfile(exe_path) and os.access(exe_path, os.X_OK):
path_ext[0] = ext
return True
return False
return exe
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return "%s%s" % (program, path_ext[0])
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return "%s%s" % (exe_file, path_ext[0])
return None
I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:
const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);
I know I am late, but stumped into the question, and based on ThomasH's answer:
for i in range(4): print "i equals 3" if i==3 else None
output: None None None i equals 3
I propose to update as:
for i in range(4): print("i equals 3") if i==3 else print('', end='')
output: i equals 3
Note, I am in python3 and had to use two print commands. pass after else won't work. Wanted to just comment on ThomasH's answer, but can't because I don't have enough reputation yet.
I found the best way to do this is with ChronoUnit.
long minutes = ChronoUnit.MINUTES.between(fromDate, toDate);
long hours = ChronoUnit.HOURS.between(fromDate, toDate);
Additional documentation is here: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
If you can't get to your php.ini file for some reason, disable errors to stdout (display_errors
) in a .htaccess file in any directory by adding the following line:
php_flag display_errors off
additionally, you can add error logging to a file:
php_flag log_errors on
You can execute commands in parallel with start
like this:
start "" ping myserver
start "" nslookup myserver
start "" morecommands
They will each start in their own command prompt and allow you to run multiple commands at the same time from one batch file.
Hope this helps!
I had the same problem and I solved it by adding a rule to the security Groups
Inbound SSH 0.0.0.0/0
Or you can add your IP address only
The answers above are more elegant, but I found a quick and dirty way that actually works really really incredibly well. You can see it in action at www.buildinglit.com
All I did was add a random offset to the latitude and longditude to my genxml.php page so it returns slightly different results each time with offset each time the map is created with markers. This sounds like a hack, but in reality you only need the markers to move a slight nudge in a random direction for them to be clickable on the map if they are overlapping. It actually works really well, I would say better than the spider method because who wants to deal with that complexity and have them spring everywhere. You just want to be able to select the marker. Nudging it randomly works perfect.
Here is an example of the while statement iteration node creation in my php_genxml.php
while ($row = @mysql_fetch_assoc($result)){ $offset = rand(0,1000)/10000000;
$offset2 = rand(0, 1000)/10000000;
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat'] + $offset);
$newnode->setAttribute("lng", $row['lng'] + $offset2);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("type", $row['type']);
$newnode->setAttribute("date", $row['date']);
$newnode->setAttribute("service", $row['service']);
$newnode->setAttribute("cost", $row['cost']);
$newnode->setAttribute("company", $company);
Notice under lat and long there is the +offset. from the 2 variables above. I had to divide random by 0,1000 by 10000000 in order to get a decimal that was randomly small enough to just barely move the markers around. Feel free to tinker with that variable to get one that is more precise for your needs.
This is the best solution I ever seen. Its more generic.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="100"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
This is the HTML only way:
<body>
<a name="top"></a>
foo content
foo bottom of page
<a href="#top">Back to Top</a>
</body>
There are quite a few other alternatives using jquery and jscript though which offer additional effects. It really just depends on what you are looking for.
This may be a Chrome bug. Unfortunately Chrome routinely breaks debugging. It often has some kind of memory leak and it often breaks or changes every few releases.
Debugging with formatted sources is currently extremely unreliable.
It's possible you're also trying to break on dead code.
To be certain it's not the browser you should also try to debug it in firefox.
If you read the message carefully you will see that you are using the permissions like camera, Microphone, Contacts, Storage and Phone, etc. and you don't supply a privacy policy. you need to supply a privacy policy if you do that. you can find more information about the android privacy policy on google
To Add Privacy Policy In-Play Console,
Find and select All Apps.
Select the application you need to add your Privacy Policy to.
Find the Policy at the end of the page.
Click App content to edit the listing for your app.
Find the field labeled Privacy Policy and place the URL of the page of your Privacy Policy
Click Save and you are good to go.
Note: You need to have a public web page to host your Privacy Policy. Google Play Store won't host the policy for you.
Having my tslint
rules configuration here always replacing the line Object["values"](myObject)
with Object.values(myObject)
.
Two options if you have same issue:
(Object as any).values(myObject)
or
/*tslint:disable:no-string-literal*/
`Object["values"](myObject)`
Here's a function I wrote for this common task. It's more efficient than the Series
/stack
methods. Column order and names are retained.
def tidy_split(df, column, sep='|', keep=False):
"""
Split the values of a column and expand so the new DataFrame has one split
value per row. Filters rows where the column is missing.
Params
------
df : pandas.DataFrame
dataframe with the column to split and expand
column : str
the column to split and expand
sep : str
the string used to split the column's values
keep : bool
whether to retain the presplit value as it's own row
Returns
-------
pandas.DataFrame
Returns a dataframe with the same columns as `df`.
"""
indexes = list()
new_values = list()
df = df.dropna(subset=[column])
for i, presplit in enumerate(df[column].astype(str)):
values = presplit.split(sep)
if keep and len(values) > 1:
indexes.append(i)
new_values.append(presplit)
for value in values:
indexes.append(i)
new_values.append(value)
new_df = df.iloc[indexes, :].copy()
new_df[column] = new_values
return new_df
With this function, the original question is as simple as:
tidy_split(a, 'var1', sep=',')
Try this, but you can adjust frame size with bounds and edit title.
package co.form.Try;
import javax.swing.JFrame;
public class Form {
public static void main(String[] args) {
JFrame obj =new JFrame();
obj.setBounds(10,10,700,600);
obj.setTitle("Application Form");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can't edit the image via CSS. The only solution I can think of is to edit the image and change its opacity, or make different images with all the opacities needed.
Set video
to your IIS MIME Type
This solved my problems.
envsubst was new to me. Fantastic.
For the record, using a heredoc is a great way to template a conf file.
STATUS_URI="/hows-it-goin"; MONITOR_IP="10.10.2.15";
cat >/etc/apache2/conf.d/mod_status.conf <<EOF
<Location ${STATUS_URI}>
SetHandler server-status
Order deny,allow
Deny from all
Allow from ${MONITOR_IP}
</Location>
EOF
Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.
You have to save Camera image to specific location then fetch from that location then convert it to byte-array.
Here is method for opening capturing camera image activity.
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
then your onActivityResult() method should be like this.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
Hope it helps!
Though all the answers on the page will return the desired result, they all have performance issues. Never perform calculations on fields in the WHERE
clause (including a DATE()
calculation) as that calculation must be performed on all rows in the table.
The BETWEEN ... AND
construct is inclusive for both border conditions, requiring one to specify the 23:59:59 syntax on the end date which itself has other issues (microsecond transactions, which I believe MySQL did not support in 2009 when the question was asked).
The proper way to query a MySQL timestamp
field for a particular day is to check for Greater-Than-Equals against the desired date, and Less-Than for the day after, with no hour specified.
WHERE datetime>='2009-10-20' AND datetime<'2009-10-21'
This is the fastest-performing, lowest-memory, least-resource intensive method, and additionally supports all MySQL features and corner-cases such as sub-second timestamp precision. Additionally, it is future proof.
In my case, the solution was to use an absolute path, to find an existing file:
import os.path
filepath = os.path.abspath(filepath)
# Leave this out if the file doesn't exist yet
assert os.path.exists(filepath), "The file doesn't exist"
conn = sqlite3.connect(filepath)
I don't know why this fix works: the path only contained ASCII characters and no spaces. Still it made the difference.
For reference: Windows 7, Python 3.6.5 (64-bit).
I was not able to reproduce the issue on another machine (also Windows 7, Python 3.6.4 64-bit), so I have no idea why this fix works.
To align horizontally it's pretty straight forward:
<style type="text/css">
body {
margin: 0;
padding: 0;
text-align: center;
}
.bodyclass #container {
width: ???px; /*SET your width here*/
margin: 0 auto;
text-align: left;
}
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>
and for vertical align, it's a bit tricky: here's the source
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Universal vertical center with CSS</title>
<style>
.greenBorder {border: 1px solid green;} /* just borders to see it */
</style>
</head>
<body>
<div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div class="greenBorder" style=" #position: relative; #top: -50%">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
</body>
</html>
admin:
takeown /r /f folder
cacls folder /c /G "ADMINNAME":F /T
rmdir /s folder
Works for anything including sys files
EDIT: I actually found the best way which also solves file path too long problem as well:
mkdir \empty
robocopy /mir \empty folder
An application does not need to have any registry entry. In fact, many applications do not need to be installed at all. U3 USB sticks are a good example; the programs on them just run from the file system.
As noted, most good applications can be found via their uninstall registry key though. This is actually a pair of keys, per-user and per-machine (HKCU/HKLM - Piskvor mentioned only the HKLM one). It does not (always) give you the install directory, though.
If it's in HKCU, then you have to realise that HKEY_CURRENT_USER
really means "Current User". Other users have their own HKCU entries, and their own installed software. You can't find that. Reading every HKEY_USERS
hive is a disaster on corporate networks with roaming profiles. You really don't want to fetch 1000 accounts from your remote [US|China|Europe] office.
Even if an application is installed, and you know where, it may not have the same "version" notion you have. The best source is the "version" resource in the executables. That's indeed a plural, so you have to find all of them, extract version resources from all and in case of a conflict decid on something reasonable.
So - good luck. There are dozes of ways to fail.
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
For me it seems it was a problem that OpenGL didn't work on my Windows 10 machine. I fixed it as follows:
$()
is the jQuery constructor function.
this
is a reference to the DOM element of invocation.
So basically, in $(this)
, you are just passing the this
in $()
as a parameter so that you could call jQuery methods and functions.
My cause of issue seems very uncommon to me, not sure if anybody else gets the error under same condition, I found the cause by diffing previous commits, here you go :
Via my build.gradle I was using these 2 compiler options, and commenting out this line fixed the issue
//compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']
A Bash function can't return a string directly like you want it to. You can do three things:
This is also true for some other shells.
Here's how to do each of those options:
lockdir="somedir"
testlock(){
retval=""
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval="true"
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval="false"
fi
echo "$retval"
}
retval=$( testlock )
if [ "$retval" == "true" ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
return "$retval"
}
testlock
retval=$?
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
retval=-1
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
}
testlock
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
I have a better solution that inclueds login with your account than changing to root user. It is a bash script
http://felipeferreira.net/index.php/2011/09/ssh-automatic-login/
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
As shown below, range
only supports integers:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
range(int(c/10))
or by using //
, which returns an integer:
range(c//10)
You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.
import React from "react";
const sizeToLetterMap = {
small_square: 's',
large_square: 'q',
thumbnail: 't',
small_240: 'm',
small_320: 'n',
medium_640: 'z',
medium_800: 'c',
large_1024: 'b',
large_1600: 'h',
large_2048: 'k',
original: 'o'
};
class PhotoComponent extends React.Component {
constructor(args) {
super(args);
}
photoUrl(image, size_text) {
return (<span>
Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
</span>);
}
render() {
return (
<div className="photo-wrapper">
The url is: {this.photoUrl(this.props.image, this.props.size_text)}
</div>
)
}
}
export default PhotoComponent;
// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
wget -S -O - http://google.com
works as expected for me, but with a caveat: the headers are considered debugging information and as such they are sent to the standard error rather than the standard output. If you are redirecting the standard output to a file or another process, you will only get the document contents.
You can try redirecting the standard error to the standard output as a possible solution. For example, in bash
:
$ wget -q -S -O - 2>&1 | grep ...
or
$ wget -q -S -O - 1>wget.txt 2>&1
The -q
option suppresses the progress bar and some other annoyingly chatty parts of the wget
output.
You can do this in a couple of ways.
One, is to build up the query yourself and execute it.
SET @sql = 'SELECT ' + @columnName + ' FROM yourTable'
sp_executesql @sql
If you opt for that method, be very certain to santise your input. Even if you know your application will only give 'real' column names, what if some-one finds a crack in your security and is able to execute the SP directly? Then they can execute just about anything they like. With dynamic SQL, always, always, validate the parameters.
Alternatively, you can write a CASE statement...
SELECT
CASE @columnName
WHEN 'Col1' THEN Col1
WHEN 'Col2' THEN Col2
ELSE NULL
END as selectedColumn
FROM
yourTable
This is a bit more long winded, but a whole lot more secure.
$user_agent = 'yandeX';
$bots = ['Google','Yahoo','Yandex'];
foreach($bots as $b){
if( stripos( $user_agent, $b ) !== false ) return $b;
}
window.setTimeout(func,1000);
This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.
This could happen if you are using reflection to GetProperty
of an object which is null.
In case anyone was a tired and silly as I was the other night whereupon I came across many threads espousing the different methods to get a javascript redirect, all of which were failing...
You can't use window.location.replace
or document.location.href
or any of your favourite vanilla javascript methods to redirect a page to itself.
So if you're dynamically adding in the redirect path from the back end, or pulling it from a data tag, make sure you do check at some stage for redirects to the current page. It could be as simple as:
if(window.location.href == linkout)
{
location.reload();
}
else
{
window.location.href = linkout;
}
Note that Boolean
will only work were you have using System;
(which is usually, but not necessarily, included) (unless you write it out as System.Boolean
). bool
does not need using System;
Did you try using t.Text
?
String s = "ASCII Text";
byte[] bytes = s.getBytes("US-ASCII");
View -> Datasets (bottom of menu, above Refresh)
I hate to add the same function to every UIViewController. By extending UIViewController to support UITextFieldDelegate, you can provide a default behavior of "return pressed".
extension UIViewController: UITextFieldDelegate{
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
}
When you create new UIViewController and UITextField, all you have to do is to write one line code in your UIViewController.
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
}
You can even omit this one line code by hooking delegate in Main.storyboard. (Using "ctrl" and drag from UITextField to UIViewController)
Efficient way to iterate your ArrayList
followed by this link. This type will improve the performance of looping during iteration
int size = list.size();
for(int j = 0; j < size; j++) {
System.out.println(list.get(i));
}
I got this error for characters in my comments (from copying/pasting content from the web into my editor for note-taking purposes).
To resolve in Text Wrangler:
My Problem Solved by
public static final String REDIRECT_URI = "http://google.com";
it will redirect to Url after ur Login into Facebook.and also you have to reach
url : https://developers.facebook.com -> My App -> (Select your app) ->Settings ->Advanced Setting -> Valid OAuth redirect URIs : "http://google.com".
In the place of "http://google.com" you can place ur respective project Url.so,that it will redirect to your Page.
while this system does use a for loop, It uses US english and is fast, accurate, and expandable(you can add infinite values to the "th" var and they will be included).
This function grabs the 3 groups of numbers backwards so it can get the number groups where a ,
would normally separate them in the numeric form. Then each group of three numbers is added to an array with the word form of just the 3 numbers(ex: one hundred twenty three). It then takes that new array list, and reverses it again, while adding the th
var of the same index to the end of the string.
var ones = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
var tens = ['', '', 'twenty ','thirty ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
var th = ['', 'thousand ','million ','billion ', 'trillion '];
function numberToWord(number){
var text = "";
var size = number.length;
var textList = [];
var textListCount = 0;
//get each 3 digit numbers
for(var i = number.length-1; i >= 0; i -= 3){
//get 3 digit group
var num = 0;
if(number[(i-2)]){num += number[(i-2)];}
if(number[(i-1)]){num += number[(i-1)];}
if(number[i]){num += number[i];}
//remove any extra 0's from begining of number
num = Math.floor(num).toString();
if(num.length == 1 || num < 20){
//if one digit or less than 20
textList[textListCount] = ones[num];
}else if(num.length == 2){
//if 2 digits and greater than 20
textList[textListCount] = tens[num[0]]+ones[num[1]];
}else if(num.length == 3){
//if 3 digits
textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
}
textListCount++;
}
//add the list of 3 digit groups to the string
for(var i = textList.length-1; i >= 0; i--){
if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
}
return text;
}
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex
contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex:
to delete the last character correctly.
$(this).bind('input propertychange', function() {
//your code here
});
This is works for typing, paste, right click mouse paste etc.
In python version >= 2.7 and in python 3:
d = {el:0 for el in a}
You could use --merge
/-m
git checkout
option:
git checkout -m <another-branch>
-m --merge
When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.
Probably the new PyCharm from the makers of IntelliJ and ReSharper.
I had a bunch of FKs to alter, so I wrote something to make the statements for me. Figured I'd share:
SELECT
CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
'` DROP FOREIGN KEY `' ,rc.CONSTRAINT_NAME,'`;')
, CONCAT('ALTER TABLE `' ,rc.TABLE_NAME,
'` ADD CONSTRAINT `' ,rc.CONSTRAINT_NAME ,'` FOREIGN KEY (`',kcu.COLUMN_NAME,
'`) REFERENCES `',kcu.REFERENCED_TABLE_NAME,'` (`',kcu.REFERENCED_COLUMN_NAME,'`) ON DELETE CASCADE;')
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
ON kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
WHERE DELETE_RULE = 'NO ACTION'
AND rc.CONSTRAINT_SCHEMA = 'foo'
If you don't want to copy the whole tree (with subdirs etc), use or glob.glob("path/to/dir/*.*")
to get a list of all the filenames, loop over the list and use shutil.copy
to copy each file.
for filename in glob.glob(os.path.join(source_dir, '*.*')):
shutil.copy(filename, dest_dir)
For me this single line solution works very well
XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument
If you are looking for a scripted solution:
.vsix
files (see example below)unzip
the binary into ~/.vscode/extensions/
: you need to modify unzipped directory name, remove one file and move/rename another one.For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.
POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json
{
"filters": [
{
"criteria": [
{
"filterType": 8,
"value": "Microsoft.VisualStudio.Code",
},
{
"filterType": 7,
"value": "ms-python.python",
}
],
"pageNumber": 1,
"pageSize": 10,
"sortBy": 0,
"sortOrder": 0,
}
],
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
"flags": 514,
}
Explanations to the above example:
"filterType": 8
- FilterType.Target
more FilterTypes"filterType": 7
- FilterType.ExtensionName
more FilterTypes"flags": 514
- 0x2 | 0x200
- Flags.IncludeFiles | Flags.IncludeLatestVersionOnly
- more Flags
python -c "print(0x2|0x200)"
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"]
- to get only link to .vsix
file more AssetTypesYou mean menu Project -> Generate Javadoc ?
Try to understand the difference between a normal def defined function and lambda function. This is a program that returns the cube of a given value:
# Python code to illustrate cube of a number
# showing difference between def() and lambda().
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
# using the normally
# defined function
print(cube(5))
# using the lamda function
print(lambda_cube(5))
output:
125
125
Without using Lambda:
Using Lambda:
Lambda functions can be used along with built-in functions like filter()
, map()
and reduce()
.
The filter()
function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True
.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
ages = [13, 90, 17, 59, 21, 60, 5]
adults = list(filter(lambda age: age>18, ages))
print(adults) # above 18 yrs
output:
[4, 6, 8, 12]
[90, 59, 21, 60]
The map()
function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
cities = ['novi sad', 'ljubljana', 'london', 'new york', 'paris']
# change all city names
# to upper case and return the same
uppered_cities = list(map(lambda city: str.upper(city), cities))
print(uppered_cities)
output:
[2, 10, 8, 12, 16, 22, 6, 24]
['NOVI SAD', 'LJUBLJANA', 'LONDON', 'NEW YORK', 'PARIS']
reduce()
works differently than map()
and filter()
. It does not return a new list based on the function
and iterable we've passed. Instead, it returns a single value.
Also, in Python 3 reduce()
isn't a built-in function anymore, and it can be found in the functools
module.
The syntax is:
reduce(function, sequence[, initial])
reduce()
works by calling the function
we passed for the first two items in the sequence. The result returned by the function
is used in another call to function
alongside with the next (third in this case), element.
The optional argument initial
is used, when present, at the beginning of this "loop" with the first element in the first call to function
. In a way, the initial
element is the 0th element, before the first one, when provided.
The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and an iterable and a new reduced result is returned. This performs a repetitive operation over the pairs of the iterable.
from functools import reduce
my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34]
sum = reduce((lambda x, y: x + y), my_list)
print(sum) # sum of a list
print("With an initial value: " + str(reduce(lambda x, y: x + y, my_list, 100)))
88
With an initial value: 188
These functions are convenience functions. They are there so you can avoid writing more cumbersome code, but avoid using both them and lambda expressions too much, because "you can", as it can often lead to illegible code that's hard to maintain. Use them only when it's absolutely clear what's going on as soon as you look at the function or lambda expression.
Convert Double
to Float
public static Float convertToFloat(Double doubleValue) {
return doubleValue == null ? null : doubleValue.floatValue();
}
Convert double
to Float
public static Float convertToFloat(double doubleValue) {
return (float) doubleValue;
}
Here's a list of languages that can be used to develop on android:
Java - primary android development language
Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017
C++ - NDK for libraries, not apps
Python, bash, et. al. - Via the Scripting Environment
Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.
Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java
Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.
As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.
I'm pretty sure you should go with bar();
because with foo();
it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!
Could use CASE WHEN
to leave those with no ';' alone.
SELECT
CASE WHEN CHARINDEX(';', MyText) > 0 THEN
LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
MyText END
FROM MyTable
Find complete example of Spring Mvc Validation
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.technicalkeeda.bean.Login;
public class LoginValidator implements Validator {
public boolean supports(Class aClass) {
return Login.class.equals(aClass);
}
public void validate(Object obj, Errors errors) {
Login login = (Login) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
"username.required", "Required field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPassword",
"userpassword.required", "Required field");
}
}
public class LoginController extends SimpleFormController {
private LoginService loginService;
public LoginController() {
setCommandClass(Login.class);
setCommandName("login");
}
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
@Override
protected ModelAndView onSubmit(Object command) throws Exception {
Login login = (Login) command;
loginService.add(login);
return new ModelAndView("loginsucess", "login", login);
}
}
Remove:
httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');
... and add:
httpRequest.withCredentials = false;
Code to delete an entry from the list
/*--dialog for delete entry--*/
private void cancelBookingAlert() {
AlertDialog dialog;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
alertDialog.setTitle("Delete Entry");
alertDialog.setMessage("Are you sure you want to delete this entry?");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//code to delete entry
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = alertDialog.create();
dialog.show();
}
Call above method on delete button click
You don't specify what kind of list, but the generic List can use either the RemoveAt(index)
method, or the Remove(obj)
method:
// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);
// RemoveAt(index)
resultList.RemoveAt(1);
Thanks to Aaron for pointing out that it's about locating the views, I misunderstood that.
[UPDATE] I just created a project that sends the user to an Area per default without messing with any of the code or lookup paths:
In global.asax, register as usual:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""} // Parameter defaults,
);
}
in Application_Start()
, make sure to use the following order;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
in you area registration, use
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ShopArea_default",
"{controller}/{action}/{id}",
new { action = "Index", id = "", controller = "MyRoute" },
new { controller = "MyRoute" }
);
}
An example can be found at http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/
I really hope that this is what you were asking for...
////
I don't think that writing a pseudo ViewEngine
is the best solution in this case. (Lacking reputation, I can't comment). The WebFormsViewEngine
is Area aware and contains AreaViewLocationFormats
which is defined per default as
AreaViewLocationFormats = new[] {
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
};
I believe you don't adhere to this convention. You posted
public ActionResult ActionY()
{
return View("~/Areas/AreaZ/views/ActionY.aspx");
}
as a working hack, but that should be
return View("~/Areas/AreaZ/views/ControllerX/ActionY.aspx");
IF you don't want to follow the convention, however, you might want to take a short path by either deriving from the WebFormViewEngine
(that is done in MvcContrib, for example) where you can set the lookup paths in the constructor, or -a little hacky- by specifying your convention like this on Application_Start
:
((VirtualPathProviderViewEngine)ViewEngines.Engines[0]).AreaViewLocationFormats = ...;
This should be performed with a little more care, of course, but I think it shows the idea. These fields are public
in VirtualPathProviderViewEngine
in MVC 2 RC.
I know that is a old question, but...
You can also use this in your class:
@Autowired
private HttpServletRequest context;
And this will provide the current instance of HttpServletRequest
for you use on your method.
drand48(3)
is the POSIX standard way. GLibC also provides a reentrant version, drand48_r(3)
.
The function was declared obsolete in SVID 3 but no adequate alternative was provided so IEEE Std 1003.1-2013 still includes it and has no notes that it's going anywhere anytime soon.
In Windows, the standard way is CryptGenRandom().
This should work:
System.currentTimeMillis();
Before proceeding:
Install a proper mergetool. On Linux, I strongly suggest you to use meld:
sudo apt-get install meld
Configure your mergetool:
git config --global merge.tool meld
Then, iterate in the following way:
git cherry-pick ....
git mergetool
git cherry-pick --continue
You just try this, Its so easy
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
It is unable to auto-detect email address.
By default it takes your system username like [email protected]
.
So you need to set your email like below:
git config user.email "[email protected]"
After setting email you can run the git commands and commit your changes.
Simple. Text-align: justify; (to get the elements aligned) Padding-left: ?px; (to center the elements)
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
Here is a little improvement for Smilediver's answer, it will not escape all no-ASCII chars but only these are really needed.
using System;
using System.Globalization;
using System.Text;
public static class CodeHelper
{
public static string ToLiteral(this string input)
{
var literal = new StringBuilder(input.Length + 2);
literal.Append("\"");
foreach (var c in input)
{
switch (c)
{
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:
if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)
{
literal.Append(c);
}
else
{
literal.Append(@"\u");
literal.Append(((ushort)c).ToString("x4"));
}
break;
}
}
literal.Append("\"");
return literal.ToString();
}
}
By the RFC7231 it does not matter and may be empty
How we implement json api standard based solution in the project:
post/put: outputs object attributes as in get (field filter/relations applies the same)
delete: data only contains null (for its a representation of missing object)
status for standard delete: 200
So I am not sure I can really think of why you would actually need a "site collection unique" id, so maybe you can comment and let us know what is actually trying to be accomplished here...
Either way, all items have a UniqueID property that is a GUID if you really need it: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.uniqueid.aspx
You could apply position: relative;
to the div and then position: absolute; top: 0;
to a paragraph or span inside of it containing the text.
This can as well be triggered by having both input
and label
inside the element with click listener.
You click on the label
, which triggers a click event and as well another click event on the input
for the label
. Both events bubble to your element.
See this pen of a fancy CSS-only toggle: https://codepen.io/stepanh/pen/WaYzzO
Note: This is not jQuery specific, native listener is triggered 2x as well as shown in the pen.
I got the problem when instelled MS SQL 2012
with IngegrationService
, the MS Visual Studio 2010 (Isolated) was installed from sql installer .
This VS returned error: Invalid license data. Reinstall is required.
I've fixed the problem by reinstalling SSDT with MS VS 2012 (Integrated) http://msdn.microsoft.com/en-us/jj650015
Thought to add this here in case someone finds it useful. @ostrokach already mentioned how you can merge the data frames across rows which is
df_row_merged = pd.concat([df_a, df_b], ignore_index=True)
To merge across columns, you can use the following syntax:
df_col_merged = pd.concat([df_a, df_b], axis=1)
If you have a really big file, and assuming you want the output to be a numpy array, using np.genfromtxt will freeze your computer. This is so much better in my experience:
def load_big_file(fname,maxrows):
'''only works for well-formed text file of space-separated doubles'''
rows = [] # unknown number of lines, so use list
with open(fname) as f:
j=0
for line in f:
if j==maxrows:
break
else:
line = [float(s) for s in line.split()]
rows.append(np.array(line, dtype = np.double))
j+=1
return np.vstack(rows) # convert list of vectors to array
The jQuery documentation recommends doing something like the following:
$( document ).ajaxStart(function() {
$( "#loading" ).show();
}).ajaxStop(function() {
$( "#loading" ).hide();
});
Where #loading
is the element with your busy indicator in it.
References:
In addition, jQuery.ajaxSetup
API explicitly recommends avoiding jQuery.ajaxSetup
for these:
Note: Global callback functions should be set with their respective global Ajax event handler methods—
.ajaxStart()
,.ajaxStop()
,.ajaxComplete()
,.ajaxError()
,.ajaxSuccess()
,.ajaxSend()
—rather than within theoptions
object for$.ajaxSetup()
.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
You can use PyInstaller. It generates a build dist so you can execute it as a single "binary" file.
http://pythonhosted.org/PyInstaller/#using-pyinstaller
Python 3 has the native option of create a build dist also:
I was having the same issue till just now; just as you mentioned, I tried "Connect As" and the username and password that I wrote down, was my machine's user (IIS is running on this machine), I tested the connection and it works now. Maybe if you weren't using that machine's user (try user with administrator privileges), you should give it a try, it worked for me, it may work in your case as well.
raw_input
can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
If you want to have sql-like syntax you can just make use of sqldf
package. Tthe function to be used is also names sqldf
and the syntax is as follows
sqldf(<your query in quotation marks>)
I had this problem cause i had already origin remote defined locally. So just change "origin" into another name:
git remote add originNew https://github.com/UAwebM...
git push -u originNew
or u can remove your local origin. to check your remote name type:
git remote
to remove remote - log in your clone repository and type:
git remote remove origin(depending on your remote's name)
Please note that when plotting a line chart, using =NA() (output #N/A) to avoid plotting non existing values will only work for the ends of each series, first and last values. Any #N/A in between two other values will be ignored and bridged.
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.
I did the following :
I would not build or clean build it. Hope that helps you out.
allernhwkim originally posted an answer on this question linking to his blog, however a moderator deleted it. It's the only post I've found which doesn't just tell you how to do the same thing with service, provider and factory, but also tells you what you can do with a provider that you can't with a factory, and with a factory that you can't with a service.
Directly from his blog:
app.service('CarService', function() {
this.dealer="Bad";
this.numCylinder = 4;
});
app.factory('CarFactory', function() {
return function(numCylinder) {
this.dealer="Bad";
this.numCylinder = numCylinder
};
});
app.provider('CarProvider', function() {
this.dealerName = 'Bad';
this.$get = function() {
return function(numCylinder) {
this.numCylinder = numCylinder;
this.dealer = this.dealerName;
}
};
this.setDealerName = function(str) {
this.dealerName = str;
}
});
This shows how the CarService will always a produce a car with 4 cylinders, you can't change it for individual cars. Whereas CarFactory returns a function so you can do new CarFactory
in your controller, passing in a number of cylinders specific to that car. You can't do new CarService
because CarService is an object not a function.
The reason factories don't work like this:
app.factory('CarFactory', function(numCylinder) {
this.dealer="Bad";
this.numCylinder = numCylinder
});
And automatically return a function for you to instantiate, is because then you can't do this (add things to the prototype/etc):
app.factory('CarFactory', function() {
function Car(numCylinder) {
this.dealer="Bad";
this.numCylinder = numCylinder
};
Car.prototype.breakCylinder = function() {
this.numCylinder -= 1;
};
return Car;
});
See how it is literally a factory producing a car.
The conclusion from his blog is pretty good:
In conclusion,
--------------------------------------------------- | Provider| Singleton| Instantiable | Configurable| --------------------------------------------------- | Factory | Yes | Yes | No | --------------------------------------------------- | Service | Yes | No | No | --------------------------------------------------- | Provider| Yes | Yes | Yes | ---------------------------------------------------
Use Service when you need just a simple object such as a Hash, for example {foo;1, bar:2} It’s easy to code, but you cannot instantiate it.
Use Factory when you need to instantiate an object, i.e new Customer(), new Comment(), etc.
Use Provider when you need to configure it. i.e. test url, QA url, production url.
If you find you're just returning an object in factory you should probably use service.
Don't do this:
app.factory('CarFactory', function() {
return {
numCylinder: 4
};
});
Use service instead:
app.service('CarService', function() {
this.numCylinder = 4;
});
CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.
I know this is an old question but here is the solution I found to a very similar coding issue in my own code:
var response = ApiDB.Persons.Include(y => y.JobTitle).Include(b => b.Discipline).Include(b => b.Team).Include(b => b.Site).OrderBy(d => d.DisplayName).ToArray();
foreach (var person in response)
{
person.JobTitle = new JobTitle()
{
JobTitle_ID = person.JobTitle.JobTitle_ID,
JobTitleName = person.JobTitle.JobTitleName,
PatientInteraction = person.JobTitle.PatientInteraction,
Active = person.JobTitle.Active,
IsClinical = person.JobTitle.IsClinical
};
}
Since the person object contains everything from the person table and the job title object contains a list of persons with that job title, the database kept self referencing. I thought disabling proxy creation and lazy loading would fix this but unfortunately it didn't.
For the that aren't able to do that, try the solution above. Explicitly creating a new object for each object that self references, but leave out the list of objects or object that goes back to the previous entity will fix it since disabling lazy loading does not appear to work for me.
As described here: Angular NgModelController, you should provide the <input
with the required controller ngModel
<input submit-required="true" ng-model="user.Name"></input>
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:
The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.
Feel free to use my plugin for your project: :)
https://github.com/leoselig/jsFancyScroll/
I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!
I haven’t actually done anything with font-face
, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.
The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.
Does Firefox download the font when you actually use it in a font
declaration? (e.g. h1 { font: 'DejaVu Serif';
)?
Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.
In vim type
:help vimrc
and check your path to the _vimrc/.vimrc file with
:echo $HOME
:echo $VIM
Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.
:help source
This is a variation of something I learned several years back. Apparently, this is popular with C++ developers.
First off, I think I know why you want to break out of IF blocks. For me, I don't like a bunch of nested blocks because 1) it makes the code look messy and 2) it can be a pia to maintain if you have to move logic around.
Consider a do/while
loop instead:
public void Method()
{
bool something = true, something2 = false;
do
{
if (!something) break;
if (something2) break;
} while (false);
}
The do/while
loop is guaranteed to run only once just like an IF block thanks to the hardcoded false
condition. When you want to exit early, just break
.
$(document).ready( function(){
$("button").click(function(){
$("p").toggle(1000,'linear');
});
});
I use this method to solve the problem:
sudo chown -R mongodb:mongodb /data/db
wget -S -i *file*
will get you the headers from each url in a file.
Filter though grep
for the status code specifically.
Swift example that actually works:
switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
println("iOS >= 8.0")
case .OrderedAscending:
println("iOS < 8.0")
}
Don't use NSProcessInfo cause it doesn't work under 8.0, so its pretty much useless until 2016
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
<form class="form-horizontal" method="post">
<div class="control-group">
<input type="text" name="subject_code" id="inputEmail" placeholder="Subject Code">
</div>
<div class="control-group">
<input type="text" class="span8" name="title" id="inputPassword" placeholder="Subject Title" required>
</div>
<div class="control-group">
<input type="text" class="span1" name="unit" id="inputPassword" required>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Semester</label>
<div class="controls">
<select name="semester">
<option></option>
<option>1st</option>
<option>2nd</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Deskripsi</label>
<div class="controls">
<textarea name="description" id="ckeditor_full"></textarea>
<script>CKEDITOR.replace('ckeditor_full');</script>
</div>
</div>
<div class="control-group">
<div class="controls">
<button name="save" type="submit" class="btn btn-info"><i class="icon-save"></i> Simpan</button>
</div>
</div>
</form>
<?php
if (isset($_POST['save'])){
$subject_code = $_POST['subject_code'];
$title = $_POST['title'];
$unit = $_POST['unit'];
$description = $_POST['description'];
$semester = $_POST['semester'];
$query = mysql_query("select * from subject where subject_code = '$subject_code' ")or die(mysql_error());
$count = mysql_num_rows($query);
if ($count > 0){ ?>
<script>
alert('Data Sudah Ada');
</script>
<?php
}else{
mysql_query("insert into subject (subject_code,subject_title,description,unit,semester) values('$subject_code','$title','$description','$unit','$semester')")or die(mysql_error());
mysql_query("insert into activity_log (date,username,action) values(NOW(),'$user_username','Add Subject $subject_code')")or die(mysql_error());
?>
<script>
window.location = "subjects.php";
</script>
<?php
}
}
?>
Try this. I purposely broke out various parts so you can move things around.
library(sfsmisc)
#Generate the data
x <- 1:100000
y <- 1:100000
#Setup the plot area
par(pty="m", plt=c(0.1, 1, 0.1, 1), omd=c(0.1,0.9,0.1,0.9))
#Plot a blank graph without completing the x or y axis
plot(x, y, type = "n", xaxt = "n", yaxt="n", xlab="", ylab="", log = "x", col="blue")
mtext(side=3, text="Test Plot", line=1.2, cex=1.5)
#Complete the x axis
eaxis(1, padj=-0.5, cex.axis=0.8)
mtext(side=1, text="x", line=2.5)
#Complete the y axis and add the grid
aty <- seq(par("yaxp")[1], par("yaxp")[2], (par("yaxp")[2] - par("yaxp")[1])/par("yaxp")[3])
axis(2, at=aty, labels=format(aty, scientific=FALSE), hadj=0.9, cex.axis=0.8, las=2)
mtext(side=2, text="y", line=4.5)
grid()
#Add the line last so it will be on top of the grid
lines(x, y, col="blue")
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
It can be as simple as:
default_data['item3'] = 3
As Chris' answer says, you can use update to add more than one item. An example:
default_data.update({'item4': 4, 'item5': 5})
Please see the documentation about dictionaries as data structures and dictionaries as built-in types.
The RestTemplate
instance has to be a real object. It should work if you create a real instance of RestTemplate
and make it @Spy
.
@Spy
private RestTemplate restTemplate = new RestTemplate();
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
You can use the beforeSend
callback to set additional parameters (The XMLHTTPRequest
object is passed to it as its only parameter).
Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:
$.ajax({
url: 'http://bar.other',
data: { whatever:'cool' },
type: 'GET',
beforeSend: function(xhr){
xhr.withCredentials = true;
}
});
One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).
The way to use mysplit.bat
below is
mysplit.bat <mysize> 'myfile'
Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.
Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.
Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.
Script mysplit.bat
:
@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell ^
$upperBound = 100MB; ^
$rootName = %2; ^
$from = $rootName; ^
$fromFile = [io.file]::OpenRead($from); ^
$buff = new-object byte[] $upperBound; ^
$count = $idx = 0; ^
try { ^
do { ^
'Reading ' + $upperBound; ^
$count = $fromFile.Read($buff, 0, $buff.Length); ^
if ($count -gt 0) { ^
$to = '{0}.{1}' -f ($rootName, $idx); ^
$toFile = [io.file]::OpenWrite($to); ^
try { ^
'Writing ' + $count + ' to ' + $to; ^
$tofile.Write($buff, 0, $count); ^
} finally { ^
$tofile.Close(); ^
} ^
} ^
$idx ++; ^
} while ($count -gt 0); ^
} ^
finally { ^
$fromFile.Close(); ^
} ^
%End PowerShell%
Here's my solution:
String s = Integer.toBinaryString(5); //Convert decimal to binary
int p = 8; //preferred length
for(int g=0,j=s.length();g<p-j;g++, s= "0" + s);
System.out.println(s);
Output: 00000101
foreach (DataRow row in DataRow row in GridView1.Rows)
{
foreach (DataColumn c in GridView1.Columns)
bool ckbVal = (bool)(row[c.ColumnName]);
}
What have you tried, what was the problem?
Creating DataColumns
and add values to a DataTable
is straight forward:
Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
dt.Rows.Add(i, "Row #" & i)
Next
Edit:
If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml
.
I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg
Try this instead:
<img src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />
UPDATE:
I don't know what your $PROJECTHOME
is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.
Then in your HTML you can simply reference the image within the images folder relative to the site, like so:
<img src="images/66.jpg" width="400" height="400" />
Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):
<img src="/images/66.jpg" width="400" height="400" />
The generally excellent C5 Generic Collection Library has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven't used any of the tree structures specifically.)
There isn't currently a better way to do it than Ctrl+C in the terminal.
We're thinking about how to have an explicit shutdown, but there's some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We haven't quite worked out how to handle the differences yet.
(For future readers, this is the situation with 0.12 released and 0.13 in development.)
Update December 2017
The IPython Notebook has become the Jupyter Notebook. A recent version has added a jupyter notebook stop
shell command which will shut down a server running on that system. You can pass the port number at the command line if it's not the default port 8888.
You can also use nbmanager, a desktop application which can show running servers and shut them down.
Finally, we are working on adding:
I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"
This will fix your connection to your database.
This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.
I hope this helps you out.
:)
The command should be the following script:
ilmerge myExe.exe Dll1.dll /target:winexe /targetplatform:"v4,c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\" /out:merged.exe /out:merged.exe
Rather than mess with the encode and decode methods I find it easier to specify the encoding when opening the file. The io
module (added in Python 2.6) provides an io.open
function, which has an encoding parameter.
Use the open method from the io
module.
>>>import io
>>>f = io.open("test", mode="r", encoding="utf-8")
Then after calling f's read() function, an encoded Unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
Note that in Python 3, the io.open
function is an alias for the built-in open
function. The built-in open function only supports the encoding argument in Python 3, not Python 2.
Edit: Previously this answer recommended the codecs module. The codecs module can cause problems when mixing read()
and readline()
, so this answer now recommends the io module instead.
Use the open method from the codecs module.
>>>import codecs
>>>f = codecs.open("test", "r", "utf-8")
Then after calling f's read() function, an encoded Unicode object is returned.
>>>f.read()
u'Capit\xe1l\n\n'
If you know the encoding of a file, using the codecs package is going to be much less confusing.
We can do this with one queue:
push:
n
is the number of elements in the queue, then remove and insert element n-1
times.pop:
.
push 1
front
+----+----+----+----+----+----+
| 1 | | | | | | insert 1
+----+----+----+----+----+----+
push2
front
+----+----+----+----+----+----+
| 1 | 2 | | | | | insert 2
+----+----+----+----+----+----+
front
+----+----+----+----+----+----+
| | 2 | 1 | | | | remove and insert 1
+----+----+----+----+----+----+
insert 3
front
+----+----+----+----+----+----+
| | 2 | 1 | 3 | | | insert 3
+----+----+----+----+----+----+
front
+----+----+----+----+----+----+
| | | 1 | 3 | 2 | | remove and insert 2
+----+----+----+----+----+----+
front
+----+----+----+----+----+----+
| | | | 3 | 2 | 1 | remove and insert 1
+----+----+----+----+----+----+
Sample implementation:
int stack_pop (queue_data *q)
{
return queue_remove (q);
}
void stack_push (queue_data *q, int val)
{
int old_count = queue_get_element_count (q), i;
queue_insert (q, val);
for (i=0; i<old_count; i++)
{
queue_insert (q, queue_remove (q));
}
}
You can use the function getBBox() to get the bounding box for the path. This will give you the position and size of the tightest rectangle that could contain the rendered path.
An advantage of using this method over reading the x and y values is that it will work with all graphical objects. There are more objects than paths that do not have x and y, for example circles that have cx and cy instead.
List<T>
has a Reverse()
method, however it only reverses the order of two (or more) consecutive items.
your_list.Reverse(index, 2);
Where the second parameter 2
indicates we are reversing the order of 2 items, starting with the item at the given index
.
Source: https://msdn.microsoft.com/en-us/library/hf2ay11y(v=vs.110).aspx
You are calling the ready function before the jQuery JavaScript is included. Reference jQuery first.
Your code works for me on Chrome (5.0.375), and Safari (5.0). Doesn't loop on Firefox (3.6).
var song = new Audio("file");
song.loop = true;
document.body.appendChild(song);?
There is no need to use the classpath: protocol in your schemaLocation URL if the namespace is configured correctly and the XSD file is on your classpath.
Spring doc "Registering the handler and the schema" shows how it should be done.
In your case, the problem was probably that the spring-context jar on your classpath was not 2.1. That was why changing the protocol to classpath: and putting the specific 2.1 XSD in your classpath fixed the problem.
From what I've seen, there are 2 schemas defined for the main XSD contained in a spring-* jar. Once to resolve the schema URL with the version and once without it.
As an example see this part of the spring.schemas contents in spring-context-3.0.5.RELEASE.jar:
http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd
http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd
http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.0.xsd
This means that (in xsi:schemaLocation)
http://www.springframework.org/schema/context/spring-context-2.5.xsd
will be validated against
org/springframework/context/config/spring-context-2.5.xsd
in the classpath.
http://www.springframework.org/schema/context/spring-context-3.0.xsd
or
http://www.springframework.org/schema/context/spring-context.xsd
will be validated against
org/springframework/context/config/spring-context-3.0.xsd
in the classpath.
http://www.springframework.org/schema/context/spring-context-2.1.xsd
is not defined so Spring will look for it using the literal URL defined in schemaLocation.
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
Android and iOS body only:
<a href="sms://;?&body=Hello%20World">Only body</a>
Android and iOS one recipient only with body:
<a href="sms://+15552345678;?&body=Hello%20World">one recipient only with body</a>
Only Android multiple recipients with body:
<a href="sms://+15552345678, +15552345679;?&body=Hello%20World">Android multiple recipients with body</a>
Only iOS multiple recipients with body:
<a href="sms://open?addresses=+15552345678,+15552345679;?&body=Hello%20World">iOS multiple recipients with body</a>
Note that the body should be URI encoded.
For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.
Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.
Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.
Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.
Something along the following in a plugin file is what you are looking for:
<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI:
Plugin URI:
*/
function $yourJS() {
wp_enqueue_script(
'custom_script',
plugins_url( '/js/your-script.js', __FILE__ ),
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', '$yourJS' );
add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );
function prefix_add_my_stylesheet() {
wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
wp_enqueue_style( 'prefix-style' );
}
?>
Structure your folders as follows:
Plugin Folder
|_ css folder
|_ js folder
|_ plugin.php ...contains the above code - modified of course ;D
Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.
For me, on a mac, it turned out I had an old VirtualBox image stored on my machine that didn't have metadata, so it wasn't being updated to the latest version.
That old image had an older version of the vbguest plugin installed in it, which the newer vbguest plugin on my machine couldn't work with.
So to fix it, I just removed the image that my Vagrant was based on, and then Vagrant downloaded the newer version and it worked fine.
# Remove an old version of the virtual box image that my vagrant was using
$ vagrant box remove centos/7
You can find out which boxes you have cached on your machine by running:
$ vagrant box list
I had also upgraded my vbguest plugin in my earlier attempts at getting this to work, using the following process, but I don't think this helped. FYI !
# Get rid of old plugins
vagrant plugin expunge
# Globally install the latest version of the vbguest plugin`
vagrant plugin install vagrant-vbguest
If you find bring the box fails on guest addtions, you can try doing the following to ensure the plugins install correctly. This downloads the latest based image for your system (for me CentOS), and may resolve the issue (it did for me!)
$ vagrant box update
In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.
SELECT ISNUMERIC('2.81104e+006')
returns 1
.
SELECT convert(decimal(15,2), '2.81104e+006')
returns
error: Error converting data type varchar to numeric.
And
SELECT try_convert(decimal(15,2), '2.81104e+006')
returns NULL
.
SELECT convert(float, '2.81104e+006')
returns the correct value 2811040
.
You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.
1 select 'ABC_blahblahblah' test_string,
2 instr('ABC_blahblahblah','_',1,1) position_underscore,
3 substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
4* from dual
SQL> /
TEST_STRING POSITION_UNDERSCORE RES
---------------- ------------------ ---
ABC_blahblahblah 4 ABC
Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.
In the case of the first block:
filecontent()
{
setGUI();
setRegister();
showfile();
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
You would have to include a try catch block:
filecontent()
{
setGUI();
setRegister();
try {
showfile();
}
catch (IOException e) {
// Do something here
}
setTitle("FileData");
setVisible(true);
setSize(300, 300);
/*
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
*/
}
In the case of the second:
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == submit)
{
showfile();
}
}
You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==submit)
{
try {
showfile();
}
catch (IOException e) {
// Do something here
}
}
}
Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.
If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.
The easiest way to implement the download is that you direct users to the file location, browsers will do that for you automatically.
You can easily achieve it through:
HttpServletResponse.sendRedirect()
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
This solution works fine, but if you change the caching strategy of the ListView away from the default value it stops working. It works if you new up your ListView like this:
listView = new ListView() { ... };
But if you do this it does not work (the background stays grey for the selected item):
listView = new ListView(cachingStrategy:ListViewCachingStrategy.RecycleElement) { ... };
Below is a solution that works even with a non-standard cachingStrategy. I prefer this to other solutions like having code in the OnItemSelected method coupled with a binding from the ViewModel for the background color.
Credit to @Lang_tu_bi_dien who posted the idea here: Listview Selected Item Background Color
The final code then looks like this:
Xamarin.Forms code:
namespace MyProject
{
public class ListView2 : ListView
{
public ListView2(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
{
}
}
}
XAML on your page:
<ListView2 x:Name="myListView" ListViewCachingStrategy="RecycleElement" ItemsSource="{Binding ListSource}" RowHeight="50">_x000D_
<ListView.ItemTemplate>_x000D_
<DataTemplate>_x000D_
<ViewCell>_x000D_
<ViewCell.View>_x000D_
<Label Text="{Binding Name}" HorizontalOptions="Center" TextColor="White" />_x000D_
</ContentView>_x000D_
</ViewCell.View>_x000D_
</ViewCell>_x000D_
</DataTemplate>_x000D_
</ListView.ItemTemplate>_x000D_
</ListView2>
_x000D_
iOS-specific renderer:
[assembly: ExportRenderer(typeof(ListView2), typeof(ListView2Renderer))]
namespace MyProject.iOS
{
public partial class ListView2Renderer : ListViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);
if (Control != null && e != null)
{
//oldDelegate = (UITableViewSource)Control.Delegate;
Control.Delegate = new ListView2Delegate(e.NewElement);
}
}
}
class ListView2Delegate : UITableViewDelegate
{
private ListView _listView;
internal ListView2Delegate(ListView listView)
{
_listView = listView;
}
public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath)
{
cell.SelectedBackgroundView = new UIView()
{
BackgroundColor = Color.Red.ToUIColor()
};
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_listView = null;
}
base.Dispose(disposing);
}
}
}
Note: you may run into some issues due to the fact that you are replacing the default delegate, for more info on this see Setting delegate of control in custom renderer results in lost functionality. In my project it all works as it should if I do this:
Use the normal ListView together with the ListItemViewCellRenderer code given in in the earlier posts on this thread for ListViews that use the default caching strategy ListViewCachingStrategy.RetainElement.
Use this ListView2 together for ListViews that use a non-default caching strategy i.e. ListViewCachingStrategy.RecycleElement or ListViewCachingStrategy.RecycleElementAndDataTemplate.
I am also filing a feature request with Xamarin, please upvote it if you feel this should be added to the standard ListView: ListView desperately needs a SelectedItemBackgroundColor property
I was extending a DialogFragment and the above answer didnot work. I had to use getDialog() to achieve remove the title:
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER …
to \gexec
.
SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec
echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql
See accepted answer there for more details.
Below code will count Message from 0 to 137 each 0.3 second replacing previous number.
Number of symbol to backstage = number of digits.
stream = sys.stdout
for i in range(137):
stream.write('\b' * (len(str(i)) + 10))
stream.write("Message : " + str(i))
stream.flush()
time.sleep(0.3)
In pre-clean phase I execute with Maven Unlocker program. This program unlock all files and directory for anyone program.
I execute this with maven-antrun-plugin and only in windows systems
<profile>
<activation>
<os>
<family>windows</family>
</os>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>pre-clean</phase>
<configuration>
<tasks>
<exec dir="${project.build.directory}" executable="cmd" failonerror="false">
<arg value="Unlocker.exe" />
<arg value="/S" />
</exec>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
It's taking the ID , dividing it by 2 and checking if the remainder is not zero; meaning, it's an odd ID.
You can have it this way:
It is important to mind the commas after each struct item or set of items.
earnings := []LineItemsType{
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
LineItemsType{
TypeName: "Earnings",
Totals: 0.0,
HasTotal: true,
items: []LineItems{
LineItems{
name: "Basic Pay",
amount: 100.0,
},
LineItems{
name: "Commuter Allowance",
amount: 100.0,
},
},
},
}
Hmmm...
As Darin said, you can specify a higher connection timeout value, but I doubt that's really the issue.
When you get connection timeouts, it's typically a problem with one of the following:
Network configuration - slow connection between your web server/dev box and the SQL server. Increasing the timeout may correct this, but it'd be wise to investigate the underlying problem.
Connection string. I've seen issues where an incorrect username/password will, for some reason, give a timeout error instead of a real error indicating "access denied." This shouldn't happen, but such is life.
Connection String 2: If you're specifying the name of the server incorrectly, or incompletely (for instance, mysqlserver
instead of mysqlserver.webdomain.com
), you'll get a timeout. Can you ping the server using the server name exactly as specified in the connection string from the command line?
Connection string 3 : If the server name is in your DNS (or hosts file), but the pointing to an incorrect or inaccessible IP, you'll get a timeout rather than a machine-not-found-ish error.
The query you're calling is timing out. It can look like the connection to the server is the problem, but, depending on how your app is structured, you could be making it all the way to the stage where your query is executing before the timeout occurs.
Connection leaks. How many processes are running? How many open connections? I'm not sure if raw ADO.NET performs connection pooling, automatically closes connections when necessary ala Enterprise Library, or where all that is configured. This is probably a red herring. When working with WCF and web services, though, I've had issues with unclosed connections causing timeouts and other unpredictable behavior.
Things to try:
Do you get a timeout when connecting to the server with SQL Management Studio? If so, network config is likely the problem. If you do not see a problem when connecting with Management Studio, the problem will be in your app, not with the server.
Run SQL Profiler, and see what's actually going across the wire. You should be able to tell if you're really connecting, or if a query is the problem.
Run your query in Management Studio, and see how long it takes.
Good luck!
I'm using:
li {_x000D_
margin: 0;_x000D_
padding: 36px 0 36px 84px;_x000D_
list-style: none;_x000D_
background-image: url("../../images/checked_red.svg");_x000D_
background-repeat: no-repeat;_x000D_
background-position: left center;_x000D_
background-size: 40px;_x000D_
}
_x000D_
where background-size set the background image size.
While using the date formats, you may want to keep in mind to always use MM
for months and mm
for minutes. That should resolve your problem.
I changed in express 4.0 the basic authentication with http-auth, the code is:
var auth = require('http-auth');
var basic = auth.basic({
realm: "Web."
}, function (username, password, callback) { // Custom authentication method.
callback(username === "userName" && password === "password");
}
);
app.get('/the_url', auth.connect(basic), routes.theRoute);
You can use it like this in jinja template
{{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}
In this code the field name is row.session_start_date_time
.
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
To answer your first question: yes, if the file is not there Python will create it.
Secondly, the user (yourself) running the python script doesn't have write privileges to create a file in the directory.
String[] value_split = rat_values.split(Pattern.quote("|"));
//System.out.println(Arrays.toString(rat_values.split(Pattern.quote("|")))); //(FOR GETTING OUTPUT)
String[] value_split = rat_values.split("\\|");
//System.out.println(Arrays.toString(rat_values.split("\\|"))); //(FOR GETTING OUTPUT)
public static String[] splitUsingTokenizer(String Subject, String Delimiters)
{
StringTokenizer StrTkn = new StringTokenizer(Subject, Delimiters);
ArrayList<String> ArrLis = new ArrayList<String>(Subject.length());
while(StrTkn.hasMoreTokens())
{
ArrLis.add(StrTkn.nextToken());
}
return ArrLis.toArray(new String[0]);
}
Arrays.asList(Pattern.compile("\\|").split(rat_values))
//System.out.println(Arrays.asList(Pattern.compile("\\|").split(rat_values))); //(FOR GETTING OUTPUT)
[Food 1 , Service 3 , Atmosphere 3 , Value for money 1 ]
You could use the Reflections Project described here
It's quite complete and easy to use.
Brief description from the above website:
Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.
Example:
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
);
Set<Class<?>> types = reflections.getTypesAnnotatedWith(Scannable.class);
Your first example is effectively what you need:
<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
Two problems:
You write that you ran
git init
git commit -m "first commit"
and that, at that stage, you got
nothing added to commit but untracked files present (use "git add" to track).
Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):
Hey Git, you see that
README.md
file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...
For that you need to stage the files of interest, using
git add README.md
before running
git commit -m "some descriptive message"
You then ran
git remote add origin https://github.com/VijayNew/NewExample.git
After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get
Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with
git push -u origin master
You need to check your config file if it has correct values such as systempath and artifact Id.
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\Users\Akshay\Downloads\ojdbc6.jar</systemPath>
</dependency>
super()
returns a parent-like object in new-style classes:
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super(B, self).__init__()
B()
What about x *= -1
? I like its simplicity.
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
WAMP Server may turn orange for various reason as it is not working. This is also a another type of issue. that can be due to webservices is running in services.msc This is explained in the below blog. Please try it. How to resolve HTTP Error 404 and launch localhost with WAMP Server for PHP & MySql?
It frees memory allocated to objects that are not being used by the program any more - hence the name "garbage". For example:
public static Object otherMethod(Object obj) {
return new Object();
}
public static void main(String[] args) {
Object myObj = new Object();
myObj = otherMethod(myObj);
// ... more code ...
}
I know this is extremely contrived, but here after you call otherMethod()
the original Object
created is made unreachable - and that's "garbage" that gets garbage collected.
In Java the GC runs automatically, but you can also call it explicitly with System.gc()
and try to force a major garbage collection. As Pascal Thivent points out, you really shouldn't have to do this and it might do more harm than good (see this question).
For more, see the wikipedia entry on Garbage collection and Tuning Garbage Collection (from Oracle)
You can get the same error in Asp.net MVC5 if you have a class name and a folder with a matching name Example : If you have class lands where when you want to see view/lands/index.cshtml file, if you also have a folder with name 'lands' you get the error as it first try the lands folder
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
When you run git commit
with no arguments, it will open your default editor to allow you to type a commit message. Saving the file and quitting the editor will make the commit.
It looks like your default editor is Vi or Vim. The reason "weird stuff" happens when you type is that Vi doesn't start in insert mode - you have to hit i on your keyboard first! If you don't want that, you can change it to something simpler, for example:
git config --global core.editor nano
Then you'll load the Nano editor (assuming it's installed!) when you commit, which is much more intuitive for users who've not used a modal editor such as Vi.
That text you see on your screen is just to remind you what you're about to commit. The lines are preceded by #
which means they're comments, i.e. Git ignores those lines when you save your commit message. You don't need to type a message per file - just enter some text at the top of the editor's buffer.
To bypass the editor, you can provide a commit message as an argument, e.g.
git commit -m "Added foo to the bar"
In your code:
import static org.imgscalr.Scalr.*;
public static BufferedImage resizeBufferedImage(BufferedImage image, Scalr.Method scalrMethod, Scalr.Mode scalrMode, int width, int height) {
BufferedImage bi = image;
bi = resize( image, scalrMethod, scalrMode, width, height);
return bi;
}
// Save image:
ImageIO.write(Scalr.resize(etotBImage, 150), "jpg", new File(myDir));
$http.delete
method doesn't accept request body.
You can try this workaround :
$http( angular.merge({}, config || {}, {
method : 'delete',
url : _url,
data : _data
}));
where in config
you can pass config data like headers etc.
I know @Martyn does not want full code, but I think this annotation its good for this question:
10 Open Source Android Apps which every Android developer must look into
Foursquared for Android is open-source, and have an interesting code pattern interacting with the foursquare REST API.
It worked for me too.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>WebContent\WEB-INF\web.xml</webXml>
</configuration>
</plugin>
Another way based on amadan:
SELECT * FROM [Purchasing].[Vendor] WHERE
( (@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%')
or
( @url = 'blank' and PurchasingWebServiceURL = '')
or
(@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%')
or( (@url not in ('fail','blank','','ALL') and @url is not null and
PurchasingWebServiceUrl Like '%'+@ur+'%')
END
An alternative, more generic method;
from pandas import DataFrame
def move_columns(df: DataFrame, cols_to_move: list, new_index: int) -> DataFrame:
"""
This method re-arranges the columns in a dataframe to place the desired columns at the desired index.
ex Usage: df = move_columns(df, ['Rev'], 2)
:param df:
:param cols_to_move: The names of the columns to move. They must be a list
:param new_index: The 0-based location to place the columns.
:return: Return a dataframe with the columns re-arranged
"""
other = [c for c in df if c not in cols_to_move]
start = other[0:new_index]
end = other[new_index:]
return df[start + cols_to_move + end]
According to some developers, "Core Java" refers to package API java.util.*
, which is mostly used in coding.
The term "Core Java" is not defined by Sun, it's just a slang definition.
J2ME / J2EE still depend on J2SDK API's for compilation and execution.
Nobody would say java.util.*
is separated from J2SDK for usage.
html code in my case
<ul class="navs">
<li id="tab1"><a href="index-2.html">home</a></li>
<li id="tab2"><a href="about.html">about</a></li>
<li id="tab3"><a href="project-02.html">Products</a></li>
<li id="tab4"><a href="contact.html">contact</a></li>
</ul>
and js code is
$('.navs li a').click(function (e) {
var $parent = $(this).parent();
document.cookie = eraseCookie("tab");
document.cookie = createCookie("tab", $parent.attr('id'),0);
});
$().ready(function () {
var $activeTab = readCookie("tab");
if (!$activeTab =="") {
$('#tab1').removeClass('ActiveTab');
}
// alert($activeTab.toString());
$('#'+$activeTab).addClass('active');
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function sort(data, orderBy) {
orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];
return data.sort((a, b) => {
for (let i = 0, size = orderBy.length; i < size; i++) {
const key = Object.keys(orderBy[i])[0],
o = orderBy[i][key],
valueA = a[key],
valueB = b[key];
if (!(valueA || valueB)) {
console.error("the objects from the data passed does not have the key '" + key + "' passed on sort!");
return [];
}
if (+valueA === +valueA) {
return o.toLowerCase() === 'desc' ? valueB - valueA : valueA - valueB;
} else {
if (valueA.localeCompare(valueB) > 0) {
return o.toLowerCase() === 'desc' ? -1 : 1;
} else if (valueA.localeCompare(valueB) < 0) {
return o.toLowerCase() === 'desc' ? 1 : -1;
}
}
}
});
}
Using :
sort(homes, [{city : 'asc'}, {price: 'desc'}])
var homes = [_x000D_
{"h_id":"3",_x000D_
"city":"Dallas",_x000D_
"state":"TX",_x000D_
"zip":"75201",_x000D_
"price":"162500"},_x000D_
{"h_id":"4",_x000D_
"city":"Bevery Hills",_x000D_
"state":"CA",_x000D_
"zip":"90210",_x000D_
"price":"319250"},_x000D_
{"h_id":"6",_x000D_
"city":"Dallas",_x000D_
"state":"TX",_x000D_
"zip":"75000",_x000D_
"price":"556699"},_x000D_
{"h_id":"5",_x000D_
"city":"New York",_x000D_
"state":"NY",_x000D_
"zip":"00010",_x000D_
"price":"962500"}_x000D_
];_x000D_
function sort(data, orderBy) {_x000D_
orderBy = Array.isArray(orderBy) ? orderBy : [orderBy];_x000D_
return data.sort((a, b) => {_x000D_
for (let i = 0, size = orderBy.length; i < size; i++) {_x000D_
const key = Object.keys(orderBy[i])[0],_x000D_
o = orderBy[i][key],_x000D_
valueA = a[key],_x000D_
valueB = b[key];_x000D_
if (!(valueA || valueB)) {_x000D_
console.error("the objects from the data passed does not have the key '" + key + "' passed on sort!");_x000D_
return [];_x000D_
}_x000D_
if (+valueA === +valueA) {_x000D_
return o.toLowerCase() === 'desc' ? valueB - valueA : valueA - valueB;_x000D_
} else {_x000D_
if (valueA.localeCompare(valueB) > 0) {_x000D_
return o.toLowerCase() === 'desc' ? -1 : 1;_x000D_
} else if (valueA.localeCompare(valueB) < 0) {_x000D_
return o.toLowerCase() === 'desc' ? 1 : -1;_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
}_x000D_
console.log(sort(homes, [{city : 'asc'}, {price: 'desc'}]));
_x000D_
There is issues with the precision of the accepted answer.
the round(value, decimals) function in this test works. unlike the simple toFixed example.
http://www.jacklmoore.com/notes/rounding-in-javascript/
Number.prototype.format = function(n) {_x000D_
return this.toFixed(Math.max(0, ~~n));_x000D_
};_x000D_
function round(value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);_x000D_
}_x000D_
_x000D_
// can anyone tell me why these are equivalent for 50.005, and 1050.005 through 8150.005 (increments of 50)_x000D_
_x000D_
var round_to = 2;_x000D_
var maxInt = 1500000;_x000D_
var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';_x000D_
var increment = 50;_x000D_
var round_from = 0.005;_x000D_
var expected = 0.01;_x000D_
var lastWasMatch = true;_x000D_
_x000D_
for( var n = 0; n < maxInt; n=n+increment){_x000D_
var data = {};_x000D_
var numberCheck = parseFloat(n + round_from);_x000D_
data.original = numberCheck * 1;_x000D_
data.expected = Number(n + expected) * 1;_x000D_
data.formatIt = Number(numberCheck).format(round_to) * 1;_x000D_
data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;_x000D_
data.numberIt = Number(numberCheck).toFixed(round_to) * 1;_x000D_
//console.log(data);_x000D_
_x000D_
if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||_x000D_
data.roundIt !== data.numberIt || data.roundIt != data.expected_x000D_
){_x000D_
if(lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;_x000D_
document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');_x000D_
document.write('expected: '+data.expected + ' :: ' + (typeof data.expected) + '<br />');_x000D_
document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt) + '<br />');_x000D_
document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt) + '<br />');_x000D_
document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt) + '<br />');_x000D_
lastWasMatch=false;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
} else {_x000D_
if(!lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;_x000D_
} {_x000D_
lastWasMatch=true;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
}_x000D_
}_x000D_
document.write('equalRound: '+equalRound + '</div><br />');
_x000D_
export default {_x000D_
methods: {_x000D_
roundFormat: function (value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);_x000D_
},_x000D_
currencyFormat: function (value, decimals, symbol='$') {_x000D_
return symbol + this.roundFormat(value,2);_x000D_
}_x000D_
}_x000D_
}
_x000D_
You can use sum
to sum the elements of a list, however if your list is coming from raw_input
, you probably want to convert the items to int
or float
first:
l = raw_input().split(' ')
sum(map(int, l))
The missing piece here is Data Conversion
object. It should be in between OLE DB Source and Destination object.
You have to do the following:
if "%1" == "" (
echo The variable is empty
) ELSE (
echo The variable contains %1
)