If you have set up your UIBarButtonItem with an image in the storyboard, one small hack to change the renderingMode is to add the following code to your viewDidLoad(). This way you don't have to resort to adding the entire button and image in code.
if let navButton = self.navigationItem.leftBarButtonItem, let buttonImage = navButton.image {
navButton.image = buttonImage.withRenderingMode(.alwaysOriginal)
}
Here is my solution. Works in most browsers
document.getElementById("scrollHere").scrollIntoView({behavior: "smooth"});
document.getElementById("end").scrollIntoView({behavior: "smooth"});
_x000D_
body {margin: 0px; display: block; height: 100%; background-image: linear-gradient(red, yellow);}_x000D_
.start {display: block; margin: 100px 10px 1000px 0px;}_x000D_
.end {display: block; margin: 0px 0px 100px 0px;}
_x000D_
<div class="start">Start</div>_x000D_
<div class="end" id="end">End</div>
_x000D_
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
You can do it this way:
=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))
Note I assume you meant >=
and <=
here since your description skipped the values 5
and 21
, but you can adjust these inequalities as needed.
Or you can do it this way:
=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))
To expand a bit on Hossein Narimani Rad's answer, you can rename both a table and columns using System.ComponentModel.DataAnnotations.Schema.TableAttribute and System.ComponentModel.DataAnnotations.Schema.ColumnAttribute respectively.
This has a couple benefits:
For example, adding [Table("Staffs")]
:
[Table("Staffs")]
public class AccountUser
{
public long Id { get; set; }
public long AccountId { get; set; }
public string ApplicationUserId { get; set; }
public virtual Account Account { get; set; }
public virtual ApplicationUser User { get; set; }
}
Will generate the migration:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AccountUsers_Accounts_AccountId",
table: "AccountUsers");
migrationBuilder.DropForeignKey(
name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
table: "AccountUsers");
migrationBuilder.DropPrimaryKey(
name: "PK_AccountUsers",
table: "AccountUsers");
migrationBuilder.RenameTable(
name: "AccountUsers",
newName: "Staffs");
migrationBuilder.RenameIndex(
name: "IX_AccountUsers_ApplicationUserId",
table: "Staffs",
newName: "IX_Staffs_ApplicationUserId");
migrationBuilder.RenameIndex(
name: "IX_AccountUsers_AccountId",
table: "Staffs",
newName: "IX_Staffs_AccountId");
migrationBuilder.AddPrimaryKey(
name: "PK_Staffs",
table: "Staffs",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_Staffs_Accounts_AccountId",
table: "Staffs",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Staffs_AspNetUsers_ApplicationUserId",
table: "Staffs",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Staffs_Accounts_AccountId",
table: "Staffs");
migrationBuilder.DropForeignKey(
name: "FK_Staffs_AspNetUsers_ApplicationUserId",
table: "Staffs");
migrationBuilder.DropPrimaryKey(
name: "PK_Staffs",
table: "Staffs");
migrationBuilder.RenameTable(
name: "Staffs",
newName: "AccountUsers");
migrationBuilder.RenameIndex(
name: "IX_Staffs_ApplicationUserId",
table: "AccountUsers",
newName: "IX_AccountUsers_ApplicationUserId");
migrationBuilder.RenameIndex(
name: "IX_Staffs_AccountId",
table: "AccountUsers",
newName: "IX_AccountUsers_AccountId");
migrationBuilder.AddPrimaryKey(
name: "PK_AccountUsers",
table: "AccountUsers",
column: "Id");
migrationBuilder.AddForeignKey(
name: "FK_AccountUsers_Accounts_AccountId",
table: "AccountUsers",
column: "AccountId",
principalTable: "Accounts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_AccountUsers_AspNetUsers_ApplicationUserId",
table: "AccountUsers",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
or can do this...
set all btn ( class name like : .btn-
+ $theme-colors: map-merge
) styles at one time :
@each $color, $value in $theme-colors {
.btn-#{$color} {
@include button-variant($value, $value,
// modify
$hover-background: lighten($value, 7.5%),
$hover-border: lighten($value, 10%),
$active-background: lighten($value, 10%),
$active-border: lighten($value, 12.5%)
// /modify
);
}
}
// code from "node_modules/bootstrap/scss/_buttons.scss"
should add into your customization scss file.
Whatever your separator is in your ls.dat, you can specify it to gnuplot:
set datafile separator "\t"
It could be due to the architecture of your OS. Is your OS 64 Bit and have you installed 64 bit version of Python? It may help to install both 32 bit version Python 3.1 and Pygame, which is available officially only in 32 bit and you won't face this problem.
I see that 64 bit pygame is maintained here, you might also want to try uninstalling Pygame only and install the 64 bit version on your existing python3.1, if not choose go for both 32-bit version.
You could do:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
You can then set the property like follows:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
This is very simple and straight forward to server the static content from outside webapps folder in tomcat.
Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
**<Context docBase="C:\Ankur\testFiles" path="/companyLogo" />**
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
Add the context element inside the host element with two attribute docBase and path.
1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.
For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:
http://localhost:8081/companyLogo/7.png
For more details, check the blog
The Ruby Style Guide says it better than I could:
Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)
# boolean expression
if some_condition && some_other_condition
do_something
end
# control flow
document.saved? or document.save!
Speaking from a PC user - Reboot.
Honestly, it worked for me. I've solved two strange git issues I thought were corruptions this way.
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':
', exe: F:
, which will take you to the drive named 'F' on your machine. Then using the command cd
to navigate your way inside that drive as you normally would.
What do you mean by nothing?
<a href='about:blank'>blank page</a>
or
<a href='whatever' onclick='return false;'>won't navigate</a>
Shubham answer didn't work for me.
When you are using axios library and to pass custom headers, you need to construct headers as an object with key name "headers". The headers key should contain an object, here it is Content-Type and Authorization.
Below example is working fine.
var headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {"headers" : headers})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
Unless you have very, very well-behaved data, this is a non-trivial challenge. A naive approach would be to tokenize on whitespace and assume that a three-token result is [first, middle, last] and a two-token result is [first, last], but you're going to have to deal with multi-word surnames (e.g. "Van Buren") and multiple middle names.
Use your bean class like this, if your JSON data starts with an an array object. it helps you.
Users[] bean = gson.fromJson(response,Users[].class);
Users is my bean class.
Response is my JSON data.
This works
psql dbname -F , --no-align -c "SELECT * FROM TABLE"
For a three dimensional array you could try:
for c in array.transpose(1, 0, 2):
do_stuff(c)
See the docs on how array.transpose
works. Basically you are specifying which dimension to shift. In this case we are shifting the second dimension (e.g. columns) to the first dimension.
To give the simplest answer I can think of:
Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.
Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.
(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)
Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.
We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.
You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.
So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.
// Use ..
const Per = {
name: 'HAMZA',
age: 20,
coords: {
tele: '09',
lan: '190'
},
setAge(age: Number): void {
this.age = age;
},
getAge(): Number {
return age;
}
};
const { age, name }: { age: Number; name: String } = Per;
const {
coords: { tele, lan }
}: { coords: { tele: String; lan: String } } = Per;
console.log(Per.getAge());
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
var destinationReader = StreamReader(fs);
var writer = StreamWriter(fs);
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
destinationReader .ReadLine();
}
line_number++;
}
}
When you compare update_date >= '2013-05-03'
postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.
So for update_date = '2013-05-03 14:45:00' your expression will be that:
'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'
This is always false
To solve this problem cast update_date to date
:
select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result
Here's a hack (updated with entire .html file):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
</head>
<body>
<label for="startDate">Date :</label>
<input name="startDate" id="startDate" class="date-picker" />
</body>
</html>
EDIT jsfiddle for the above example: http://jsfiddle.net/DBpJe/7755/
EDIT 2 Adds the month year value to input box only on clicking of Done button. Also allows to delete input box values, which isn't possible in above field http://jsfiddle.net/DBpJe/5103/
EDIT 3
updated Better Solution based on rexwolf's solution down.
http://jsfiddle.net/DBpJe/5106
Try this one:
string strDate = DateTime.Now.ToString("MM/01/yyyy");
I guess you want to do this:
$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
$avg = round($total_rating_points / $total_rating_count, 1);
I don't like adding new package into my project just to handle this simple task.
And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.
So I made a function to get all the folder content (and its sub folder).... NON-Recursively
var getDirectoryContent = function(dirPath) {
/*
get list of files and directories from given dirPath and all it's sub directories
NON RECURSIVE ALGORITHM
By. Dreamsavior
*/
var RESULT = {'files':[], 'dirs':[]};
var fs = fs||require('fs');
if (Boolean(dirPath) == false) {
return RESULT;
}
if (fs.existsSync(dirPath) == false) {
console.warn("Path does not exist : ", dirPath);
return RESULT;
}
var directoryList = []
var DIRECTORY_SEPARATOR = "\\";
if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;
directoryList.push(dirPath); // initial
while (directoryList.length > 0) {
var thisDir = directoryList.shift();
if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;
var thisDirContent = fs.readdirSync(thisDir);
while (thisDirContent.length > 0) {
var thisFile = thisDirContent.shift();
var objPath = thisDir+thisFile
if (fs.existsSync(objPath) == false) continue;
if (fs.lstatSync(objPath).isDirectory()) { // is a directory
let thisDirPath = objPath+DIRECTORY_SEPARATOR;
directoryList.push(thisDirPath);
RESULT['dirs'].push(thisDirPath);
} else { // is a file
RESULT['files'].push(objPath);
}
}
}
return RESULT;
}
the only drawback of this function is that this is Synchronous function... You have been warned ;)
new Double(object.toString());
But it seems weird to me that you're going from an Object to a Double. You should have a better idea what class of object you're starting with before attempting a conversion. You might have a bit of a code quality problem there.
Note that this is a conversion, not casting.
You need astype
:
df['zipcode'] = df.zipcode.astype(str)
#df.zipcode = df.zipcode.astype(str)
For converting to categorical
:
df['zipcode'] = df.zipcode.astype('category')
#df.zipcode = df.zipcode.astype('category')
Another solution is Categorical
:
df['zipcode'] = pd.Categorical(df.zipcode)
Sample with data:
import pandas as pd
df = pd.DataFrame({'zipcode': {17384: 98125, 2680: 98107, 722: 98005, 18754: 98109, 14554: 98155}, 'bathrooms': {17384: 1.5, 2680: 0.75, 722: 3.25, 18754: 1.0, 14554: 2.5}, 'sqft_lot': {17384: 1650, 2680: 3700, 722: 51836, 18754: 2640, 14554: 9603}, 'bedrooms': {17384: 2, 2680: 2, 722: 4, 18754: 2, 14554: 4}, 'sqft_living': {17384: 1430, 2680: 1440, 722: 4670, 18754: 1130, 14554: 3180}, 'floors': {17384: 3.0, 2680: 1.0, 722: 2.0, 18754: 1.0, 14554: 2.0}})
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode int64
dtype: object
df['zipcode'] = df.zipcode.astype('category')
print (df)
bathrooms bedrooms floors sqft_living sqft_lot zipcode
722 3.25 4 2.0 4670 51836 98005
2680 0.75 2 1.0 1440 3700 98107
14554 2.50 4 2.0 3180 9603 98155
17384 1.50 2 3.0 1430 1650 98125
18754 1.00 2 1.0 1130 2640 98109
print (df.dtypes)
bathrooms float64
bedrooms int64
floors float64
sqft_living int64
sqft_lot int64
zipcode category
dtype: object
I tested all the solutions above and finally decided to empty my Maven repository manually (I actually deleted the .m2
folder on linux). It did the trick.
This is a very tricky issue - even if you're familiar with how things are working in https with certificates (OTOH if you see my workaround, it seems very logical :)
If you want to connect to a GIT repository via http(s) from shell, you would make sure to have the public certificate stored (as file) on your machine. Then you would add that certificate to your GIT configuration
git config [--global] http.sslCAInfo "certificate"
(replace "certificate" with the complete path/name of the PEM file :)
For shell usage you would as well e.g. supply a '.netrc' provding your credentials for the http-server login. Having done that, you shall be able to do a 'git clone https://...' without any interactive provisioning of credentials.
However, for the Jenkins-service it's a bit different ... Here, the jenkins process needs to be aware of the server certificate - and it doesn't use the shell settings (in the meaning of the global git configuration file '.gitconfig') :P
What I needed to do is to add another parameter to the startup options of Jenkins.
... -Djavax.net.ssl.trustStore="keystore" ...
(replace "keystore" with the complete path/name like explained below :)
Now copy the keystore file of your webserver holding the certificate to some path (I know this is a dirty hack and not exactly secure :) and refer to it with the '-Djavax.net.ssl.trustStore=' parameter.
Now the Jenkins service will accept the certificate from the webserver providing the repository via https. Configure the GIT repository URL like
Note that you still require the '.netrc' under the jenkins-user home folder for the logon !!! Thus what I describe is to be seen as a workaround ... until a properly working credentials helper plugin is provided. IMHO this plugin (in its current version 1.9.4) is buggy.
I could never get the credentials-helper to work from Jenkins no matter what I tried :( At best I got to see some errors about the not accessible temporary credential helper file, etc. You can see lots of bugs reported about it in the Jenkins JIRA, but no fix.
So if somebody got it to work okay, please share the knowledge ...
P.S.: Using the Jenkins plugins in the following versions:
Credentials plugin 1.9.4, GIT client plugin 1.6.1, Jenkins GIT plugin 2.0.1
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();
Would change "ABCb" to "Abcb"
In Qt5 you should use QtWidgets
instead of QtGui
#include <QtGui/QComboBox> // incorrect in QT5
#include <QtWidgets/QComboBox> // correct in QT5
Or
#include <QtGui/QStringListModel> // incorrect in QT5
#include <QtCore/QStringListModel> // correct in QT5
Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.
Records .Where(r => r.Name.Contains("lkjwer--_~[]"))
-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'
So I haven't tested it yet but it looks like potentially the ESCAPE '~'
keyword may allow for automatic escaping of a string for use within a like expression.
Probably use jenkins command line is another option, see https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI
So you can do
java -jar jenkins-cli.jar -s http://server get-job myjob > myjob.xml
java -jar jenkins-cli.jar -s http://server create-job newmyjob < myjob.xml
It works fine for me and I am used to store in inside my version control system
(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); // 12,345.67
The idea behind this solution is replacing matched sections with first match and comma, i.e. '$&,'
. The matching is done using lookahead approach. You may read the expression as "match a number if it is followed by a sequence of three number sets (one or more) and a dot".
TESTS:
1 --> "1.00"
12 --> "12.00"
123 --> "123.00"
1234 --> "1,234.00"
12345 --> "12,345.00"
123456 --> "123,456.00"
1234567 --> "1,234,567.00"
12345.67 --> "12,345.67"
DEMO: http://jsfiddle.net/hAfMM/9571/
You can also extend the prototype of Number
object to add additional support of any number of decimals [0 .. n]
and the size of number groups [0 .. x]
:
/**
* Number.prototype.format(n, x)
*
* @param integer n: length of decimal
* @param integer x: length of sections
*/
Number.prototype.format = function(n, x) {
var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
1234..format(); // "1,234"
12345..format(2); // "12,345.00"
123456.7.format(3, 2); // "12,34,56.700"
123456.789.format(2, 4); // "12,3456.79"
DEMO / TESTS: http://jsfiddle.net/hAfMM/435/
In this super extended version you may set different delimiter types:
/**
* Number.prototype.format(n, x, s, c)
*
* @param integer n: length of decimal
* @param integer x: length of whole part
* @param mixed s: sections delimiter
* @param mixed c: decimal delimiter
*/
Number.prototype.format = function(n, x, s, c) {
var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
num = this.toFixed(Math.max(0, ~~n));
return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};
12345678.9.format(2, 3, '.', ','); // "12.345.678,90"
123456.789.format(4, 4, ' ', ':'); // "12 3456:7890"
12345678.9.format(0, 3, '-'); // "12-345-679"
DEMO / TESTS: http://jsfiddle.net/hAfMM/612/
By default Build location
is in Derived Data
.
Please note: a path to a product can be changed if you delete DerivedData during development process and rebuild it again.
Xcode -> Preferences... -> Locations
You can change the location of Build location
. It will have an effect on the whole workspace
File -> Project/Workspace Settings... -> Advanced
You can change the location of Target using:
Project editor -> select a target -> Build Settings -> Per-configuration Build Products Path
The default value is$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
It makes sense if you want to create an autonomic Build location
Xcode 10.2.1
char ch = Character.MIN_VALUE;
The code above will initialize the variable ch
with the minimum value that a char can have (i.e. \u0000
).
The warning from your compiler is telling you that your format specifier doesn't match the data type you're passing to it.
Try using %lx
or %llx
. For more portability, include inttypes.h
and use the PRIx64
macro.
For example: printf("val = 0x%" PRIx64 "\n", val);
(note that it's string concatenation)
I got this problem because i uninstalled the jdk version 13 and reinstall the jdk version 8
Even though i have updated the path variables eclipse still pick the old configuration.
You need to edit the eclipse.ini file which is in your folder where eclipse.exe is placed.
Just update this file with the latest path so eclipse can pick it up
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
in activity used ContextCompat
ContextCompat.getColor(context, R.color.color_name)
in Adaper
private Context context;
context.getResources().getColor()
To explain the decorator in a simple way:
With:
@decor1
@decor2
def func(*args, **kwargs):
pass
When do:
func(*args, **kwargs)
You really do:
decor1(decor2(func))(*args, **kwargs)
If it's not mandatory to specify column names:
> cor(dt[, !c(1:3, 5)])
V4 V6 V7 V8 V9 V10
V4 1.00000000 -0.50472635 -0.07123705 0.9089868 -0.17232607 -0.77988709
V6 -0.50472635 1.00000000 0.05757776 -0.2374420 0.67334474 0.29476983
V7 -0.07123705 0.05757776 1.00000000 -0.1812176 -0.36093750 0.01102428
V8 0.90898683 -0.23744196 -0.18121755 1.0000000 0.21372140 -0.75798418
V9 -0.17232607 0.67334474 -0.36093750 0.2137214 1.00000000 -0.01179544
V10 -0.77988709 0.29476983 0.01102428 -0.7579842 -0.01179544 1.00000000
I think that the problem is the way that you retrieve the entity.
Maybe you are doing something like this:
Person p = (Person) session.load(Person.class, new Integer(id));
Try using the method get
instead of load
Person p = (Person) session.get(Person.class, new Integer(id));
The problem is that with load method you get just a proxy but not the real object. The proxy object doesn't have the properties already loaded so when the serialization happens there are no properties to be serialized. With the get method you actually get the real object, this object could in fact be serialized.
You can do this by using following code.
$('#dropDownId').val();
If you want to get the selected value from the select list`s options. This will do the trick.
$('#dropDownId option:selected').text();
In Chromium 81+, I have found the answer to be: go to chrome://extensions/, click to enable Developer Mode on the top right corner, then drag and drop your .user.js script.
For multiple selection dropdown list,cannot accomplish it directly using dropdown..Can be done in similar ways..
Either you have to use checkbox list or listbox (ajax inclusive)
http://www.codeproject.com/Articles/55184/MultiSelect-Dropdown-in-ASP-NET
Here are few steps that must be followed carefully
Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1
Return to your browser in phpmyadmin setup tab, and click New server.
Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.
If used in a FragmentActivity, try this:
The first page extends FragmentActivity
Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);
In the fragment, you just need to call getActivity()
first,
The second page extends Fragment:
String receive = getActivity().getIntent().getExtras().getString("name");
The shortcut to comment out or uncomment the selected text or current line:
Alternatively, use the menu: Edit > Comment
For the block comment you may want to use:
revalidate
is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate
will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel
are considered dirty by the RepaintManager
.
repaint
is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.
When using Typescript:
In my case I used the newer syntax of webpack v3.11 from their documentation page I just copied the css and style loaders configuration form their website. The commented out code (newer API) causes this error, see below.
module: {
loaders: [{
test: /\.ts$/,
loaders: ['ts-loader']
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
]
// ,
// rules: [{
// test: /\.css$/,
// use: [
// 'style-loader',
// 'css-loader'
// ]
// }]
}
The right way is to put this:
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader'
]
}
in the array of the loaders property.
My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well
ES6
const originalFruits = ["apple","banana","orange"];_x000D_
_x000D_
const fruits1 = ["apple","banana","pineapple"];_x000D_
_x000D_
const fruits2 = ["grape", "pineapple"];_x000D_
_x000D_
const commonFruits = (myFruitsArr, otherFruitsArr) => {_x000D_
return myFruitsArr.some(fruit => otherFruitsArr.includes(fruit))_x000D_
}_x000D_
console.log(commonFruits(originalFruits, fruits1)) //returns true;_x000D_
console.log(commonFruits(originalFruits, fruits2)) //returns false;
_x000D_
If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.
try this.
$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');
string x = "My name @is ,Wan.;'; Wan";
string modifiedString = x.Replace("@", "").Replace(",", "").Replace(".", "").Replace(";", "").Replace("'", "");
I took Crystalonics' answer and turned them into extension methods. I hope someone else will find them useful:
public static byte[] SerializeToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray) where T : class
{
if (byteArray == null)
{
return null;
}
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(byteArray, 0, byteArray.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = (T)binForm.Deserialize(memStream);
return obj;
}
}
Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after
// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });
// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bars = bs })
.SelectMany(
fooBars => fooBars.Bars.DefaultIfEmpty(),
(x,y) => new { Foo = x.Foo, Bar = y });
To display the difference using a simple data set (assuming we're joining on the values themselves):
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };
// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };
// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 } // Misleading, we had multiple matches.
// Which 3 should get selected (not arbitrarily the first)?.
// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
{ A = 3, B = 3 }
Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set.
Your JDK version: Java 8
Your JRE version: Java 9
Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java
into <yourclassname>.java
javac -source 1.8 -target 1.8 *.java
source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.
This will return the matching word or an error if no match is found. For this example I used the following.
List of words to search for: G1:G7
Cell to search in: A1
=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))
Enter as an array formula by pressing Ctrl+Shift+Enter.
This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX()
function, throwing an error.
To return the row number of a matching word, you can use the following:
=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))
This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1
if no match is found.
Open the Simulator app, not Xcode.
Then File >> Open Device >> Select iOS version >> select device.
The location of the 'open device' has changed in different Xcode versions so it may be at a different place
To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.
Yes, you should use docstrings to make your classes and functions more friendly to other programmers:
More: http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
Some editors allow you to see docstrings while typing, so it really makes work easier.
For a JPA 2.x example usage for the general case of two tables, with a @OneToMany
unidirectional join see https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Example_of_a_JPA_2.x_unidirectional_OneToMany_relationship_annotations
Screenshot from this WikiBooks JPA article: Example of a JPA 2.x unidirectional OneToMany relationship database
Try this: http://jsbin.com/axaler/3/edit
$(function(){
$(window).scroll(function(){
var aTop = $('.ad').height();
if($(this).scrollTop()>=aTop){
alert('header just passed.');
// instead of alert you can use to show your ad
// something like $('#footAd').slideup();
}
});
});
It's more readable a single try catch block. If its important identify a kind of error I recommend customize your Exceptions.
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
$tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (TableAException $e){
throw $e;
} catch (Exception $e) {
throw $e;
}
To plot an equation that is not solved for a specific variable (like circle or hyperbola):
import numpy as np
import matplotlib.pyplot as plt
plt.figure() # Create a new figure window
xlist = np.linspace(-2.0, 2.0, 100) # Create 1-D arrays for x,y dimensions
ylist = np.linspace(-2.0, 2.0, 100)
X,Y = np.meshgrid(xlist, ylist) # Create 2-D grid xlist,ylist values
F = X**2 + Y**2 - 1 # 'Circle Equation
plt.contour(X, Y, F, [0], colors = 'k', linestyles = 'solid')
plt.show()
More about it: http://courses.csail.mit.edu/6.867/wiki/images/3/3f/Plot-python.pdf
Sure, try:
input[value="United States"]{ color: red; }
Simply change body height < 300px (height of mobile viewport on landspace is around 300px to 500px)
JS
$( '.offcanvas-toggle' ).on( 'click', function() {
$( 'body' ).toggleClass( 'offcanvas-expanded' );
});
CSS
.offcanvas-expended { /* this is class added to body on click */
height: 200px;
}
.offcanvas {
height: 100%;
}
I've successfully implemented ReCaptcha in the following way.
note: this is in VB, but can easily be converted
1] First grab a copy of the reCaptcha library
2] Then build a custom ReCaptcha HTML Helper
''# fix SO code coloring issue.
<Extension()>
Public Function reCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString
Dim captchaControl = New Recaptcha.RecaptchaControl With {.ID = "recaptcha",
.Theme = "clean",
.PublicKey = "XXXXXX",
.PrivateKey = "XXXXXX"}
Dim htmlWriter = New HtmlTextWriter(New IO.StringWriter)
captchaControl.RenderControl(htmlWriter)
Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString)
End Function
3] From here you need a re-usable server side validator
Public Class ValidateCaptchaAttribute : Inherits ActionFilterAttribute
Private Const CHALLENGE_FIELD_KEY As String = "recaptcha_challenge_field"
Private Const RESPONSE_FIELD_KEY As String = "recaptcha_response_field"
Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
If IsNothing(filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)) Then
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = True
Return
End If
Dim captchaChallengeValue = filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)
Dim captchaResponseValue = filterContext.HttpContext.Request.Form(RESPONSE_FIELD_KEY)
Dim captchaValidtor = New RecaptchaValidator() With {.PrivateKey = "xxxxx",
.RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
.Challenge = captchaChallengeValue,
.Response = captchaResponseValue}
Dim recaptchaResponse = captchaValidtor.Validate()
''# this will push the result value into a parameter in our Action
filterContext.ActionParameters("CaptchaIsValid") = recaptchaResponse.IsValid
MyBase.OnActionExecuting(filterContext)
End Sub
Now that you have your re-usable code... all you need to do is add the captcha to your View.
<%: Html.reCaptcha %>
And when you post the form to your controller...
''# Fix SO code coloring issues
<ValidateCaptcha()>
<AcceptVerbs(HttpVerbs.Post)>
Function Add(ByVal CaptchaIsValid As Boolean, ByVal [event] As Domain.Event) As ActionResult
If Not CaptchaIsValid Then ModelState.AddModelError("recaptcha", "*")
'#' Validate the ModelState and submit the data.
If ModelState.IsValid Then
''# Post the form
Else
''# Return View([event])
End If
End Function
PyInstaller will create a single-file executable if you use the --onefile
option (though what it actually does is extracts then runs itself).
There's a simple PyInstaller tutorial here. If you have any questions about using it, please post them...
Use the modulus (%
) operator:
6 % 3 == 0
7 % 3 == 1
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
I've seen this error a few times too, and I've always been able to solve it by correctly identifying the project's module settings. In IntelliJ, right-click on the top level project -> "Open Module Settings". This should open up a window with the entire project structure and content identified as "Source Folders", "Test Source Folders", etc. Make sure these are correctly set. For the "Source Folders", ensure that the folder is your src/ or src/java (or whatever your source language is), as the case may be
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
serves two purposes.
IE=edge
: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.chrome=1
: specifies that Google Chrome frame should start if the user has it installedThe IE=edge
flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.
As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1
will do nothing more than consume a few bytes of bandwidth.
I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.
Note, the W3C validator will flag chrome=1
as an error:
Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.
The following recipe using Homebrew worked for me to update to gcc/g++ 4.7:
$ brew tap SynthiNet/synthinet
$ brew install gcc47
Found it on a post here.
Here is another way...
It adds "others" to the enum definition of the column "rtipo" of the table "firmas".
set @new_enum = 'others';
set @table_name = 'firmas';
set @column_name = 'rtipo';
select column_type into @tmp from information_schema.columns
where table_name = @table_name and column_name=@column_name;
set @tmp = insert(@tmp, instr(@tmp,')'), 0, concat(',\'', @new_enum, '\'') );
set @tmp = concat('alter table ', @table_name, ' modify ', @column_name, ' ', @tmp);
prepare stmt from @tmp;
execute stmt;
deallocate prepare stmt;
Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with using T = int (*)(int, int);
is clearer than with typedef int (*T)(int, int);
. Second is that template alias form is not possible with typedef
. Third is that exposing C API would require typedef
in public headers.
There is no such thing as connection on server side and/or browser side. There is only one connection. If one of the sides closes it, then it is closed (and you cannot push data to a connection that is closed obviously).
Now a browser closes the connection when you leave the page (it does not depend on the library/language/OS you are using on the sever-side). This is at least true for WebSockets (it might not be true for long polling because of keep-alive
but hopefuly socket.io handles this correctly).
If a problem like this happens, then I'm pretty sure that there's a bug in your own code (on the server side). Possibly you are stacking some event handlers where you should not.
Ok, i had a few problems because i was inside a
$('.my-dropdown').live('click', function(){
});
I had multiples inside my page that's why i used a class.
My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)
so...
I had to do:
$('.my-dropdown').live('click', function(){
total_tems = $(this).find('option').length;
});
Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows
On Windows its:
mov $source , %destination
but on the Mac its the other way around.
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
nextLine() will throw an exception when there's no line and it will never return null,you can try the Scanner Class instead : http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
I know that due to this ugly anonymous inner class usage of TransactionTemplate
doesn't look nice, but when for some reason we want to have a test method transactional IMHO it is the most flexible option.
In some cases (it depends on the application type) the best way to use transactions in Spring tests is a turned-off @Transactional
on the test methods. Why? Because @Transactional
may leads to many false-positive tests. You may look at this sample article to find out details. In such cases TransactionTemplate
can be perfect for controlling transaction boundries when we want that control.
Hope this will help:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>compute elapsed time in JavaScript</title>
<script type="text/javascript">
function display_c (start) {
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh = 1000; // Refresh rate in milli seconds
if( window.start >= end ) {
mytime = setTimeout( 'display_ct()',refresh )
} else {
alert("Time Over ");
}
}
function display_ct () {
// Calculate the number of days left
var days = Math.floor(window.start / 86400);
// After deducting the days calculate the number of hours left
var hours = Math.floor((window.start - (days * 86400 ))/3600)
// After days and hours , how many minutes are left
var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60)
// Finally how many seconds left after removing days, hours and minutes.
var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)))
var x = window.start + "(" + days + " Days " + hours + " Hours " + minutes + " Minutes and " + secs + " Secondes " + ")";
document.getElementById('ct').innerHTML = x;
window.start = window.start - 1;
tt = display_c(window.start);
}
function stop() {
clearTimeout(mytime);
}
</script>
</head>
<body>
<input type="button" value="Start Timer" onclick="display_c(86501);"/> | <input type="button" value="End Timer" onclick="stop();"/>
<span id='ct' style="background-color: #FFFF00"></span>
</body>
</html>
clear:both
makes the element drop below any floated elements that precede it in the document.
You can also use clear:left
or clear:right
to make it drop below only those elements that have been floated left or right.
+------------+ +--------------------+
| | | |
| float:left | | without clear |
| | | |
| | +--------------------+
| | +--------------------+
| | | |
| | | with clear:right |
| | | (no effect here, |
| | | as there is no |
| | | float:right |
| | | element) |
| | | |
| | +--------------------+
| |
+------------+
+---------------------+
| |
| with clear:left |
| or clear:both |
| |
+---------------------+
I used a for and while loop on a solid test machine (no non-standard 3rd party background processes running). I ran a for loop
vs while loop
as it relates to changing the style property of 10,000 <button>
nodes.
The test is was run consecutively 10 times, with 1 run timed out for 1500 milliseconds before execution:
Here is the very simple javascript I made for this purpose
function runPerfTest() {
"use strict";
function perfTest(fn, ns) {
console.time(ns);
fn();
console.timeEnd(ns);
}
var target = document.getElementsByTagName('button');
function whileDisplayNone() {
var x = 0;
while (target.length > x) {
target[x].style.display = 'none';
x++;
}
}
function forLoopDisplayNone() {
for (var i = 0; i < target.length; i++) {
target[i].style.display = 'none';
}
}
function reset() {
for (var i = 0; i < target.length; i++) {
target[i].style.display = 'inline-block';
}
}
perfTest(function() {
whileDisplayNone();
}, 'whileDisplayNone');
reset();
perfTest(function() {
forLoopDisplayNone();
}, 'forLoopDisplayNone');
reset();
};
$(function(){
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
setTimeout(function(){
console.log('cool run');
runPerfTest();
}, 1500);
});
Here are the results I got
pen.js:8 whileDisplayNone: 36.987ms
pen.js:8 forLoopDisplayNone: 20.825ms
pen.js:8 whileDisplayNone: 19.072ms
pen.js:8 forLoopDisplayNone: 25.701ms
pen.js:8 whileDisplayNone: 21.534ms
pen.js:8 forLoopDisplayNone: 22.570ms
pen.js:8 whileDisplayNone: 16.339ms
pen.js:8 forLoopDisplayNone: 21.083ms
pen.js:8 whileDisplayNone: 16.971ms
pen.js:8 forLoopDisplayNone: 16.394ms
pen.js:8 whileDisplayNone: 15.734ms
pen.js:8 forLoopDisplayNone: 21.363ms
pen.js:8 whileDisplayNone: 18.682ms
pen.js:8 forLoopDisplayNone: 18.206ms
pen.js:8 whileDisplayNone: 19.371ms
pen.js:8 forLoopDisplayNone: 17.401ms
pen.js:8 whileDisplayNone: 26.123ms
pen.js:8 forLoopDisplayNone: 19.004ms
pen.js:61 cool run
pen.js:8 whileDisplayNone: 20.315ms
pen.js:8 forLoopDisplayNone: 17.462ms
Here is the demo link
Update
A separate test I have conducted is located below, which implements 2 differently written factorial algorithms, 1 using a for loop, the other using a while loop.
Here is the code:
function runPerfTest() {
"use strict";
function perfTest(fn, ns) {
console.time(ns);
fn();
console.timeEnd(ns);
}
function whileFactorial(num) {
if (num < 0) {
return -1;
}
else if (num === 0) {
return 1;
}
var factl = num;
while (num-- > 2) {
factl *= num;
}
return factl;
}
function forFactorial(num) {
var factl = 1;
for (var cur = 1; cur <= num; cur++) {
factl *= cur;
}
return factl;
}
perfTest(function(){
console.log('Result (100000):'+forFactorial(80));
}, 'forFactorial100');
perfTest(function(){
console.log('Result (100000):'+whileFactorial(80));
}, 'whileFactorial100');
};
(function(){
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
runPerfTest();
console.log('cold run @1500ms timeout:');
setTimeout(runPerfTest, 1500);
})();
And the results for the factorial benchmark:
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.280ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.241ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.254ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.254ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.285ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.294ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.181ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.172ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.195ms
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.279ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.185ms
pen.js:55 cold run @1500ms timeout:
pen.js:38 Result (100000):7.156945704626378e+118
pen.js:8 forFactorial100: 0.404ms
pen.js:41 Result (100000):7.15694570462638e+118
pen.js:8 whileFactorial100: 0.314ms
Conclusion: No matter the sample size or specific task type tested, there is no clear winner in terms of performance between a while and for loop. Testing done on a MacAir with OS X Mavericks on Chrome evergreen.
The full list of readyState
values is:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
(from https://www.w3schools.com/js/js_ajax_http_response.asp)
In practice you almost never use any of them except for 4.
Some XMLHttpRequest implementations may let you see partially received responses in responseText
when readyState==3
, but this isn't universally supported and shouldn't be relied upon.
Use the -j
option:
-j Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current path).
In C# 7 you can now use tuples!... which eliminates the need to create a class just to return the result.
Here is a sample code:
public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
}.ToList();
return result.Select(r => (r.Name, r.BreedName)).ToList();
}
You might need to install System.ValueTuple nuget package though.
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)
And this sample is printing -> The number is : 1
declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)
For the full-screen responsive background image cover
<div class="full-screen">
</div>
CSS
.full-screen{
background-image: url("img_girl.jpg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
readonly
, for example:Then the reasonable solution would be to set all form elements' disabled
attributes to true
, since the OP did not state that the specific "locked" form should be sent to the server (which the disabled
attribute does not allow).
Another solution, which is presented in the demo below, is to place a layer on top of the form
element which will prevent any interaction with all the elements inside the form
element, since that layer is set with a greater z-index
value:
var form = document.forms[0], // form element to be "readonly"_x000D_
btn1 = document.querySelectorAll('button')[0],_x000D_
btn2 = document.querySelectorAll('button')[1]_x000D_
_x000D_
btn1.addEventListener('click', lockForm)_x000D_
btn2.addEventListener('click', lockFormByCSS)_x000D_
_x000D_
function lockForm(){_x000D_
btn1.classList.toggle('on');_x000D_
[].slice.call( form.elements ).forEach(function(item){_x000D_
item.disabled = !item.disabled;_x000D_
});_x000D_
}_x000D_
_x000D_
function lockFormByCSS(){_x000D_
btn2.classList.toggle('on');_x000D_
form.classList.toggle('lock');_x000D_
}
_x000D_
form{ position:relative; } _x000D_
form.lock::before{_x000D_
content:'';_x000D_
position:absolute;_x000D_
z-index:999;_x000D_
top:0;_x000D_
right:0;_x000D_
bottom:0;_x000D_
left:0;_x000D_
}_x000D_
_x000D_
button.on{ color:red; }
_x000D_
<button type='button'>Lock / Unlock Form</button>_x000D_
<button type='button'>Lock / Unlock Form (with CSS)</button>_x000D_
<br><br>_x000D_
<form>_x000D_
<fieldset>_x000D_
<legend>Some Form</legend>_x000D_
<input placeholder='text input'>_x000D_
<br><br>_x000D_
<input type='file'>_x000D_
<br><br>_x000D_
<textarea placeholder='textarea'></textarea>_x000D_
<br><br>_x000D_
<label><input type='checkbox'>Checkbox</label>_x000D_
<br><br>_x000D_
<label><input type='radio' name='r'>option 1</label>_x000D_
<label><input type='radio' name='r' checked>option 2</label>_x000D_
<label><input type='radio' name='r'>option 3</label>_x000D_
<br><br>_x000D_
<select>_x000D_
<option>options 1</option>_x000D_
<option>options 2</option>_x000D_
<option selected>options 3</option>_x000D_
</select>_x000D_
</fieldset>_x000D_
</form>
_x000D_
I tweaked the accepted answer to perform the operation for multiple dataframes on different suffix
parameters using reduce
and i guess it can be extended to different on
parameters as well.
from functools import reduce
dfs_with_suffixes = [(df2,suffix2), (df3,suffix3),
(df4,suffix4)]
merge_one = lambda x,y,sfx:pd.merge(x,y,on=['col1','col2'..], suffixes=sfx)
merged = reduce(lambda left,right:merge_one(left,*right), dfs_with_suffixes, df1)
In my mind @slugslog had it, but I would change one thing. I would use replace instead so you don't have to set it back.
$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id).replace();
$anchorScroll();
};
Docs Search for "Replace method"
Sort of:
class some_class {
static std::vector<std::string> v; // declaration
};
const char *vinit[] = {"one", "two", "three"};
std::vector<std::string> some_class::v(vinit, end(vinit)); // definition
end
is just so I don't have to write vinit+3
and keep it up to date if the length changes later. Define it as:
template<typename T, size_t N>
T * end(T (&ra)[N]) {
return ra + N;
}
I did
msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)
else
msgbox "Closing..."
// simple example using the concept of setInterval
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
Try the solution with is described here: Exact Substring Searches in ElasticSearch
{
"mappings": {
"my_type": {
"index_analyzer":"index_ngram",
"search_analyzer":"search_ngram"
}
},
"settings": {
"analysis": {
"filter": {
"ngram_filter": {
"type": "ngram",
"min_gram": 3,
"max_gram": 8
}
},
"analyzer": {
"index_ngram": {
"type": "custom",
"tokenizer": "keyword",
"filter": [ "ngram_filter", "lowercase" ]
},
"search_ngram": {
"type": "custom",
"tokenizer": "keyword",
"filter": "lowercase"
}
}
}
}
}
To solve the disk usage problem and the too-long search term problem short 8 characters long ngrams are used (configured with: "max_gram": 8). To search for terms with more than 8 characters, turn your search into a boolean AND query looking for every distinct 8-character substring in that string. For example, if a user searched for large yard (a 10-character string), the search would be:
"arge ya AND arge yar AND rge yard.
Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.
To do so:
Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.
You can easily do this one. In each column you will get a class with the field name prefixed with mat-column, so the class will be like mat-column-yourFieldName. So for that you can set the style like following
.mat-column-yourFieldName {
flex: none;
width: 100px;
}
So we can give fixed width for column as per our requirement.
Hope this helps for someone.
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
There is plenty of good answer to this question. Just gonna drop another one into the basket if you wish to do it with lolcat
lolcat FileName.csv | head -n 1
Based on your comments, we need to go over how the Bundling
mechanism works in MVC.
Edit: Based on the comment below by VSDev, you need to ensure WebGrease is installed into your project. NuGet would be the easiest was to install this package.
When you set a bundle configuration (Example not from above to illustrate)
bundles.Add(new ScriptBundle("~/bundles/mainJs")
.Include("~/Scripts/mainSite.js")
.Include("~/Scripts/helperStuff.js");
You then, in your views, call something like @Scripts.Render("~/bundles/mainJs")
. When your web.config is set into a debug compilation OR you explicitly turn off bundling using the following line in your BundleConfig.cs
file
BundleTable.EnableOptimizations = false;
Then, in your view, you will see the following rendered out
<script src="/Scripts/mainSite.js" type="text/javascript"></script>
<script src="/Scripts/helperStuff.js" type="text/javascript"></script>
These are the individual items that made up our bundle, uncompressed and listed individually. The reason these list out individually in debug mode is so that you can debug your scripts and see them as you wrote them (actual variable names, etc).
Now, when we are not in a debug compilation and have not turned off the EnableOptimizations
feature, MVC will combine those files in our bundles, compress (minify) them and output only a single script tag.
<script src="/bundles/mainJs?v=someBigLongNumber" type="text/javascript"></script>
Notice that the source is the same as the name of the bundle from the bundle configurations. Also, the number after the ?v=
will change anytime you change a file in that bundle. This is to help prevent caching of old js and css files by the client browsers.
Your scripts are still there and being outputted, but they are being compressed and combined into a single file called /bundles/mainJs
. This feature is present to
A) compress the files and reduce information being transmitted and,
B) reduce the number of calls to a website to retrieve the necessary content to render the page.
Nothing is missing, it sounds like everything is working as intended. In a production site, the minification makes these files almost impossible to read, thus why the minification does not take affect while debugging.
As to why the jQuery UI is still being a single JS file, ensure someone didn't hard code that into your layout view. As for the JS errors, it could be errors that are present on your development box or perhaps something did not compress correctly (however, in all of my MVC development, I have not seen a JS error because of bad minification).
Exec time for the 3 answers :
Remove the first letter by replacing the case
$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo
Exec time for 1.000.000 tests : 0.39602184295654
sec
Remove the first letter with substr()
$str = "hello";
$str = substr($str, 1);
Exec time for 1.000.000 tests : 5.153294801712
sec
Remove the first letter with ltrim()
$str = "hello";
$str= ltrim ($str,'h');
Exec time for 1.000.000 tests : 5.2393000125885
sec
Remove the first letter with preg_replace()
$str = "hello";
$str = preg_replace('/^./', '', $str);
Exec time for 1.000.000 tests : 6.8543920516968
sec
Since you haven't given table definitions, it's hard to guess. But it looks like you are attempting to modify the foreign key in the child table. AFAIK, this is illegal, you can modify it from the parent, but not the child table.
Consider this example:
CREATE TABLE parent (
parent_id INT NOT NULL,
parent_data int,
PRIMARY KEY (parent_id)
) ENGINE=INNODB;
CREATE TABLE child1 (
child1_id INT,
child1_data INT,
fk_parent_id INT,
INDEX par_ind1 (fk_parent_id),
FOREIGN KEY (fk_parent_id)
REFERENCES parent(parent_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
CREATE TABLE child2 (
child2_id INT,
child2_data INT,
fk_parent_id INT,
INDEX par_ind2 (fk_parent_id),
FOREIGN KEY (fk_parent_id)
REFERENCES parent(parent_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=INNODB;
INSERT INTO parent
(parent_id, parent_data)
VALUES
(1, 11),
(2, 12);
INSERT INTO child1
(child1_id, child1_data, fk_parent_id)
VALUES
(101, 1001, 1),
(102, 1002, 1),
(103, 1003, 1),
(104, 1004, 2),
(105, 1005, 2);
INSERT INTO child2
(child2_id, child2_data, fk_parent_id)
VALUES
(106, 1006, 1),
(107, 1007, 1),
(108, 1008, 1),
(109, 1009, 2),
(110, 1010, 2);
Then this is allowed:
UPDATE parent
SET parent_id = 3 WHERE parent_id = 2;
SELECT * FROM parent;
SELECT * FROM child1;
SELECT * FROM child2;
But this is not, because it modifies the parent fk from the child table:
UPDATE child1
SET fk_parent_id = 4 WHERE fk_parent_id = 1;
It gets an error very similar to your error:
Cannot add or update a child row: a foreign key constraint fails (`db_2_b43a7`.`child1`, CONSTRAINT `child1_ibfk_1` FOREIGN KEY (`fk_parent_id`) REFERENCES `parent` (`parent_id`) ON DELETE CASCADE ON UPDATE CASCADE):
If your JSON is without key you can do it like this:
library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
So, try this:
var library = {[{
"title" : "Gold Rush",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["1.jpg","","2.jpg"]
}, {
"title" : California",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["3.jpg","4.jpg","5.jpg"]
}]
}
Then:
library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};
The selected answer does not work.
declare @str varchar(50)='79D136'
select 1 where @str NOT LIKE '%[^0-9]%'
I don't have a solution but know of this potential pitfall. The same goes if you substitute the letter 'D' for 'E' which is scientific notation.
There are two directories that looks like JDK.
C:\Program Files\Java\jdk1.7.0_02
C:\Program Files (x86)\Java\jdk1.7.0_02\
This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe
seen by ant.bat should from the JDK. If the JRE's java.exe
comes first in the path, that will be used to guess the JDK location.
Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.
Further steps:
You can take output of ant -diagnostics
and look for interesting keys. (assuming Sun/Oracle JDK).
java.class.path
java.library.path
sun.boot.library.path
(in my case tools.jar appears in java.class.path)
ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
By using this code, you'll get your live time zone.
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
I had the same problem and executing npm config delete prefix
did not help me.
But this did:
After installing nvm using brew, create ~/.nvm
directory:
$ mkdir ~/.nvm
and add following lines into ~/.bash_profile
:
export NVM_DIR=~/.nvm
. $(brew --prefix nvm)/nvm.sh
(Check that you have no other nvm related command in any ~/.bashrc
or ~/.profile
or ~/.bash_profile
)
Open a new terminal and this time it should not print any warning message.
Check that nvm is working by executing nvm --version
command.
After that, install/reinstall NodeJS using nvm install node && nvm alias default node
.
More Info
I installed nvm
using homebrew
and after that I got this notification:
Please note that upstream has asked us to make explicit managing nvm via Homebrew is unsupported by them and you should check any problems against the standard nvm install method prior to reporting.
You should create NVM's working directory if it doesn't exist:
mkdir ~/.nvm
Add the following to
~/.bash_profile
or your desired shell configuration file:export NVM_DIR=~/.nvm . $(brew --prefix nvm)/nvm.sh
You can set
$NVM_DIR
to any location, but leaving it unchanged from/usr/local/Cellar/nvm/0.31.0
will destroy any nvm-installed Node installations upon upgrade/reinstall.
Ignoring it brought me to this error message:
nvm
is not compatible with thenpm config
"prefix" option: currently set to"/usr/local/Cellar/nvm/0.31.0/versions/node/v5.7.1"
Runnvm use --delete-prefix v5.7.1 --silent
to unset it.
I followed an earlier guide (from homebrew/nvm
) and after that I found that I needed to reinstall NodeJS. So I did:
nvm install node && nvm alias default node
and it was fixed.
Update: Using brew to install NVM causes slow startup of the Terminal. You can follow this instruction to resolve it.
Don't use it. The description says:
Register one or more global variables with the current session.
Two things that came to my mind:
$_SESSION['var'] = "value"
.See also the warnings from the manual:
If you want your script to work regardless of
register_globals
, you need to instead use the$_SESSION
array as$_SESSION
entries are automatically registered. If your script usessession_register()
, it will not work in environments where the PHP directiveregister_globals
is disabled.
This is pretty important, because the register_globals
directive is set to False
by default!
Further:
This registers a
global
variable. If you want to register a session variable from within a function, you need to make sure to make it global using theglobal
keyword or the$GLOBALS[]
array, or use the special session arrays as noted below.
and
If you are using
$_SESSION
(or$HTTP_SESSION_VARS
), do not usesession_register()
,session_is_registered()
, andsession_unregister()
.
Have you considered using Javascript for this?
$('input').val($('input').val().replace(',', '.'));
Generally a parameter is what appears in the definition of the method. An argument is the instance passed to the method during runtime.
You can see a description here: http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments
You're looking for UPDATE not insert.
UPDATE mytable
SET table_column = 'test';
UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).
Array is not a primitive type, and the arrays belong to different addresses in the C++ memory.
$('#mySelect').val('fg');...........
A view is a virtual table. A view consists of rows and columns just like a table. The difference between a view and a table is that views are definitions built on top of other tables (or views), and do not hold data themselves. If data is changing in the underlying table, the same change is reflected in the view. A view can be built on top of a single table or multiple tables. It can also be built on top of another view. In the SQL Create View page, we will see how a view can be built.
Views offer the following advantages:
Ease of use: A view hides the complexity of the database tables from end users. Essentially we can think of views as a layer of abstraction on top of the database tables.
Space savings: Views takes very little space to store, since they do not store actual data.
Additional data security: Views can include only certain columns in the table so that only the non-sensitive columns are included and exposed to the end user. In addition, some databases allow views to have different security settings, thus hiding sensitive data from prying eyes.
Answer from:http://www.1keydata.com/sql/sql-view.html
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
While iterating over a list or array with this method:
ar = [10, 11, 12]
for i in ar:
theSum = theSum + ar[i]
You are actually getting the values of list or array sequentially in i
variable.
If you print the variable i
inside the for loop
. You will get following output:
10
11
12
However, in your code you are confusing i
variable with index value of array. Therefore, while doing ar[i]
will mean ar[10]
for the first iteration. Which is of course index out of range throwing IndexError
Edit You can read this for better understanding of different methods of iterating over array or list in Python
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.
-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory
-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder
-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf
-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.
If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop
Create sample .php file and put below code and run on wamp or xampp server
$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);
This code working for me in windows-8 operating system
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
Short answer: use an unassigned user port
Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.
The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.
You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.
The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.
The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.
Using LD_PRELOAD
path, you can force the application loader to load provided shared object, over the default provided.
Developers uses this to debug their applications by providing different versions of the shared objects.
We've used it to hack certain applications, by overriding existing functions using prepared shared objects.
This is an example of the use of this pattern that worked for me on empty datagrids.
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
app[func].apply(this, args);
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command for Laravel 4:
php artisan migrate:make add_paid_to_users
And for laravel 5 version
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
Then you need to use the Schema::table() . And you have to add the column:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
further you can check this
First of all you need to make the field Nullable, then after that so simple - instead of putting a value put this code CURRENT_TIMESTAMP
.
Use a regular expression for .replace()
.:
messagetoSend = messagetoSend.replace(/\n/g, "<br />");
If those linebreaks were made by windows-encoding, you will also have to replace the carriage return
.
messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");
How to convert array to json String in swift 2.3
var yourString : String = ""
do
{
if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(yourArray, options: NSJSONWritingOptions.PrettyPrinted)
{
yourString = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
}
}
catch
{
print(error)
}
And now you can use yourSting as JSON string..
Or in restSharp:
var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.
So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository
I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:
"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."
You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:
"git reflog expire --expire=now --all && git gc --prune=now --aggressive"
When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:
"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"
Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".
What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)
I hope this saves someone's time
I was facing the same problem as mentioned in the question. The following steps solved my problem.
I upgraded the nodejs package link with following steps
Clear NPM's cache:
npm cache clean -f
Install a little helper called 'n'
npm install -g n
Then I went to node.js website, downloaded the latest node js package, installed it, and my problem was solved.
According to an article on Medium, this will work:
install --upgrade pandas==1.0.0rc0
First convert the numeric value then add the 'S'
:
select convert(varchar(10),StandardCost) +'S'
from DimProduct where ProductKey = 212
If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):
Set-Location -Path 'E:\FOLDER NAME'
If you are running in a local server, such as wamp or xampp, make sure it's using the php.ini you think it is. These servers usually default to a php.ini that's not in your html docs folder.
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file);
returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
File.expand_path File.dirname(__FILE__)
will return the directory relative to the file this command is called from.
But Dir.pwd
returns the working directory (results identical to executing pwd
in your terminal)
readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:
http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx
taken from Mark's example:
public class Fragrance : IFragrance
{
private readonly string name;
public Fragrance(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Spread()
{
return this.name;
}
}
in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.
I use this:
template <typename T>
bool fromHex(const std::string& hexValue, T& result)
{
std::stringstream ss;
ss << std::hex << hexValue;
ss >> result;
return !ss.fail();
}
According to the official documentation, a click on any link in WebView launches an application that handles URLs, which by default is a browser. You need to override the default behavior like this
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
This answer is based on MadisonTrash's great answer above but updated to use new Vue 3 syntax.
Vue 3 now uses beforeMount
instead of bind
, and unmounted
instead of unbind
(src).
const clickOutside = {
beforeMount: (el, binding) => {
el.clickOutsideEvent = event => {
// here I check that click was outside the el and his children
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
binding.value();
}
};
document.addEventListener("click", el.clickOutsideEvent);
},
unmounted: el => {
document.removeEventListener("click", el.clickOutsideEvent);
},
};
createApp(App)
.directive("click-outside", clickOutside)
.mount("#app");
This seems more straightforward using data.table
as it performs the sort while setting the key.
So, if I were to get the top 3 records in sort (ascending order), then,
require(data.table)
d <- data.table(mtcars, key="cyl")
d[, head(.SD, 3), by=cyl]
does it.
And if you want the descending order
d[, tail(.SD, 3), by=cyl] # Thanks @MatthewDowle
Edit: To sort out ties using mpg
column:
d <- data.table(mtcars, key="cyl")
d.out <- d[, .SD[mpg %in% head(sort(unique(mpg)), 3)], by=cyl]
# cyl mpg disp hp drat wt qsec vs am gear carb rank
# 1: 4 22.8 108.0 93 3.85 2.320 18.61 1 1 4 1 11
# 2: 4 22.8 140.8 95 3.92 3.150 22.90 1 0 4 2 1
# 3: 4 21.5 120.1 97 3.70 2.465 20.01 1 0 3 1 8
# 4: 4 21.4 121.0 109 4.11 2.780 18.60 1 1 4 2 6
# 5: 6 18.1 225.0 105 2.76 3.460 20.22 1 0 3 1 7
# 6: 6 19.2 167.6 123 3.92 3.440 18.30 1 0 4 4 1
# 7: 6 17.8 167.6 123 3.92 3.440 18.90 1 0 4 4 2
# 8: 8 14.3 360.0 245 3.21 3.570 15.84 0 0 3 4 7
# 9: 8 10.4 472.0 205 2.93 5.250 17.98 0 0 3 4 14
# 10: 8 10.4 460.0 215 3.00 5.424 17.82 0 0 3 4 5
# 11: 8 13.3 350.0 245 3.73 3.840 15.41 0 0 3 4 3
# and for last N elements, of course it is straightforward
d.out <- d[, .SD[mpg %in% tail(sort(unique(mpg)), 3)], by=cyl]
Its happened with me. I deletes some css files by mistake and then copied back. This error appeared at that time. So i restart all my dockers and other servers and then it went away, Perhaps this help some one :)
HTML5 and the VLC web plugin were a no go for me but I was able to get this work using the following setup:
DivX Web Player (NPAPI browsers only)
And here is the HTML:
<embed id="divxplayer" type="video/divx" width="1024" height="768"
src ="path_to_file" autoPlay=\"true\"
pluginspage=\"http://go.divx.com/plugin/download/\"></embed>
The DivX player seems to allow for a much wider array of video and audio options than the native HTML5, so far I am very impressed by it.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
You may approach this differently; omit the use of the :empty
pseudo-class and utilize input
events to detect a significant value in the <input>
field and style it accordingly:
var inputs = document.getElementsByTagName('input');_x000D_
_x000D_
for (var i = 0; i < inputs.length; i++) {_x000D_
var input = inputs[i];_x000D_
input.addEventListener('input', function() {_x000D_
var bg = this.value ? 'green' : 'red';_x000D_
this.style.backgroundColor = bg;_x000D_
});_x000D_
}
_x000D_
body {_x000D_
padding: 40px;_x000D_
}_x000D_
#inputList li {_x000D_
list-style-type: none;_x000D_
padding-bottom: 1.5em;_x000D_
}_x000D_
#inputList li input,_x000D_
#inputList li label {_x000D_
float: left;_x000D_
width: 10em;_x000D_
}_x000D_
#inputList li input {_x000D_
color: white;_x000D_
background-color: red;_x000D_
}_x000D_
#inputList li label {_x000D_
text-align: right;_x000D_
padding-right: 1em;_x000D_
}
_x000D_
<ul id="inputList">_x000D_
<li>_x000D_
<label for="username">Enter User Name:</label>_x000D_
<input type="text" id="username" />_x000D_
</li>_x000D_
<li>_x000D_
<label for="password">Enter Password:</label>_x000D_
<input type="password" id="password" />_x000D_
</li>_x000D_
</ul>
_x000D_
input
Events (DOM Mutation Events are now deprecated in DOM level 4, and have been replaced by DOM Mutation Observers).Disclaimer: note that input
events are currently experimental, and probably not widely supported.
Use :
<select onchange="myFunction()">
function myFunction() {
document.querySelectorAll("input[type=submit]")[0].click();
}
Sets
Sets can be combined using mathematical operations.
|
combines two sets to form a new one containing items in either. &
gets items only in both. -
gets items in the first set but not in the second. ^
gets items in either set, but not both.Try It Yourself:
first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}
print(first | second)
print(first & second)
print(first - second)
print(second - first)
print(first ^ second)
Result:
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{4, 5, 6}
{1, 2, 3}
{8, 9, 7}
{1, 2, 3, 7, 8, 9}
I’ve made a small gem that can alleviate the need to manually delete associated records in some circumstances.
This gem adds a new option for ActiveRecord associations:
dependent: :delete_recursively
When you destroy a record, all records that are associated using this option will be deleted recursively (i.e. across models), without instantiating any of them.
Note that, just like dependent: :delete or dependent: :delete_all, this new option does not trigger the around/before/after_destroy callbacks of the dependent records.
However, it is possible to have dependent: :destroy associations anywhere within a chain of models that are otherwise associated with dependent: :delete_recursively. The :destroy option will work normally anywhere up or down the line, instantiating and destroying all relevant records and thus also triggering their callbacks.
Just add 20 minutes in milliseconds to your date:
var currentDate = new Date();
currentDate.setTime(currentDate.getTime() + 20*60*1000);
Installed Maven in Juno IDE for Java EE (eclipse-jee-juno-SR2-linux-gtk-x86_64)
Eclipse -> Available Software Sites -> Maven URL -> http://download.eclipse.org/technology/m2e/releases
Following Maven URL did not work and was giving "No software found" error: http://eclipse.org/m2e/download/
Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems
Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:
For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:
<html> <head> <title>Test Page</title> </head> <body> <h2>Data Collection</h2><p> <form action="process.php" method="post"> <table> <tr> <td>Name:</td> <td><input type="text" name="Name"/></td> </tr> <tr> <td>Age:</td> <td><input type="text" name="Age"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit"/> </td> </tr> </table> </form> </body> </html>
This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:
<?php
print "Your name is ". $Name;
print "<br />";
print "You are ". $Age . " years old";
print "<br />"; $old = 25 + $Age;
print "In 25 years you will be " . $old . " years old";
?>
As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.
Additional JavaScript Example
This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.
Note: document.getElementById("fname").value
gets the object with the ID
tag that equals fname
and then pulls it's value
- which in this case is the text in the First Name textbox.
<html>
<head>
<script type="text/javascript">
function ExampleJS(){
var jFirst = document.getElementById("fname").value;
var jLast = document.getElementById("lname").value;
alert("Your name is: " + jFirst + " " + jLast);
}
</script>
</head>
<body>
<FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">
First name: <input type="text" id="fname" name="firstname" /><br />
Last name: <input type="text" id="lname" name="lastname" /><br />
<input name="Submit" type="submit" value="Update" />
</FORM>
</body>
</html>
A new answer to reflect the most current practices: as of version 1.0.1, neither astype('str')
nor astype(str)
work.
As per the documentation, a Series can be converted to the string datatype in the following ways:
df['id'] = df['id'].astype("string")
df['id'] = pandas.Series(df['id'], dtype="string")
df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)
The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid
and I didn't..
The .before
argument in dplyr::add_row
can be used to specify the row.
dplyr::add_row(
cars,
speed = 0,
dist = 0,
.before = 3
)
#> speed dist
#> 1 4 2
#> 2 4 10
#> 3 0 0
#> 4 7 4
#> 5 7 22
#> 6 8 16
#> ...
There's also the undocumented value of "none" to disable it entirely.
By default, a comma is used as a delimiter in a CSV file. However, some CSV files can use delimiters other than a comma. Few popular ones are |
and \t
.
import csv
data_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|')
writer.writerows(data_list)
output:
SN|Name|Contribution
1|Linus Torvalds|Linux Kernel
2|Tim Berners-Lee|World Wide Web
3|Guido van Rossum|Python Programming
import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=';')
writer.writerows(row_list)
output:
"SN";"Name";"Contribution"
1;"Linus Torvalds";"Linux Kernel"
2;"Tim Berners-Lee";"World Wide Web"
3;"Guido van Rossum";"Python Programming"
As you can see, we have passed csv.QUOTE_NONNUMERIC
to the quoting
parameter. It is a constant defined by the csv
module.
csv.QUOTE_NONNUMERIC
specifies the writer
object that quotes should be added around the non-numeric entries.
There are 3 other predefined constants you can pass to the quoting
parameter:
csv.QUOTE_ALL
- Specifies the writer
object to write CSV file with quotes around all the entries.csv.QUOTE_MINIMAL
- Specifies the writer
object to only quote those fields which contain special characters (delimiter, quotechar or any characters in lineterminator)csv.QUOTE_NONE
- Specifies the writer
object that none of the entries should be quoted. It is the default value.import csv
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
with open('innovators.csv', 'w', newline='') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC,
delimiter=';', quotechar='*')
writer.writerows(row_list)
output:
*SN*;*Name*;*Contribution*
1;*Linus Torvalds*;*Linux Kernel*
2;*Tim Berners-Lee*;*World Wide Web*
3;*Guido van Rossum*;*Python Programming*
Here, we can see that quotechar='*'
parameter instructs the writer
object to use *
as quote for all non-numeric values.
You should try
$ sudo gem install json -v '1.8.2'
in my case (Ubuntu 14.04) that didn't work directly and I had to do this:
$ sudo apt-get install ruby-dev
and then I could install the gem and continue. Had one more problem that was fixed by:
$ sudo apt-get install libsqlite3-dev
Hoping helps.
you just add this style in your style.xml
file which is in your values folder
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
After that set this style to your activity class in your AndroidManifest.xml file
android:theme="@style/AppTheme.NoActionBar"
Edit:- If you are going with programmatic way to hide ActionBar then use below code in your activity onCreate()
method.
if(getSupportedActionbar()!=null)
this.getSupportedActionBar().hide();
and if you want to hide ActionBar from Fragment then
getActivity().getSupportedActionBar().hide();
AppCompat v7:-
Use following theme in your Activities where you don't want actiobBar Theme.AppComat.NoActionBar
or Theme.AppCompat.Light.NoActionBar
or if you want to hide in whole app then set this theme in your <application... />
in your AndroidManifest
.
In Kotlin:
add this line of code in your onCreate()
method or you can use above theme.
if (supportActionBar != null)
supportActionBar?.hide()
i hope this will help you more.
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
The blaze project has come a long way over the last 6 years. It has a simple API covering a useful subset of pandas features.
dask.dataframe takes care of chunking internally, supports many parallelisable operations and allows you to export slices back to pandas easily for in-memory operations.
import dask.dataframe as dd
df = dd.read_csv('filename.csv')
df.head(10) # return first 10 rows
df.tail(10) # return last 10 rows
# iterate rows
for idx, row in df.iterrows():
...
# group by my_field and return mean
df.groupby(df.my_field).value.mean().compute()
# slice by column
df[df.my_field=='XYZ'].compute()
UPDATE for v1.1:
Rather than giving q="search_string"
give it q="hashtag"
in URL encoded form to return results with HASHTAG ONLY. So your query would become:
GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames
%23
is URL encoded form of #
. Try the link out in your browser and it should work.
You can optimize the query by adding since_id
and max_id
parameters detailed here. Hope this helps !
Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call
Updated
Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
.pyc
contain the compiled bytecode of Python source files. The Python interpreter loads .pyc
files before .py
files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.
If you are looking for the executable that npm installed, maybe because you would like to put it in your PATH, you can simply do
npm bin
or
npm bin -g
maybe this is what u want?
<a href="#" id="bottle" onclick="document.location=this.id+'.html';return false;" >
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" />
</a>
edit: keep in mind that anyone who does not have javascript enabled will not be able to navaigate to the image page....
This is easy, use this query to find select data from date range between two dates
select * from tabblename WHERE (datecolumn BETWEEN '2018-04-01' AND '2018-04-5')
Use combination of isNaN
and parseInt
functions:
var character = ... ; // your character
var isDigit = ! isNaN( parseInt(character) );
Another notable way - multiplication by one (like character * 1
instead of parseInt(character)
) - makes a number not only from any numeric string, but also a 0
from empty string and a string containing only spaces so it is not suitable here.
<Program files>\Android\Android-sdk\platforms\<platform SDK's>
On a 32bit machine:
"<Program files>
" will be \Program Files\
On a 64bit machine:
If you installed the 32bit ADT, "<Program files>
" will be \Program Files (x86)\
If you installed the 64bit ADT, "<Program files>
" will be \Program Files\
$ mvn --version
and look for Maven home: in the output
, mine is: Maven home: /usr/share/maven
CREATE VIEW MyView AS
SELECT Column, Value FROM Table;
SELECT Column FROM MyView WHERE Value = 1;
Is the proper solution in MySQL, some other SQLs let you define Views more exactly.
Note: Unless the View is very complicated, MySQL will optimize this just fine.
@[User::path] ="MDS/Material/"+(DT_STR, 4, 1252) DATEPART("yy" , GETDATE())+ "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "/" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
An alternative solution:
div[class|='tocolor']
will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.
Beware that this won't match
<div class="foo tocolor-">
Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)
myString.replace(/<br ?\/?>/g, "\n")
This takes care of nulls
var body = JObject.Parse("anyjsonString");
body?.SelectToken("path-string-prop")?.ToString();
body?.SelectToken("path-double-prop")?.ToObject<double>();
The style
property lets you specify values for CSS properties.
The CSS width
property takes a length as its value.
Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.
e1.style.width = "400px";
You are using MVC with OOPS Concept. So there are some certain rules.
1) Your class name (ie: controller name) should be start with capital Letter.
e.g.: your controller name is 'icecream'. that should be 'Icecream'
In localhost it might not be compulsory, but in server it will check all these rules, else it can't detect the right class name.
For using dictionary object in typescript you can use interface as below:
interface Dictionary<T> {
[Key: string]: T;
}
and, use this for your class property type.
export class SearchParameters {
SearchFor: Dictionary<string> = {};
}
to use and initialize this class,
getUsers(): Observable<any> {
var searchParams = new SearchParameters();
searchParams.SearchFor['userId'] = '1';
searchParams.SearchFor['userName'] = 'xyz';
return this.http.post(searchParams, 'users/search')
.map(res => {
return res;
})
.catch(this.handleError.bind(this));
}
If I understand your question right:
To add a .net 2.0 Web Service Reference instead of a WCF Service Reference, right-click on your project and click 'Add Service Reference.'
Then click "Advanced.." at the bottom left of the dialog.
Then click "Add Web Reference.." on the bottom left of the next dialog.
Now you can add a regular SOAP web reference like you are looking for.
you could get a htmldocument by:
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.Stream stream = wc.OpenRead(url);
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string s = reader.ReadToEnd();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(s);
so you have getbiyid and getbyname ... but any further you'd better of with
HTML Agility Pack as suggested . f.e
you can do: doc.DocumentNode.SelectNodes(xpathselector)
or regex to parse the doc ..
btw: why not regex ? . its soo cool if you can use it right... but xpath is also very mighty ... so "choose your poison"
cu
I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.
And what happen if the user catch de JSON and change the bool to True?
I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.
According to composer's manual:
require-dev (root-only)
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both
install
orupdate
support the--no-dev
option that prevents dev dependencies from being installed.
So running composer install
will also download the development dependencies.
The reason is actually quite simple. When contributing to a specific library you may want to run test suites or other develop tools (e.g. symfony). But if you install this library to a project, those development dependencies may not be required: not every project requires a test runner.
DOMSubtreeModified is not a good solution. It's can cause infinite loops if you decide to change the DOM inside the event handler, hence it has been disabled in a number of browsers. MutationObserver will be the answer.
const onChangeElement = (qSelector, cb)=>{
const targetNode = document.querySelector(qSelector);
if(targetNode){
const config = { attributes: true, childList: false, subtree: false };
const callback = function(mutationsList, observer) {
cb($(qSelector))
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}else {
console.error("onChangeElement: Invalid Selector")
}
}
And you can use it,
onChangeElement('mydiv', function(jqueryElement){
alert('changed')
})
As mentioned in some of the answers/comments already, Python objects already store a dictionary of their attributes (methods aren't included). This can be accessed as __dict__
, but the better way is to use vars
(the output is the same, though). Note that modifying this dictionary will modify the attributes on the instance! This can be useful, but also means you should be careful with how you use this dictionary. Here's a quick example:
class A():
def __init__(self, x=3, y=2, z=5):
self.x = x
self._y = y
self.__z__ = z
def f(self):
pass
a = A()
print(vars(a))
# {'x': 3, '_y': 2, '__z__': 5}
# all of the attributes of `a` but no methods!
# note how the dictionary is always up-to-date
a.x = 10
print(vars(a))
# {'x': 10, '_y': 2, '__z__': 5}
# modifying the dictionary modifies the instance attribute
vars(a)["_y"] = 20
print(vars(a))
# {'x': 10, '_y': 20, '__z__': 5}
Using dir(a)
is an odd, if not outright bad, approach to this problem. It's good if you really needed to iterate over all attributes and methods of the class (including the special methods like __init__
). However, this doesn't seem to be what you want, and even the accepted answer goes about this poorly by applying some brittle filtering to try to remove methods and leave just the attributes; you can see how this would fail for the class A
defined above.
(using __dict__
has been done in a couple of answers, but they all define unnecessary methods instead of using it directly. Only a comment suggests to use vars
).
In Python 3 the following will work. I am using the lower level http.client from the standard library. Also check out section 2 of rfc2617 for details of basic authorization. This code won't check the certificate is valid, but will set up a https connection. See the http.client docs on how to do that.
from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' % userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()
var str = "";
for(var k in obj)
if (obj.hasOwnProperty(k)) //omit this test if you want to see built-in properties
str += k + " = " + obj[k] + "\n";
alert(str);
You can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.
import numpy as np
import vg
x = np.array([1, 2, 3, 4, 5])
mag1 = np.linalg.norm(x)
mag2 = vg.magnitude(x)
print mag1 == mag2
# True
I created the library at my last startup, where it was motivated by uses like this: simple ideas which are far too verbose in NumPy.
Alter table table_name modify table_name.column_name data_type AUTO_INCREMENT;
eg:
Alter table avion modify avion.av int AUTO_INCREMENT;
If you want to have back button with back arrow you can use an image and code below
backArrow.png [email protected] [email protected]
override func viewDidLoad() {
super.viewDidLoad()
let customBackButton = UIBarButtonItem(image: UIImage(named: "backArrow") , style: .plain, target: self, action: #selector(backAction(sender:)))
customBackButton.imageInsets = UIEdgeInsets(top: 2, left: -8, bottom: 0, right: 0)
navigationItem.leftBarButtonItem = customBackButton
}
func backAction(sender: UIBarButtonItem) {
// custom actions here
navigationController?.popViewController(animated: true)
}