Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.
So, if I have the following NewFile.xml:
<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />
And the eclipse encoding is UTF-8:
The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.
The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.
EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.
When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.
I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.
The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!
Instead of using new Date()
you should use:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse()
returns a timestamp, an integer representing the number of milliseconds since 01/Jan/1970. It will return NaN
if it cannot parse the supplied date string.
In more recent browsers code like below may be enough.
<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">_x000D_
Not supported_x000D_
</object>
_x000D_
First navigate to below location and open it in a text editor
<TOMCAT_HOME>/conf/tomcat-users.xml
For tomcat 7, Add the following xml code somewhere between <tomcat-users>
I find the following solution.
<role rolename="manager-gui"/>
<user username="username" password="password" roles="manager-gui"/>
Now restart the tomcat server.
The scoping is correct as you've noted. However, you are not calling the inner
function anywhere.
You can do either:
function outer() {
// when you define it this way, the inner function will be accessible only from
// inside the outer function
function inner() {
alert("hi");
}
inner(); // call it
}
Or
function outer() {
this.inner = function() {
alert("hi");
}
}
<input type="button" onclick="(new outer()).inner();" value="ACTION">?
I guess this can help :
selection styles
It's possible to define color and background for text the user selects.
Try it below. If you select something and it looks like this, your browser supports selection styles.
This is the paragraph with
normal ::selection
.This is the paragraph with
::-moz-selection
.This is the paragraph with
::-webkit-selection
.Testsheet:
p.normal::selection { background:#cc0000; color:#fff; } p.moz::-moz-selection { background:#cc0000; color:#fff; } p.webkit::-webkit-selection { background:#cc0000; color:#fff; }
Quoted from Quirksmode
By setting the scale, you decrease the precision. Try NUMBER(16,2).
The default
keyword parameter should be given to the Column object.
Example:
Column(u'timestamp', TIMESTAMP(timezone=True), primary_key=False, nullable=False, default=time_now),
The default value can be a callable, which here I defined like the following.
from pytz import timezone
from datetime import datetime
UTC = timezone('UTC')
def time_now():
return datetime.now(UTC)
In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.
You can create a RecyclerView
with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView
with two Viewholders
.
Remember these 3 simple steps and you will be good to go.
getItemViewType(int position)
ViewType
in
onCreateViewHolder() methodPopulate View based on the itemViewType in onBindViewHolder()
method
Here is a code snippet for you
public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
@Override
public int getItemViewType(int position)
{
if(position==0)
return LAYOUT_ONE;
else
return LAYOUT_TWO;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =null;
RecyclerView.ViewHolder viewHolder = null;
if(viewType==LAYOUT_ONE)
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
viewHolder = new ViewHolderOne(view);
}
else
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
viewHolder= new ViewHolderTwo(view);
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder.getItemViewType()== LAYOUT_ONE)
{
// Typecast Viewholder
// Set Viewholder properties
// Add any click listener if any
}
else {
ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
vaultItemHolder.name.setText(displayText);
vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
.......
}
});
}
}
/**************** VIEW HOLDER 1 ******************//
public class ViewHolderOne extends RecyclerView.ViewHolder {
public TextView name;
public ViewHolderOne(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.displayName);
}
}
//**************** VIEW HOLDER 2 ******************//
public class ViewHolderTwo extends RecyclerView.ViewHolder{
public ViewHolderTwo(View itemView) {
super(itemView);
..... Do something
}
}
}
Here is a project where I have implemented a RecyclerView with multiple ViewHolders.
You could just outright select the elements of interest.
$('a[href*="?"]').each(function() {
alert('Contains question mark');
});
http://jsfiddle.net/mattball/TzUN3/
Note that you were using the attribute-ends-with
selector, the above code uses the attribute-contains
selector, which is what it sounds like you're actually aiming for.
To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.
TLDR; The formula is n(n-1)/2
where n
is the number of items in the set.
To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA)
, you can calculate the summation of 1 + 2 + ... + (n-1)
where n
is the number of items in the set.
The reasoning is as follows, say you have 4 items:
A
B
C
D
The number of items that can be paired with A
is 3, or n-1
:
AB
AC
AD
It follows that the number of items that can be paired with B
is n-2
(because B
has already been paired with A
):
BC
BD
and so on...
(n-1) + (n-2) + ... + (n-(n-1))
which is the same as
1 + 2 + ... + (n-1)
or
n(n-1)/2
You are confusing 'strongly typed' with 'dynamically typed'.
I cannot change the type of 1
by adding the string '12'
, but I can choose what types I store in a variable and change that during the program's run time.
The opposite of dynamic typing is static typing; the declaration of variable types doesn't change during the lifetime of a program. The opposite of strong typing is weak typing; the type of values can change during the lifetime of a program.
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
In case something modifies the location that you're trying to serve, e.g. try_files
, this preserves the request for the back-end:
location / {
proxy_pass http://127.0.0.1:8080$request_uri;
}
Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title()
, the corresponding argument for an axes is ax.set_title()
. Therefore you need to call
sns.boxplot('Day', 'Count', data= gg).set_title('lalala')
A complete example would be:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")
plt.show()
Of course you could also use the returned axes instance to make it more readable:
ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')
With Column, use:
mainAxisAlignment: MainAxisAlignment.center
It align its children(s) to center of its parent Space vertically
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
For debug/release flags, see the CMAKE_BUILD_TYPE
variable (you pass it as cmake -DCMAKE_BUILD_TYPE=value
). It takes values like Release
, Debug
, etc.
https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/Useful-Variables#compilers-and-tools
cmake uses the extension to choose the compiler, so just name your files .c.
You can override this with various settings:
For example:
set_source_files_properties(yourfile.c LANGUAGE CXX)
Would compile .c files with g++. The link above also shows how to select a specific compiler for C/C++.
I had the same problem.
Here is a workaround
android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"
Use json
in dataType
and send like this:
$.ajax({
url: "your url which return json",
type: "POST",
crossDomain: true,
data: data,
dataType: "json",
success:function(result){
alert(JSON.stringify(result));
},
error:function(xhr,status,error){
alert(status);
}
});
and put this lines in your server side file:
if PHP:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
if java:
response.addHeader( "Access-Control-Allow-Origin", "*" );
response.addHeader( "Access-Control-Allow-Methods", "POST" );
response.addHeader( "Access-Control-Max-Age", "1000" );
You're almost there: it's NOW() - INTERVAL 1 DAY
java.util.Date
object can't represent date in custom format instead you've to use SimpleDateFormat.format
method that returns string
.
String myString=format1.format(date);
Let me go through the process step by step:
$ mkdir packages
$ cd packages
open up a command prompt or shell and execute the following command:
Suppose the package you want is tensorflow
$ pip download tensorflow
Now, on the target computer, copy the packages
folder and apply the following command
$ cd packages
$ pip install 'tensorflow-xyz.whl' --no-index --find-links '.'
Note that the tensorflow-xyz.whl
must be replaced by the original name of the required package.
CsvHelper library is very popular in the Nuget.You worth it,man! https://github.com/JoshClose/CsvHelper/wiki/Basics
Using CsvHelper is really easy. It's default settings are setup for the most common scenarios.
Here is a little setup data.
Actors.csv:
Id,FirstName,LastName
1,Arnold,Schwarzenegger
2,Matt,Damon
3,Christian,Bale
Actor.cs (custom class object that represents an actor):
public class Actor
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Reading the CSV file using CsvReader:
var csv = new CsvReader( new StreamReader( "Actors.csv" ) );
var actorsList = csv.GetRecords();
Writing to a CSV file.
using (var csv = new CsvWriter( new StreamWriter( "Actors.csv" ) ))
{
csv.WriteRecords( actorsList );
}
I'm not a 100% sure, but won't
$(data)
produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.
EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)
$("img", data).attr ("src")
if you want to access the src-attribute. If your data is just text, it would probably work to do
$("img", $(data)).attr ("src")
The size of an array is static in C++. You cannot dynamically resize it. That's what std::vector
is for:
std::vector<int> v; // size of the vector starts at 0
v.push_back(10); // v now has 1 element
v.push_back(20); // v now has 2 elements
v.push_back(30); // v now has 3 elements
v.pop_back(); // removes the 30 and resizes v to 2
v.resize(v.size() - 1); // resizes v to 1
Use
apply plugin: 'com.android.library'
to convert an app module to a library module. More info here: https://developer.android.com/studio/projects/android-library.html
Consider normalizing to E.164 format. For full international support, you'd need a VARCHAR of 15 digits.
See Twilio's recommendation for more information on localization of phone numbers.
Those look like Smarty templates. There should be some additional PHP scripts which actually instantiate the Smarty engine and give it the data it can use for the replaceable elements.
I just tried a bare-bones implementation and it just works:
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello");
frame.setPreferredSize(new Dimension(200, 200));
frame.add(new Board());
frame.pack();
frame.setVisible(true);
}
}
public class Board extends JPanel {
private Player player = new Player();
public Board(){
setBackground(Color.BLACK);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getCenter().x, player.getCenter().y,
player.getRadius(), player.getRadius());
}
}
public class Player {
private Point center = new Point(50, 50);
public Point getCenter() {
return center;
}
private int radius = 10;
public int getRadius() {
return radius;
}
}
So here is the scenario that I faced, and how I solved it.
[branch-a]
[Hundreds of commits] -> [R] -> [I]
here R
is the commit that I needed to be removed, and I
is a single commit that comes after R
I made a revert commit and squashed them together
git revert [commit id of R]
git rebase -i HEAD~3
During the interactive rebase squash the last 2 commits.
Of course the "You shall not instantiate an item of this class" statement has been violated, but if this is the logic behind that, then we should all throw
AssertionErrors
everywhere, and that is obviously not what happens.
The code isn't saying the user shouldn't call the zero-args constructor. The assertion is there to say that as far as the programmer is aware, he/she has made it impossible to call the zero-args constructor (in this case by making it private
and not calling it from within Example
's code). And so if a call occurs, that assertion has been violated, and so AssertionError
is appropriate.
You must to add a needle headers:
Sample code :
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "BCC: [email protected]\r\n";
if ( mail($to,$subject,$message,$headers) ) {
echo "The email has been sent!";
} else {
echo "The email has failed!";
}
?>
You can also use functions with $filter('filter')
:
var foo = $filter('filter')($scope.results.subjects, function (item) {
return item.grade !== 'A';
});
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
You can use
$_FILES['filename']['error'];
If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done
1 : if file size is over limit .... You can find other options by googling
This should get you started:
set datafile separator ","
plot 'infile' using 0:1
Current method is to use:
npm install --save-dev babel-cli babel-preset-env
And then in in .babelrc
{
"presets": ["env"]
}
this install Babel support for latest version of js (es2015 and beyond) Check out babeljs
Do not forget to add babel-node
to your scripts inside package.json
use when running your js file as follows.
"scripts": {
"test": "mocha",
//Add this line to your scripts
"populate": "node_modules/babel-cli/bin/babel-node.js"
},
Now you can npm populate yourfile.js
inside terminal.
If you are running windows and running error internal or external command not recognized, use node infront of the script as follow
node node_modules/babel-cli/bin/babel-node.js
Then npm run populate
Maybe try kint: composer require raveren/kint "dev-master" More information: Why is my debug data unformatted?
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
Another great way of solving it while using a model is by using the values()
function.
def returnResponse(date):
response = ScheduledDate.objects.filter(date__startswith=date).values()
return Response(response)
To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:
While ImageText1.Contains(" ") '2 spaces.
ImageText1 = ImageText1.Replace(" ", " ") 'Replace with 1 space.
End While
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
Or you can do
public class Person
{
public Person(int id)
{
this.Id=id;
}
public string Name { get; set; }
public int Id { get; private set; }
public int Age { get; set; }
}
Whatever you set in crontab
will be available in the cronjobs, both directly and using the variables in the scripts.
You can configure crontab
so that it sets variables that then the can cronjob use:
$ crontab -l
myvar="hi man"
* * * * * echo "$myvar. date is $(date)" >> /tmp/hello
Now the file /tmp/hello
shows things like:
$ cat /tmp/hello
hi man. date is Thu May 12 12:10:01 CEST 2016
hi man. date is Thu May 12 12:11:01 CEST 2016
You can configure crontab
so that it sets variables that then the scripts can use:
$ crontab -l
myvar="hi man"
* * * * * /bin/bash /tmp/myscript.sh
And say script /tmp/myscript.sh
is like this:
echo "Now is $(date). myvar=$myvar" >> /tmp/myoutput.res
It generates a file /tmp/myoutput.res
showing:
$ cat /tmp/myoutput.res
Now is Thu May 12 12:07:01 CEST 2016. myvar=hi man
Now is Thu May 12 12:08:01 CEST 2016. myvar=hi man
...
If you google for javascript callback function example
you will get Getting a better understanding of callback functions in JavaScript
This is how to do a callback function:
function f() {
alert('f was called!');
}
function callFunction(func) {
func();
}
callFunction(f);
I had same problem about SaveChanges() in EF but in my case I forget to update my sql table then after I used migration my problem solved so maybe updating your tables will solve problem.
Both ~
and ^
on their own refer to the parent of the commit (~~
and ^^
both refer to the grandparent commit, etc.) But they differ in meaning when they are used with numbers:
~2
means up two levels in the hierarchy, via the first parent if a commit has more than one parent
^2
means the second parent where a commit has more than one parent (i.e. because it's a merge)
These can be combined, so HEAD~2^3
means HEAD
's grandparent commit's third parent commit.
Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.
Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.
Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.
Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
First answer is still valid, but the API has changed in the past. Since my edit there wasn't accepted I post it as separate answer.
The method authentication()
is only used to provide the authentication method (e.g. Basic) but not any credentials.
You also shouldn't use it since it's printing the credentials plain on failure!
This his how it should look like in your build.gradle
maven {
credentials {
username "$mavenUser"
password "$mavenPassword"
}
url 'https://maven.yourcorp.net/'
}
In gradle.properties
in your userhome dir put:
mavenUser=admin
mavenPassword=admin123
Also ensure that the GRADLE_USER_HOME
is set to ~/.gradle
otherwise the properties file there won't be resolved.
See also:
https://docs.gradle.org/current/userguide/build_environment.html
and
https://docs.gradle.org/current/userguide/dependency_management.html (23.6.4.1)
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
Full solution in Firefox 5:
<html>
<head>
</head>
<body>
<form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
<input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input>
</form>
<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>";
$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {
echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
$ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1);
// generate a random new file name to avoid name conflict
$fPath = md5(rand() * time()) . ".$ext";
echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
$result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);
if (strlen($ext) > 0){
echo "Uploaded ". $fPath ." succefully. <br>";
}
}
echo "Upload complete.<br>";
?>
</body>
</html>
<p><b> BOLD TEXT </b> not in bold </p>;
Include the text you want to be in bold between <b>...</b>
I had the same problem. Everything was ok: the device was registered in IOS Provisioning Portal; the certificate was downloaded and the Development Provisioning Profiles for my app was downloaded.
So the solution!!!
Target> Get Info
Select Configuration to Release (here's the devil) In code signing, Code Signing Identity check iPhone Developer. Close.
On Target chose Clean Target and then Run the app.
Good Luck.
Adding to slebetman answer:
When you say Node.JS
can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.
Internally, event loop
of Node.JS
is handling a thread pool
, where each thread handles a non-blocking request
and event loop continues to listen to more request after delegating work to one of the thread of the thread pool
. When one of the thread completes the work, it send a signal to the event loop
that it has finished aka callback
. Event loop
then process this callback and send the response back.
As you are new to NodeJS, do read more about nextTick
to understand how event loop works internally.
Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.
Set java Environment variable in Centos / Linux
/home/ vi .bashrc
export JAVA_HOME=/opt/oracle/product/java/jdk1.8.0_45
export PATH=$JAVA_HOME/bin:$PATH
java -version
$(".show-pass").click(function (e) {_x000D_
e.preventDefault();_x000D_
var type = $("#signupform-password").attr('type');_x000D_
switch (type) {_x000D_
case 'password':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'text');_x000D_
return;_x000D_
}_x000D_
case 'text':_x000D_
{_x000D_
$("#signupform-password").attr('type', 'password');_x000D_
return;_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" name="password" class="show-pass">
_x000D_
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price>0 AND
course_enrollment_settings.base_price<=100 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Just checked, it is already built-in in current version of JQuery:
jQuery - v1.9.1
jQuery UI - v1.10.2
$("#myDiv").on("remove", function () {
alert("Element was removed");
})
Important: This is functionality of Jquery UI script (not JQuery), so you have to load both scripts (jquery and jquery-ui) to make it work. Here is example: http://jsfiddle.net/72RTz/
Keep these three options in mind (you want #3):
1) Whole element is transparent:
visibility: hidden;
2) Whole element is somewhat transparent:
opacity: 0.0 - 1.0;
3) Just the background of the element is transparent:
background-color: transparent;
Something like:
if(divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
Here is a pure-java implementation of background image repeating:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundDrawable(bitmapDrawable);
}
In this case, our background image would have to be stored in res/drawable/bg_image.png.
Yes, template member functions are perfectly legal and useful on numerous occasions.
The only caveat is that template member functions cannot be virtual.
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:index.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
I think this is a file problem, you simple saved your file in 1-byte encoding like latin-1. Google up your editor and how to set files to utf-8.
I wonder why there are editors that don't default to utf-8.
In an Ionic 4 capacitor project, when I packaged and deployed to android phone for testing I got this error. Resolved by re-installing capacitor and updating android platform.
npm run build --prod --release
npx cap copy
npm install --save @capacitor/core @capacitor/cli
npx cap init
npx cap update android
npx cap open android
in
keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.
In this case string is nothing but a list of characters:
dog = "xdasds"
if "x" in dog:
print "Yes!"
You can check a substring too:
>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>>
>>>
>>> 'xa' in "xdasds"
False
Think collection:
>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>>
You can also test the set membership over user defined classes.
For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.
A temporary table can have 3 kinds, the #
is the most used. This is a temp table that only exists in the current session.
An equivalent of this is @
, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session.
The ##
is one that is the same as the #
, however, the scope is wider, so you can use it within the same session, within other stored procedures.
You can create a temp table in various ways:
declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz
If DF
is your data frame of numeric columns:
library(zoo)
na.aggregate(DF)
ADDED:
Using only the base of R define a function which does it for one column and then lapply to every column:
NA2mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
replace(DF, TRUE, lapply(DF, NA2mean))
The last line could be replaced with the following if it's OK to overwrite the input:
DF[] <- lapply(DF, NA2mean)
Try this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
This is the syntax you need:
CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END
Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it.
In this link, you can find a fork of the famous PullToRefresh
view that has new interesting implementations like PullTorRefreshWebView
or PullToRefreshGridView
or the possibility to add a PullToRefresh
on the bottom edge of a list.
https://github.com/chrisbanes/Android-PullToRefresh
And the best of it is that work perfect in Android 4.1 (the normal PullToRefresh
doesn't work )
from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]
Use the concatenation operator +
, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;
Are you using Google App Engine? You could use cookies (made with JavaScript) to maintain a relationship between filenames and the name received from the server.
Helvetica Neue is a paid font, so you shouldn't @font-face it, as you'd be freely distributing a copyrighted font. It's included in Mac systems but not in windows/linux ones, so yes, plenty of your users wont have it installed. Anyway, you can use 'Arial Narrow' as a windows substitute, which is it's windows equivalent.
func deleteAll(entityName: String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs
guard let context = self.container?.viewContext
else { print("error in deleteAll")
return }
do {
let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
} catch {
print(error.localizedDescription)
}
}
I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.
If you really want this (understand, if you can't use a corporate repository), then my advice would be to use a "file repository" local to the project and to not use a system
scoped dependency. The system
scoped should be avoided, such dependencies don't work well in many situation (e.g. in assembly), they cause more troubles than benefits.
So, instead, declare a repository local to the project:
<repositories>
<repository>
<id>my-local-repo</id>
<url>file://${project.basedir}/my-repo</url>
</repository>
</repositories>
Install your third party lib in there using install:install-file
with the localRepositoryPath
parameter:
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<myGroup> \
-DartifactId=<myArtifactId> -Dversion=<myVersion> \
-Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>
Update: It appears that install:install-file
ignores the localRepositoryPath
when using the version 2.2 of the plugin. However, it works with version 2.3 and later of the plugin. So use the fully qualified name of the plugin to specify the version:
mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
-Dfile=<path-to-file> -DgroupId=<myGroup> \
-DartifactId=<myArtifactId> -Dversion=<myVersion> \
-Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>
maven-install-plugin documentation
Finally, declare it like any other dependency (but without the system
scope):
<dependency>
<groupId>your.group.id</groupId>
<artifactId>3rdparty</artifactId>
<version>X.Y.Z</version>
</dependency>
This is IMHO a better solution than using a system
scope as your dependency will be treated like a good citizen (e.g. it will be included in an assembly and so on).
Now, I have to mention that the "right way" to deal with this situation in a corporate environment (maybe not the case here) would be to use a corporate repository.
Here is an example of how to use strtok borrowed from MSDN.
And the relevant bits, you need to call it multiple times. The token
char* is the part you would stuff into an array (you can figure that part out).
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
I just had this problem when trying to use data bind and declaring the layout tag. I know it is a bit late but for the sake of anyone encountering this problem, What I did to resolve the issue after so many attempts was that on your root layout when you are not using data bind say for example this
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"> </android.support.constraint.ConstraintLayout>
remove the
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
and just put it on your layout tag(that is if you are using data binding)
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
</layout>
and hopefully it will work. the android.enableAapt2=false
didn't work for me so I have to remove everything and try to figure out why I get the error when I put layout tag and use data binding thus I came up with the solution. Hope it helps
Simply, double shift then type Assets Folder
choose it to be created in the correct place
If you just want to round the number for output purposes, then the "%.2f"
format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works:
#include <math.h>
float val = 37.777779;
float rounded_down = floorf(val * 100) / 100; /* Result: 37.77 */
float nearest = roundf(val * 100) / 100; /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100; /* Result: 37.78 */
Notice that there are three different rounding rules you might want to choose: round down (ie, truncate after two decimal places), rounded to nearest, and round up. Usually, you want round to nearest.
As several others have pointed out, due to the quirks of floating point representation, these rounded values may not be exactly the "obvious" decimal values, but they will be very very close.
For much (much!) more information on rounding, and especially on tie-breaking rules for rounding to nearest, see the Wikipedia article on Rounding.
On DataTable 1.9.x:
$('.dataTable').dataTable({
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1], /* 1st colomn, starting from the right */
}]
});
While on 1.10.x
$('.dataTable').dataTable({
columnDefs: [{ orderable: false, "targets": -1 }] /* -1 = 1st colomn, starting from the right */
});
To keep the aspect ratio you have to use android:scaleType=fitCenter
or fitStart
etc. Using fitXY
will not keep the original aspect ratio of the image!
Note this works only for images with a src
attribute, not for the background image.
See following snippet :
$(document).on("click", "a.deleteText", function() {_x000D_
if (confirm('Are you sure ?')) {_x000D_
$(this).prev('span.text').remove();_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
<span class="text">some text</span>_x000D_
<a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
There can be corrupted jar file for which it may show error as "ZipFile invalid LOC header (bad signature)" You need to delete all jar files for which it shows the error and add this Dependency
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
Direct support was added to SQLAlchemy as of version 0.8
As per the docs, connection.execute(table.insert().values(data))
should do the trick. (Note that this is not the same as connection.execute(table.insert(), data)
which results in many individual row inserts via a call to executemany
). On anything but a local connection the difference in performance can be enormous.
df.loc[df['A'] == df['B'], 'C'] = 0
df.loc[df['A'] > df['B'], 'C'] = 1
df.loc[df['A'] < df['B'], 'C'] = -1
Easy to solve using indexing. The first line of code reads like so, if column A
is equal to column B
then create and set column C
equal to 0.
You can try to get index or position of list or array first, then use for loop to assign current array to a temp list, filter out unwanted item and store wanted item back to original array
removeItem(index) {
var tempList = this.uploadFile;
this.uploadFile = [];
for (var j = 0; j < tempList.length; j++) {
if (j != index)
this.uploadFile.push(tempList[j]);
}
}
You can set content view (or design) of an activity. For example you can do it like this too :
public void onCreate(Bundle savedinstanceState) {
super.onCreate(savedinstanceState);
Button testButon = new Button(this);
setContentView(testButon);
}
Also watch this tutorial too.
A slightly less verbose way is to use the performSelector: withObject: afterDelay: which sets up the NSTimer object for you and can be easily cancelled
So continuing with the previous example this would be
[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];
More info in the doc
One of the simplest way: use Link as follows:
import { Link } from 'react-router-dom';
<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
If we want to cover the whole div section as link:
<div>
<Card as={Link} to={'path-name'}>
....
card content here
....
</Card>
</div>
Java uses double quotes for "String"
and single quotes for 'C'
haracters.
This is an old question, but answering for gathering knowledge. We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close()
will free the memory and we can never interact with that form again
form.hide()
will just hide the form, where the code part can still run
For more details about timer refer this link, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
You could define callFriend
this way:
public <T extends Animal> T callFriend(String name, Class<T> type) {
return type.cast(friends.get(name));
}
Then call it as such:
jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();
This code has the benefit of not generating any compiler warnings. Of course this is really just an updated version of casting from the pre-generic days and doesn't add any additional safety.
I know this is an older question but with Visual Studio 2015 I was having issues where my newly created test class was not being recognized. Tried everything. What ended up being the issue was that the class was not "included in the project". I only found this on restarting Visual Studio and noticing that my test class was not there. Upon showing hidden files, I saw it, as well as other classes I had written, were not included. Hope that helps
Looking at the jQuery code, this is what happens:
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
After trying all possible options, the below trick worked for me:
Search for
"# The MySQL server"
[mysqld]
user = mysql
port=3308
and change the port number.
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
I think the problem was the two single quotes missing.
This is the sql I run to the MSSMS:
WHERE checktime >= '2019-01-24 15:01:36.000' AND checktime <= '2019-01-25 16:01:36.000'
As you can see there are two single quotes, so your codes must be:
string sqlFormattedDate = "'" + myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss") + "'";
Use single quotes for every string in MSSQL or even in MySQL. I hope this helps.
I could not get @Andrei Karcheuski 's approach to work but he inspired me to this approach: (I added the Localizable Property so the Hint can be translated through .resx files for each dialog you use it on)
public partial class HintComboBox : ComboBox
{
string hint;
Font greyFont;
[Localizable(true)]
public string Hint
{
get { return hint; }
set { hint = value; Invalidate(); }
}
public HintComboBox()
{
InitializeComponent();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
if (string.IsNullOrEmpty(Text))
{
this.ForeColor = SystemColors.GrayText;
Text = Hint;
}
else
{
this.ForeColor = Color.Black;
}
}
private void HintComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if( string.IsNullOrEmpty(Text) )
{
this.ForeColor = SystemColors.GrayText;
Text = Hint;
}
else
{
this.ForeColor = Color.Black;
}
}
I had this problem on my developent environment with Visual Studio.
What helped me was to Clean Solution
in Visual Studio and then do a rebuild.
Extending the Storage object is an awesome solution. For my API, I have created a facade for localStorage and then check if it is an object or not while setting and getting.
var data = {
set: function(key, value) {
if (!key || !value) {return;}
if (typeof value === "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
get: function(key) {
var value = localStorage.getItem(key);
if (!value) {return;}
// assume it is an object that has been stringified
if (value[0] === "{") {
value = JSON.parse(value);
}
return value;
}
}
I read a csv file from local directory. Following code works for me.
# to get number of which contains na
sum(is.na(df[, c(columnName)]) # to get number of na row
# to get number of which not contains na
sum(!is.na(df[, c(columnName)])
#here columnName is your desire column name
HTML5 introduces FormData
class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
The right way to do this is simple:
def rate(T):
if (T > 200):
return 200*exp(-T)
else:
return 400*exp(-T)
There is absolutely no advantage to using lambda
here. The only thing lambda
is good for is allowing you to create anonymous functions and use them in an expression (as opposed to a statement). If you immediately assign the lambda
to a variable, it's no longer anonymous, and it's used in a statement, so you're just making your code less readable for no reason.
The rate
function defined this way can be stored in an array, passed around, called, etc. in exactly the same way a lambda function could. It'll be exactly the same (except a bit easier to debug, introspect, etc.).
From a comment:
Well the function needed to fit in one line, which i didn't think you could do with a named function?
I can't imagine any good reason why the function would ever need to fit in one line. But sure, you can do that with a named function. Try this in your interpreter:
>>> def foo(x): return x + 1
Also these functions are stored as strings which are then evaluated using "eval" which i wasn't sure how to do with regular functions.
Again, while it's hard to be 100% sure without any clue as to why why you're doing this, I'm at least 99% sure that you have no reason or a bad reason for this. Almost any time you think you want to pass Python functions around as strings and call eval
so you can use them, you actually just want to pass Python functions around as functions and use them as functions.
But on the off chance that this really is what you need here: Just use exec
instead of eval
.
You didn't mention which version of Python you're using. In 3.x, the exec
function has the exact same signature as the eval
function:
exec(my_function_string, my_globals, my_locals)
In 2.7, exec
is a statement, not a function—but you can still write it in the same syntax as in 3.x (as long as you don't try to assign the return value to anything) and it works.
In earlier 2.x (before 2.6, I think?) you have to do it like this instead:
exec my_function_string in my_globals, my_locals
//Page load starts here
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new
{
api_key = "my key",
action = "categories",
store_id = "my store"
});
var json2 = "{\"api_key\":\"my key\",\"action\":\"categories\",\"store_id\":\"my store\",\"user\" : {\"id\" : 12345,\"screen_name\" : \"twitpicuser\"}}";
var list = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<FooBar>(json);
var list2 = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<FooBar>(json2);
string a = list2.action;
var b = list2.user;
string c = b.screen_name;
//Page load ends here
public class FooBar
{
public string api_key { get; set; }
public string action { get; set; }
public string store_id { get; set; }
public User user { get; set; }
}
public class User
{
public int id { get; set; }
public string screen_name { get; set; }
}
To collapse methods in the Visual Studio Code editor:
NB.: As per the Visual Studio Code documentation, a folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
Here is a function that even supports clockwise/anticlockwise drawing do that you control fills with the non-zero winding rule.
Here is a full article on how it works and more.
// Defines a path for any regular polygon with the specified number of sides and radius,
// centered on the provide x and y coordinates.
// optional parameters: startAngle and anticlockwise
function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}
// Example using the function.
// Define a path in the shape of a pentagon and then fill and stroke it.
context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle="rgba(227,11,93,0.75)";
context.fill();
context.stroke();
Answer os Crisalin is almost perfect. Just improved the performance to avoid create new RegExp on each run.
var normalizeConversions = [
{ regex: new RegExp('ä|æ|?', 'g'), clean: 'ae' },
{ regex: new RegExp('ö|œ', 'g'), clean: 'oe' },
{ regex: new RegExp('ü', 'g'), clean: 'ue' },
{ regex: new RegExp('Ä', 'g'), clean: 'Ae' },
{ regex: new RegExp('Ü', 'g'), clean: 'Ue' },
{ regex: new RegExp('Ö', 'g'), clean: 'Oe' },
{ regex: new RegExp('À|Á|Â|Ã|Ä|Å|?|A|A|A|A', 'g'), clean: 'A' },
{ regex: new RegExp('à|á|â|ã|å|?|a|a|a|a|ª', 'g'), clean: 'a' },
{ regex: new RegExp('Ç|C|C|C|C', 'g'), clean: 'C' },
{ regex: new RegExp('ç|c|c|c|c', 'g'), clean: 'c' },
{ regex: new RegExp('Ð|D|Ð', 'g'), clean: 'D' },
{ regex: new RegExp('ð|d|d', 'g'), clean: 'd' },
{ regex: new RegExp('È|É|Ê|Ë|E|E|E|E|E', 'g'), clean: 'E' },
{ regex: new RegExp('è|é|ê|ë|e|e|e|e|e', 'g'), clean: 'e' },
{ regex: new RegExp('G|G|G|G', 'g'), clean: 'G' },
{ regex: new RegExp('g|g|g|g', 'g'), clean: 'g' },
{ regex: new RegExp('H|H', 'g'), clean: 'H' },
{ regex: new RegExp('h|h', 'g'), clean: 'h' },
{ regex: new RegExp('Ì|Í|Î|Ï|I|I|I|I|I|I', 'g'), clean: 'I' },
{ regex: new RegExp('ì|í|î|ï|i|i|i|i|i|i', 'g'), clean: 'i' },
{ regex: new RegExp('J', 'g'), clean: 'J' },
{ regex: new RegExp('j', 'g'), clean: 'j' },
{ regex: new RegExp('K', 'g'), clean: 'K' },
{ regex: new RegExp('k', 'g'), clean: 'k' },
{ regex: new RegExp('L|L|L|?|L', 'g'), clean: 'L' },
{ regex: new RegExp('l|l|l|?|l', 'g'), clean: 'l' },
{ regex: new RegExp('Ñ|N|N|N', 'g'), clean: 'N' },
{ regex: new RegExp('ñ|n|n|n|?', 'g'), clean: 'n' },
{ regex: new RegExp('Ò|Ó|Ô|Õ|O|O|O|O|O|Ø|?', 'g'), clean: 'O' },
{ regex: new RegExp('ò|ó|ô|õ|o|o|o|o|o|ø|?|º', 'g'), clean: 'o' },
{ regex: new RegExp('R|R|R', 'g'), clean: 'R' },
{ regex: new RegExp('r|r|r', 'g'), clean: 'r' },
{ regex: new RegExp('S|S|S|Š', 'g'), clean: 'S' },
{ regex: new RegExp('s|s|s|š|?', 'g'), clean: 's' },
{ regex: new RegExp('T|T|T', 'g'), clean: 'T' },
{ regex: new RegExp('t|t|t', 'g'), clean: 't' },
{ regex: new RegExp('Ù|Ú|Û|U|U|U|U|U|U|U|U|U|U|U|U', 'g'), clean: 'U' },
{ regex: new RegExp('ù|ú|û|u|u|u|u|u|u|u|u|u|u|u|u', 'g'), clean: 'u' },
{ regex: new RegExp('Ý|Ÿ|Y', 'g'), clean: 'Y' },
{ regex: new RegExp('ý|ÿ|y', 'g'), clean: 'y' },
{ regex: new RegExp('W', 'g'), clean: 'W' },
{ regex: new RegExp('w', 'g'), clean: 'w' },
{ regex: new RegExp('Z|Z|Ž', 'g'), clean: 'Z' },
{ regex: new RegExp('z|z|ž', 'g'), clean: 'z' },
{ regex: new RegExp('Æ|?', 'g'), clean: 'AE' },
{ regex: new RegExp('ß', 'g'), clean: 'ss' },
{ regex: new RegExp('?', 'g'), clean: 'IJ' },
{ regex: new RegExp('?', 'g'), clean: 'ij' },
{ regex: new RegExp('Œ', 'g'), clean: 'OE' },
{ regex: new RegExp('ƒ', 'g'), clean: 'f' }
];
Usage:
function(str){
normalizeConversions.forEach(function(normalizeEntry){
str = str.replace(normalizeEntry.regex, normalizeEntry.clean);
});
return str;
};
SELECT CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
WHEN SERVERPROPERTY('EditionID') = -2117995310 THEN 'Developer'
WHEN SERVERPROPERTY('EditionID') = 610778273 THEN 'Windows Embedded SQL'
WHEN SERVERPROPERTY('EditionID') = 4161255391 THEN 'Express with Advanced Services'
END AS 'Edition';
You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty
to the mount command.
You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..
// create 10 MB file
dd if=/dev/zero of=partition bs=1024 count=10240
// create loopdevice from that file
sudo losetup /dev/loop0 ./partition
// create filesystem on it
sudo e2mkfs.ext3 /dev/loop0
// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo
# unmount the device
sudo umount /dev/loop0
# create the file again
echo "bar2" > test/foo
# now mount the device (having file with same name on it)
# and see what happens
sudo mount -o loop /dev/loop0 test
If you define a color in your XML and want to use it to change background color or something this API is the one your are looking for:
((TextView) view).setBackgroundResource(R.drawable.your_color_here);
In my sample I used it for TestView
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
The directions state:
- Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
- Unzip the packages into a single directory such as "instantclient".
- Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
- Start your application and enjoy.
Suggest extracting/unzipping into a new directory. They've suggested instantclient
, but you can name the directory anything you like. Name it C:\OracleInstantClient\
if you choose.
Then in Step 3, open a Windows Command Prompt. Type:
PATH C:\OracleInstantClient; %PATH%`
That's all there is to it!
You can use MongoDB_DataObject wrapper to perform such query like below:
$model = new MongoDB_DataObject('orders');
$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');
$model->find();
while ($model->fetch()) {
var_dump($model);
}
OR, similarly, using direct query string:
$model = new MongoDB_DataObject();
$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');
while ($model->fetch()) {
var_dump($model);
}
$ g++ 1st.cpp -o 1st
$ ./1st
if you found any error then first install g++ using code as below
$ sudo apt-get install g++
then install g++ and use above run code
The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.
Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.
In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.
I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
You can see it the whole example here:
Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this:
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
this will make you to answer the question
Looks like you missed -m for commit command
Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful.
You can also do this by running a single line.
git merge aq master
This is equivalent to
git checkout aq
git merge master
@Html.Partial
and @Html.RenderPartial
are used when your Partial view model is correspondence of parent model, we don't need to create any action method to call this.
@Html.Action
and @Html.RenderAction
are used when your partial view model are independent from parent model, basically it is used when you want to display any widget type content on page. You must create an action method which returns a partial view result while calling the method from view.
Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.
Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.
Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.
The best way to link these two is to add an OnDismissListener and override the onDismiss()
method of the intended to dimiss the dummy popup window from their.
Code for the dummy popup window:
fadepopup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fadePopup"
android:background="#AA000000">
</LinearLayout>
Show fade popup to dim the background
private PopupWindow dimBackground() {
LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.fadepopup,
(ViewGroup) findViewById(R.id.fadePopup));
PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
return fadePopup;
}
For a visual way to think about it, picture a clock face that, in your particular example, only goes to 4 instead of 12. If you start at 4 on the clock (which is like starting at zero) and go around it clockwise for 2 "hours", you land on 2, just like going around it clockwise for 6 "hours" would also land you on 2 (6 mod 4 == 2 just like 2 mod 4 == 2).
I followed some tips from the rest answers and discovered that these odd actions helped (at least in my case).
1) I added to server block the following:
location ~ \.css {
add_header Content-Type text/css;
}
I reloaded nginx and got this in error.log:
2015/06/18 11:32:29 [error] 3430#3430: *169 open() "/etc/nginx/html/css/mysite.css" failed (2: No such file or directory)
2) I deleted the rows, reloaded nginx and got working css. I can't explain what happend because my conf file became such as before.
My case was clean xubuntu 14.04 on VirtualBox, nginx/1.9.2, a row 127.51.1.1 mysite
in /etc/hosts and pretty simple /etc/nginx/nginx.conf with a server block:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
server {
listen 80;
server_name mysite;
location / {
root /home/testuser/dev/mysite/;
}
}
}
You should use the resource folders such as
values-ldpi
values-mdpi
values-hdpi
And write the text size in 'dimensions.xml' file for each range.
And in the java code you can set the text size with
textView.setTextSize(getResources().getDimension(R.dimen.textsize));
Sample dimensions.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="textsize">15sp</dimen>
</resources>
For windows add the path for meld is like below:
git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum
I was also running into this - turns out I was using a community-created AMI - and the default username was niehter root, nor was it ect-user or ubuntu. In fact, I had no idea what it was - till I tried 'root' and the server kindly asked me to login as xxx where xxx is whatever it tells you.
-cheers!
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]
Ive just been searching for a solution and come across Spreadsheetlight
which looks very promising. Its open source and available as a nuget package.
Following are eight ways to find the Uptime in Windows OS.
In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.
The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.
The systeminfo
command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:
systeminfo
You can also narrow down the results to just the line you need:
systeminfo | find "System Boot Time:"
Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.
Read the following KB for more info and for the download links:
To use it, follow these steps:
uptime.exe
utility. You can add a /? to the command in order
to get more options.
It does not offer many command line parameters:
C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version
C:\uptimefromcodeplex\> uptime -V
version 1.1.0
There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)
Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)
C:\uptimev100download>uptime.exe /?
UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation
Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.
Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:
net statistics workstation
The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.
Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.
Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.
Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.
Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}
GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.
wmic os get lastbootuptime
Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h
command-line parameter).
Additionally, this version of uptime.exe
will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:
and when executed as uptime -h
:
You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",")
and then use it for the new cookie instead of using old_cookie
which is not shortened.
You may also not be using .splice()
correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()
here.
Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:
svn add directory_name
will add the directory directory_name
and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
See Scirocco Recorder For Chrome. It does IDE recording for Selenium 2 on Chrome.
https://chrome.google.com/webstore/detail/scirocco-recorder-for-chr/ibclajljffeaafooicpmkcjdnkbaoiih
To increase performance when downloading a large file, the below may work a bit more efficiently:
import requests
from contextlib import closing
import csv
url = "http://download-and-process-csv-efficiently/python.csv"
with closing(requests.get(url, stream=True)) as r:
reader = csv.reader(r.iter_lines(), delimiter=',', quotechar='"')
for row in reader:
# Handle each row here...
print row
By setting stream=True
in the GET request, when we pass r.iter_lines()
to csv.reader(), we are passing a generator to csv.reader(). By doing so, we enable csv.reader() to lazily iterate over each line in the response with for row in reader
.
This avoids loading the entire file into memory before we start processing it, drastically reducing memory overhead for large files.
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
I don’t think you can select the parent in CSS only.
But as you already seem to have an .active
class, it would be easier to move that class to the li
(instead of the a
). That way you can access both the li
and the a
via CSS only.
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
in smarty V3 you can use this
{var_dump($variable)}
I had the same problem of running a QT5 application in windows 10 ( VS2019). My error was
..\Debug\Qt5Cored.dll
Module: 5.14.1
File: kernel\qguiapplication.cpp
Line: 1249
This application failed to start because no Qt platform plugin could be initialized.
Reinstalling the application may fix this problem.
Since I was using QT msvc2017, I copied plugins folders from "C:\Qt\Qt5.14.1\5.14.1\msvc2017\plugins" location to the binary location
it worked.
Then check visual studio output window and identify the dlls loaded from plugin folder and removed unwanted dlls
A simple way is to write it:
Dim rs As Object
Set rs = Me.Recordset.Clone
If Me.Recordset.RecordCount = 0 then 'checks for number of records
msgbox "There is no records"
End if
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/
On a Mac:
brew install swaks
swaks --to [email protected] --server smtp.example.com
I could not access the context object directly.
My solution is as following:
Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
wifiManager.SetWifiEnabled(state);
Also I had to change some writings eg. WIFI_SERVICE vs. WifiService.
Note that this most often occurs when the content has been "double encoded", meaning the encoding algorithm has accidentally been called twice.
The first call would encode the "text2" value:
FROM: Heute startet unsere Rundreise "Example text". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
TO: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
A second encoding then converts it again, escaping the already escaped characters:
FROM: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
TO: Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.
So, if you are responsible for the implementation of the server here, check to make sure there aren't two steps trying to encode the same content.
(Linux)
Open your Terminal ctrl+alt+t
run the command
cat ~/.mysql_history
you will get all the previous mysql query history enjoy :)
$('#subscribeForm').validate( {
rules: {
list: {
required: true,
minlength: 1
}
}
});
I think this will make sure at least one is checked.
The following hack works:
xmlns:tools="http://schemas.android.com/tools"
line in the
manifest tag tools:replace="android:icon,android:theme,android:allowBackup,label"
in the application tagFor AWS importing an existing public key,
Export from the .pem doing this... (on linux)
openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
This will produce a file which if you open in a text editor looking something like this...
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
9WyrKhxq4Vbt42BthadX3Ty/pKkJ81Qn8KjxWoL+SMaCGFzRlfWsFju9Q5C7+aTj
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
However AWS will NOT accept this file.
You have to strip off the -----BEGIN PUBLIC KEY-----
and -----END PUBLIC KEY-----
from the file. Save it and import and it should work in AWS.
rsync
transfers files as fast as it can over the network. For example, try using it to copy one large file that doesn't exist at all on the destination. That speed is the maximum speed rsync can transfer data. Compare it with the speed of scp
(for example). rsync
is even slower at raw transfer when the destination file exists, because both sides have to have a two-way chat about what parts of the file are changed, but pays for itself by identifying data that doesn't need to be transferred.
A simpler way to run rsync
in parallel would be to use parallel
. The command below would run up to 5 rsync
s in parallel, each one copying one directory. Be aware that the bottleneck might not be your network, but the speed of your CPUs and disks, and running things in parallel just makes them all slower, not faster.
run_rsync() {
# e.g. copies /main/files/blah to /main/filesTest/blah
rsync -av "$1" "/main/filesTest/${1#/main/files/}"
}
export -f run_rsync
parallel -j5 run_rsync ::: /main/files/*
For attaching fragment to an activity programmatically in Kotlin, you can look at the following code:
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// create fragment instance
val fragment : FragmentName = FragmentName.newInstance()
// for passing data to fragment
val bundle = Bundle()
bundle.putString("data_to_be_passed", DATA)
fragment.arguments = bundle
// check is important to prevent activity from attaching the fragment if already its attached
if (savedInstanceState == null) {
supportFragmentManager
.beginTransaction()
.add(R.id.fragment_container, fragment, "fragment_name")
.commit()
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentName.kt
class FragmentName : Fragment() {
companion object {
fun newInstance() = FragmentName()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// receiving the data passed from activity here
val data = arguments!!.getString("data_to_be_passed")
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
}
If you are familiar with Extensions in Kotlin then you can even better this code by following this article.
I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.
I gave up and used Java the last time I needed to do this, and simply gave up a few times the last time I wanted to do this, but it wasn't essential.
Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.
Turns out that's not too difficult, but it is time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.
Do this:
box-shadow: 0 4px 2px -2px gray;
It's actually much simpler, whatever you set the blur to (3rd value), set the spread (4th value) to the negative of it.
The other answers provided will not include files or directories that start with a . the following worked for me:
#/bin/sh
getAll()
{
local fl1="$1"/*;
local fl2="$1"/.[!.]*;
local fl3="$1"/..?*;
for inpath in "$1"/* "$1"/.[!.]* "$1"/..?*; do
if [ "$inpath" != "$fl1" -a "$inpath" != "$fl2" -a "$inpath" != "$fl3" ]; then
stat --printf="%F\0%n\0\n" -- "$inpath";
if [ -d "$inpath" ]; then
getAll "$inpath"
#elif [ -f $inpath ]; then
fi;
fi;
done;
}
The radio buttons are sent on form submit when they are checked only...
use isset()
if true then its checked otherwise its not
To answer my own question, the trick is to turn auto scaling off...
p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)
use Javascript sort() function
var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){
var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
// if a < b return 1
return tda < tdb ? 1
// else if a > b return -1
: tda > tdb ? -1
// else they are equal - return 0
: 0;
}).appendTo($tbody);
If you want ascending you just have to reverse the > and <
Change the logic accordingly for you.
I would recommend that you start by pulling your task apart into it's component parts.
Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.
If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.
DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation. Integer.parseInt() will prase integers from strings.
Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).
PyPy has had Python 3 support for a while, but according to this HackerNoon post by Anthony Shaw from April 2nd, 2018, PyPy3 is still several times slower than PyPy (Python 2).
For many scientific calculations, particularly matrix calculations, numpy is a better choice (see FAQ: Should I install numpy or numpypy?).
Pypy does not support gmpy2. You can instead make use of gmpy_cffi though I haven't tested its speed and the project had one release in 2014.
For Project Euler problems, I make frequent use of PyPy, and for simple numerical calculations often from __future__ import division
is sufficient for my purposes, but Python 3 support is still being worked on as of 2018, with your best bet being on 64-bit Linux. Windows PyPy3.5 v6.0, the latest as of December 2018, is in beta.
alter table table_name
rename column old_column_name/field_name to new_column_name/field_name;
example: alter table student column name to username;
It may be because you are not stopping your tomcat service properly. To do that, Open your task manager there you can see a javaw.exe
service. First stop that service. Now restart your tomcat it works fine.
Depending on how big your arrays are you might consider an efficient algorithm O(n log n)
def equal_a(a1, a2)
a1sorted = a1.sort
a2sorted = a2.sort
return false if a1.length != a2.length
0.upto(a1.length - 1) do
|i| return false if a1sorted[i] != a2sorted[i]
end
end
Sorting costs O(n log n) and checking each pair costs O(n) thus this algorithm is O(n log n). The other algorithms cannot be faster (asymptotically) using unsorted arrays.
docker ps -a
This command saves modified container state into a new image user/test_image
docker commit $CONTAINER_ID user/test_image
docker run -ti --entrypoint=sh user/test_image
Entrypoint argument description: https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) https://github.com/docker/docker/issues/18078
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Add id's to both inputs, id="first" and id="second"
//trigger second button $("#second").click()
Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.
Read regular-expression.info for more details.
Syntax:
(?=REGEX_1)REGEX_2
Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.
example:
(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}
REGEX_1 is [a-z0-9]{4}$
which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3}
which matches one or two letters followed by two or three digits.
REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.
Syntax:
(?!REGEX_1)REGEX_2
Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.
example:
(?!.*\bFWORD\b)\w{10,30}$
The look-ahead part checks for the FWORD
in the string and fails if it finds it. If it doesn't find FWORD
, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_
Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.
This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.
The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.
On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.
So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.
Just create a data frame of empty vectors:
collect1 <- data.frame(id = character(0), max1 = numeric(0), max2 = numeric(0))
But if you know how many rows you're going to have in advance, you should just create the data frame with that many rows to start with.
I didn't mean to copy the same answer, that is why I didn't accept my own answer.
Actually when I add use DateTime
in top of the controller solves this problem.
A couple of quick extensions on what has already been said...
An id
must be unique, but you can use the same id to make different styles more specific.
For example, given this HTML extract:
<div id="sidebar">
<h2>Heading</h2>
<ul class="menu">
...
</ul>
</div>
<div id="content">
<h2>Heading</h2>
...
</div>
<div id="footer">
<ul class="menu">
...
</ul>
</div>
You could apply different styles with these:
#sidebar h2
{ ... }
#sidebar .menu
{ ... }
#content h2
{ ... }
#footer .menu
{ ... }
Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...
<ul class="main menu">...</ul>
<ul class="other menu">...</ul>
Which allows you to have common styling in .menu
with specific styles using .main.menu
and .sub.menu
.menu
{ ... }
.main.menu
{ ... }
.other.menu
{ ... }
For quick and dirty, you can do
import java.awt.Color;
private Color dropPrecision(Color c,int threshold){
return new Color((c.getRed()/threshold),
(c.getGreen()/threshold),
(c.getBlue()/threshold));
}
public boolean inThreshold(Color _1,Color _2,int threshold){
return dropPrecision(_1,threshold)==dropPrecision(_2,threshold);
}
making use of integer division to quantize the colors.
The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0
(the other answer works for versions <2.0.0
):
Handlebars.registerHelper('renderPartial', function(partialName, options) {
if (!partialName) {
console.error('No partial name given.');
return '';
}
var partial = Handlebars.partials[partialName];
if (!partial) {
console.error('Couldnt find the compiled partial: ' + partialName);
return '';
}
return new Handlebars.SafeString( partial(options.hash) );
});
Then in your template, you can do something like:
{{renderPartial 'myPartialName' foo=this bar=../bar}}
And in your partial, you'll be able to access those values as context like:
<div id={{bar.id}}>{{foo}}</div>
This problem is a well-known / "classic" optimization issue for JavaScript, caused by the fact that JavaScript strings are "immutable" and addition by concatenation of even a single character to a string requires creation of, including memory allocation for and copying to, an entire new string.
Unfortunately, the accepted answer on this page is wrong, where "wrong" means by a performance factor of 3x for simple one-character strings, and 8x-97x for short strings repeated more times, to 300x for repeating sentences, and infinitely wrong when taking the limit of the ratios of complexity of the algorithms as n
goes to infinity. Also, there is another answer on this page which is almost right (based on one of the many generations and variations of the correct solution circulating throughout the Internet in the past 13 years). However, this "almost right" solution misses a key point of the correct algorithm causing a 50% performance degradation.
~ October 2000 I published an algorithm for this exact problem which was widely adapted, modified, then eventually poorly understood and forgotten. To remedy this issue, in August, 2008 I published an article http://www.webreference.com/programming/javascript/jkm3/3.html explaining the algorithm and using it as an example of simple of general-purpose JavaScript optimizations. By now, Web Reference has scrubbed my contact information and even my name from this article. And once again, the algorithm has been widely adapted, modified, then poorly understood and largely forgotten.
Original string repetition/multiplication JavaScript algorithm by Joseph Myers, circa Y2K as a text multiplying function within Text.js; published August, 2008 in this form by Web Reference: http://www.webreference.com/programming/javascript/jkm3/3.html (The article used the function as an example of JavaScript optimizations, which is the only for the strange name "stringFill3.")
/*
* Usage: stringFill3("abc", 2) == "abcabc"
*/
function stringFill3(x, n) {
var s = '';
for (;;) {
if (n & 1) s += x;
n >>= 1;
if (n) x += x;
else break;
}
return s;
}
Within two months after publication of that article, this same question was posted to Stack Overflow and flew under my radar until now, when apparently the original algorithm for this problem has once again been forgotten. The best solution available on this Stack Overflow page is a modified version of my solution, possibly separated by several generations. Unfortunately, the modifications ruined the solution's optimality. In fact, by changing the structure of the loop from my original, the modified solution performs a completely unneeded extra step of exponential duplicating (thus joining the largest string used in the proper answer with itself an extra time and then discarding it).
Below ensues a discussion of some JavaScript optimizations related to all of the answers to this problem and for the benefit of all.
To illustrate how this technique works, we use a real-life JavaScript function which creates strings of whatever length is needed. And as we'll see, more optimizations can be added!
A function like the one used here is to create padding to align columns of text, for formatting money, or for filling block data up to the boundary. A text generation function also allows variable length input for testing any other function that operates on text. This function is one of the important components of the JavaScript text processing module.
As we proceed, we will be covering two more of the most important optimization techniques while developing the original code into an optimized algorithm for creating strings. The final result is an industrial-strength, high-performance function that I've used everywhere--aligning item prices and totals in JavaScript order forms, data formatting and email / text message formatting and many other uses.
Original code for creating strings stringFill1()
function stringFill1(x, n) {
var s = '';
while (s.length < n) s += x;
return s;
}
/* Example of output: stringFill1('x', 3) == 'xxx' */
The syntax is here is clear. As you can see, we've used local function variables already, before going on to more optimizations.
Be aware that there's one innocent reference to an object property s.length
in the code that hurts its performance. Even worse, the use of this object property reduces the simplicity of the program by making the assumption that the reader knows about the properties of JavaScript string objects.
The use of this object property destroys the generality of the computer program. The program assumes that x
must be a string of length one. This limits the application of the stringFill1()
function to anything except repetition of single characters. Even single characters cannot be used if they contain multiple bytes like the HTML entity
.
The worst problem caused by this unnecessary use of an object property is that the function creates an infinite loop if tested on an empty input string x
. To check generality, apply a program to the smallest possible amount of input. A program which crashes when asked to exceed the amount of available memory has an excuse. A program like this one which crashes when asked to produce nothing is unacceptable. Sometimes pretty code is poisonous code.
Simplicity may be an ambiguous goal of computer programming, but generally it's not. When a program lacks any reasonable level of generality, it's not valid to say, "The program is good enough as far as it goes." As you can see, using the string.length
property prevents this program from working in a general setting, and in fact, the incorrect program is ready to cause a browser or system crash.
Is there a way to improve the performance of this JavaScript as well as take care of these two serious problems?
Of course. Just use integers.
Optimized code for creating strings stringFill2()
function stringFill2(x, n) {
var s = '';
while (n-- > 0) s += x;
return s;
}
Timing code to compare stringFill1()
and stringFill2()
function testFill(functionToBeTested, outputSize) {
var i = 0, t0 = new Date();
do {
functionToBeTested('x', outputSize);
t = new Date() - t0;
i++;
} while (t < 2000);
return t/i/1000;
}
seconds1 = testFill(stringFill1, 100);
seconds2 = testFill(stringFill2, 100);
The success so far of stringFill2()
stringFill1()
takes 47.297 microseconds (millionths of a second) to fill a 100-byte string, and stringFill2()
takes 27.68 microseconds to do the same thing. That's almost a doubling in performance by avoiding a reference to an object property.
Our previous result looked good--very good, in fact. The improved function stringFill2()
is much faster due to the use of our first two optimizations. Would you believe it if I told you that it can be improved to be many times faster than it is now?
Yes, we can accomplish that goal. Right now we need to explain how we avoid appending short strings to long strings.
The short-term behavior appears to be quite good, in comparison to our original function. Computer scientists like to analyze the "asymptotic behavior" of a function or computer program algorithm, which means to study its long-term behavior by testing it with larger inputs. Sometimes without doing further tests, one never becomes aware of ways that a computer program could be improved. To see what will happen, we're going to create a 200-byte string.
The problem that shows up with stringFill2()
Using our timing function, we find that the time increases to 62.54 microseconds for a 200-byte string, compared to 27.68 for a 100-byte string. It seems like the time should be doubled for doing twice as much work, but instead it's tripled or quadrupled. From programming experience, this result seems strange, because if anything, the function should be slightly faster since work is being done more efficiently (200 bytes per function call rather than 100 bytes per function call). This issue has to do with an insidious property of JavaScript strings: JavaScript strings are "immutable."
Immutable means that you cannot change a string once it's created. By adding on one byte at a time, we're not using up one more byte of effort. We're actually recreating the entire string plus one more byte.
In effect, to add one more byte to a 100-byte string, it takes 101 bytes worth of work. Let's briefly analyze the computational cost for creating a string of N
bytes. The cost of adding the first byte is 1 unit of computational effort. The cost of adding the second byte isn't one unit but 2 units (copying the first byte to a new string object as well as adding the second byte). The third byte requires a cost of 3 units, etc.
C(N) = 1 + 2 + 3 + ... + N = N(N+1)/2 = O(N^2)
. The symbol O(N^2)
is pronounced Big O of N squared, and it means that the computational cost in the long run is proportional to the square of the string length. To create 100 characters takes 10,000 units of work, and to create 200 characters takes 40,000 units of work.
This is why it took more than twice as long to create 200 characters than 100 characters. In fact, it should have taken four times as long. Our programming experience was correct in that the work is being done slightly more efficiently for longer strings, and hence it took only about three times as long. Once the overhead of the function call becomes negligible as to how long of a string we're creating, it will actually take four times as much time to create a string twice as long.
(Historical note: This analysis doesn't necessarily apply to strings in source code, such as html = 'abcd\n' + 'efgh\n' + ... + 'xyz.\n'
, since the JavaScript source code compiler can join the strings together before making them into a JavaScript string object. Just a few years ago, the KJS implementation of JavaScript would freeze or crash when loading long strings of source code joined by plus signs. Since the computational time was O(N^2)
it wasn't difficult to make Web pages which overloaded the Konqueror Web browser or Safari, which used the KJS JavaScript engine core. I first came across this issue when I was developing a markup language and JavaScript markup language parser, and then I discovered what was causing the problem when I wrote my script for JavaScript Includes.)
Clearly this rapid degradation of performance is a huge problem. How can we deal with it, given that we cannot change JavaScript's way of handling strings as immutable objects? The solution is to use an algorithm which recreates the string as few times as possible.
To clarify, our goal is to avoid adding short strings to long strings, since in order to add the short string, the entire long string also must be duplicated.
How the algorithm works to avoid adding short strings to long strings
Here's a good way to reduce the number of times new string objects are created. Concatenate longer lengths of string together so that more than one byte at a time is added to the output.
For instance, to make a string of length N = 9
:
x = 'x';
s = '';
s += x; /* Now s = 'x' */
x += x; /* Now x = 'xx' */
x += x; /* Now x = 'xxxx' */
x += x; /* Now x = 'xxxxxxxx' */
s += x; /* Now s = 'xxxxxxxxx' as desired */
Doing this required creating a string of length 1, creating a string of length 2, creating a string of length 4, creating a string of length 8, and finally, creating a string of length 9. How much cost have we saved?
Old cost C(9) = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 9 = 45
.
New cost C(9) = 1 + 2 + 4 + 8 + 9 = 24
.
Note that we had to add a string of length 1 to a string of length 0, then a string of length 1 to a string of length 1, then a string of length 2 to a string of length 2, then a string of length 4 to a string of length 4, then a string of length 8 to a string of length 1, in order to obtain a string of length 9. What we're doing can be summarized as avoiding adding short strings to long strings, or in other words, trying to concatenate strings together that are of equal or nearly equal length.
For the old computational cost we found a formula N(N+1)/2
. Is there a formula for the new cost? Yes, but it's complicated. The important thing is that it is O(N)
, and so doubling the string length will approximately double the amount of work rather than quadrupling it.
The code that implements this new idea is nearly as complicated as the formula for the computational cost. When you read it, remember that >>= 1
means to shift right by 1 byte. So if n = 10011
is a binary number, then n >>= 1
results in the value n = 1001
.
The other part of the code you might not recognize is the bitwise and operator, written &
. The expression n & 1
evaluates true if the last binary digit of n
is 1, and false if the last binary digit of n
is 0.
New highly-efficient stringFill3()
function
function stringFill3(x, n) {
var s = '';
for (;;) {
if (n & 1) s += x;
n >>= 1;
if (n) x += x;
else break;
}
return s;
}
It looks ugly to the untrained eye, but it's performance is nothing less than lovely.
Let's see just how well this function performs. After seeing the results, it's likely that you'll never forget the difference between an O(N^2)
algorithm and an O(N)
algorithm.
stringFill1()
takes 88.7 microseconds (millionths of a second) to create a 200-byte string, stringFill2()
takes 62.54, and stringFill3()
takes only 4.608. What made this algorithm so much better? All of the functions took advantage of using local function variables, but taking advantage of the second and third optimization techniques added a twenty-fold improvement to performance of stringFill3()
.
Deeper analysis
What makes this particular function blow the competition out of the water?
As I've mentioned, the reason that both of these functions, stringFill1()
and stringFill2()
, run so slowly is that JavaScript strings are immutable. Memory cannot be reallocated to allow one more byte at a time to be appended to the string data stored by JavaScript. Every time one more byte is added to the end of the string, the entire string is regenerated from beginning to end.
Thus, in order to improve the script's performance, one must precompute longer length strings by concatenating two strings together ahead of time, and then recursively building up the desired string length.
For instance, to create a 16-letter byte string, first a two byte string would be precomputed. Then the two byte string would be reused to precompute a four-byte string. Then the four-byte string would be reused to precompute an eight byte string. Finally, two eight-byte strings would be reused to create the desired new string of 16 bytes. Altogether four new strings had to be created, one of length 2, one of length 4, one of length 8 and one of length 16. The total cost is 2 + 4 + 8 + 16 = 30.
In the long run this efficiency can be computed by adding in reverse order and using a geometric series starting with a first term a1 = N and having a common ratio of r = 1/2. The sum of a geometric series is given by a_1 / (1-r) = 2N
.
This is more efficient than adding one character to create a new string of length 2, creating a new string of length 3, 4, 5, and so on, until 16. The previous algorithm used that process of adding a single byte at a time, and the total cost of it would be n (n + 1) / 2 = 16 (17) / 2 = 8 (17) = 136
.
Obviously, 136 is a much greater number than 30, and so the previous algorithm takes much, much more time to build up a string.
To compare the two methods you can see how much faster the recursive algorithm (also called "divide and conquer") is on a string of length 123,457. On my FreeBSD computer this algorithm, implemented in the stringFill3()
function, creates the string in 0.001058 seconds, while the original stringFill1()
function creates the string in 0.0808 seconds. The new function is 76 times faster.
The difference in performance grows as the length of the string becomes larger. In the limit as larger and larger strings are created, the original function behaves roughly like C1
(constant) times N^2
, and the new function behaves like C2
(constant) times N
.
From our experiment we can determine the value of C1
to be C1 = 0.0808 / (123457)2 = .00000000000530126997
, and the value of C2
to be C2 = 0.001058 / 123457 = .00000000856978543136
. In 10 seconds, the new function could create a string containing 1,166,890,359 characters. In order to create this same string, the old function would need 7,218,384 seconds of time.
This is almost three months compared to ten seconds!
I'm only answering (several years late) because my original solution to this problem has been floating around the Internet for more than 10 years, and apparently is still poorly-understood by the few who do remember it. I thought that by writing an article about it here I would help:
Performance Optimizations for High Speed JavaScript / Page 3
Unfortunately, some of the other solutions presented here are still some of those that would take three months to produce the same amount of output that a proper solution creates in 10 seconds.
I want to take the time to reproduce part of the article here as a canonical answer on Stack Overflow.
Note that the best-performing algorithm here is clearly based on my algorithm and was probably inherited from someone else's 3rd or 4th generation adaptation. Unfortunately, the modifications resulted in reducing its performance. The variation of my solution presented here perhaps did not understand my confusing for (;;)
expression which looks like the main infinite loop of a server written in C, and which was simply designed to allow a carefully-positioned break statement for loop control, the most compact way to avoid exponentially replicating the string one extra unnecessary time.
I'm using Jquery Load to handels this, works great for me. check out my code from my project. I need to refresh with arguments to put Javascript variable into php
if (isset($_GET['language'])){
$language = $_GET['language'];
}else{
echo '<script>';
echo ' var userLang = navigator.language || navigator.userLanguage;';
echo ' if(userLang.search("zh") != -1) {';
echo ' var language = "chn";';
echo ' }else{';
echo ' var language = "eng";';
echo ' }';
echo '$("html").load("index.php","language=" + language);';
echo '</script>';
die;
}
the URL is also encrypted, you really only have the IP, Port and if SNI, the host name that are unencrypted.
I found another solution elsewhere; that is, to use
upper(@yourString)
but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.
Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks. There's no splitting or regular expression. It scans the input string 1-2 characters at a time and builds an array.
Test it at http://jsfiddle.net/vHKYH/.
function parseCSV(str) {
var arr = [];
var quote = false; // 'true' means we're inside a quoted field
// Iterate over each character, keep track of current row and column (of the returned array)
for (var row = 0, col = 0, c = 0; c < str.length; c++) {
var cc = str[c], nc = str[c+1]; // Current character, next character
arr[row] = arr[row] || []; // Create a new row if necessary
arr[row][col] = arr[row][col] || ''; // Create a new column (start with empty string) if necessary
// If the current character is a quotation mark, and we're inside a
// quoted field, and the next character is also a quotation mark,
// add a quotation mark to the current column and skip the next character
if (cc == '"' && quote && nc == '"') { arr[row][col] += cc; ++c; continue; }
// If it's just one quotation mark, begin/end quoted field
if (cc == '"') { quote = !quote; continue; }
// If it's a comma and we're not in a quoted field, move on to the next column
if (cc == ',' && !quote) { ++col; continue; }
// If it's a newline (CRLF) and we're not in a quoted field, skip the next character
// and move on to the next row and move to column 0 of that new row
if (cc == '\r' && nc == '\n' && !quote) { ++row; col = 0; ++c; continue; }
// If it's a newline (LF or CR) and we're not in a quoted field,
// move on to the next row and move to column 0 of that new row
if (cc == '\n' && !quote) { ++row; col = 0; continue; }
if (cc == '\r' && !quote) { ++row; col = 0; continue; }
// Otherwise, append the current character to the current column
arr[row][col] += cc;
}
return arr;
}
For Notepad++ 64-bit:
There is an unreleased 64-bit version of this plugin. You can download the DLL from here, drop it under Notepad++/plugins/NppTextFX directory and restart Notepad++. You will need to create the NppTextFX directory first though.
As per this GitHub issue, there might be some bugs lurking around. If you run into any, feel free to raise a GitHub ticket for each, as the author (HQJaTu) is recommending. As per the author, the code behind this binary is found on this branch.
Tested on Notepad++ v7.5.8 (64-bit, Build time: Jul 23 2018)
I wonder why "amend" is not suggest and have been crossed out by @damkrat, as amend appears to me as just the right way to resolve the most efficiently the underlying problem of fixing the wrong commit since there is no purpose of having no initial commit. As some stressed out you should only modify "public" branch like master if no one has clone your repo...
git add <your different stuff>
git commit --amend --author="author name <[email protected]>"-m "new message"
You can write the command also for Bitbucket as mentioned by Dustin:
git push -f origin HEAD^:master
Note: instead of master you can use any branch. And it deletes just push on Bitbucket.
To remove last commit locally in git use:
git reset --hard HEAD~1
In Spyder one can configure the IPython console for each Python file to clear all variables before each execution in the Menu Run -> Configuration -> General settings -> Remove all variables before execution
.
If you have renamed anything verify the (Properties/) AssemblyInfo.cs
is correct, as well as the header in the service file.
ServiceName.svc
<%@ ServiceHost Language="C#" Debug="true" Service="Company.Namespace.WcfApp" CodeBehind="WcfApp.svc.cs" %>
Aligning with your namespace in your Service.svc.cs
For environment variable in Maven, you can set below.
http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html#environmentVariables http://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html#environmentVariables
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
...
<configuration>
<includes>
...
</includes>
<environmentVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</environmentVariables>
</configuration>
</plugin>