As Selman22 said, you are overriding the default object.Equals
method, which accepts an object obj
and not a safe compile time type.
In order for that to happen, make your type implement IEquatable<Box>
:
public class Box : IEquatable<Box>
{
double height, length, breadth;
public static bool operator ==(Box obj1, Box obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(Box obj1, Box obj2)
{
return !(obj1 == obj2);
}
public bool Equals(Box other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return height.Equals(other.height)
&& length.Equals(other.length)
&& breadth.Equals(other.breadth);
}
public override bool Equals(object obj)
{
return Equals(obj as Box);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = height.GetHashCode();
hashCode = (hashCode * 397) ^ length.GetHashCode();
hashCode = (hashCode * 397) ^ breadth.GetHashCode();
return hashCode;
}
}
}
Another thing to note is that you are making a floating point comparison using the equality operator and you might experience a loss of precision.
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
You should use isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
Sometimes it would be nice to have operator overloading, friend classes and multiple inheritance.
However I still think it was a good decision. If Java would have had operator overloading then we could never be sure of operator meanings without looking through source code. At present that's not necessary. And I think your example of using methods instead of operator overloading is also quite readable. If you want to make things more clear you could always add a comment above hairy statements.
// a = b + c
Complex a, b, c; a = b.add(c);
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
&&, || They can't be overloaded
() (Conversion operator) They can't be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
[ ] Can be overloaded but not always!
For bracket:
public Object this[int index]
{
}
The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
From MSDN
public int this[int index]
{
get => values[index];
}
This way works:
class A
{
struct Wrap
{
A& a;
Wrap(A& aa) aa(a) {}
operator int() { return a.value; }
operator std::string() { stringstream ss; ss << a.value; return ss.str(); }
}
Wrap operator*() { return Wrap(*this); }
};
You can't do this yourself since Java doesn't permit operator overloading.
With one exception, however. + and += are overloaded for String objects.
When it comes to operator overloading in C++, there are three basic rules you should follow. As with all such rules, there are indeed exceptions. Sometimes people have deviated from them and the outcome was not bad code, but such positive deviations are few and far between. At the very least, 99 out of 100 such deviations I have seen were unjustified. However, it might just as well have been 999 out of 1000. So you’d better stick to the following rules.
Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded. Instead, provide a function with a well-chosen name.
Basically, the first and foremost rule for overloading operators, at its very heart, says: Don’t do it. That might seem strange, because there is a lot to be known about operator overloading and so a lot of articles, book chapters, and other texts deal with all this. But despite this seemingly obvious evidence, there are only a surprisingly few cases where operator overloading is appropriate. The reason is that actually it is hard to understand the semantics behind the application of an operator unless the use of the operator in the application domain is well known and undisputed. Contrary to popular belief, this is hardly ever the case.
Always stick to the operator’s well-known semantics.
C++ poses no limitations on the semantics of overloaded operators. Your compiler will happily accept code that implements the binary +
operator to subtract from its right operand. However, the users of such an operator would never suspect the expression a + b
to subtract a
from b
. Of course, this supposes that the semantics of the operator in the application domain is undisputed.
Always provide all out of a set of related operations.
Operators are related to each other and to other operations. If your type supports a + b
, users will expect to be able to call a += b
, too. If it supports prefix increment ++a
, they will expect a++
to work as well. If they can check whether a < b
, they will most certainly expect to also to be able to check whether a > b
. If they can copy-construct your type, they expect assignment to work as well.
Continue to The Decision between Member and Non-member.
To add to Mehrdad answer ,
namespace Math
{
class Matrix
{
public:
[...]
}
std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix);
}
In your implementation
std::ostream& operator<<(std::ostream& stream,
const Math::Matrix& matrix) {
matrix.print(stream); //assuming you define print for matrix
return stream;
}
I ran into this problem with templated classes. Here's a more general solution I had to use:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// Friend means operator<< can use private variables
// It needs to be declared as a template, but T is taken
template <class U>
friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}
// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
obj.toString(os);
return os;
}
Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.
The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(
Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.
This works too:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// For some reason this requires using T, and not U as above
friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
{
obj.toString(os);
return os;
}
}
I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.
this might be helpful:
// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;
class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
idNum = 0, salary = 0.0;
}
void setValues (int a, int b);
void operator= (Employee &emp );
};
void Employee::setValues ( int idN , int sal )
{
salary = sal; idNum = idN;
}
void Employee::operator = (Employee &emp) // Assignment operator overloading function
{
salary = emp.salary;
}
int main ( )
{
Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator
}
I believe another solution to this problem would be use to variables of type long instead of int.
I was just working on some code where the % operator was returning a negative value which caused some issues (for generating uniform random variables on [0,1] you don't really want negative numbers :) ), but after switching the variables to type long, everything was running smoothly and the results matched the ones I was getting when running the same code in python (important for me as I wanted to be able to generate the same "random" numbers across several platforms.
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
var val = (string === "true");
Another useful difference in Chrome exists when sending DOM elements to the console.
Notice:
console.log
prints the element in an HTML-like treeconsole.dir
prints the element in a JSON-like treeSpecifically, console.log
gives special treatment to DOM elements, whereas console.dir
does not. This is often useful when trying to see the full representation of the DOM JS object.
There's more information in the Chrome Console API reference about this and other functions.
I was able to workaround/hack this problem by moving in to "Classic" mode from "integrated" mode.
You could try some sort of COALESCE trick, eg:
SELECT COALESCE( CASE WHEN condition1 THEN calculation1 ELSE NULL END, CASE WHEN condition2 THEN calculation2 ELSE NULL END, etc... )
I use this: https://github.com/Homebrew/homebrew-php
The command is:
$ xcode-select --install
$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/homebrew-php
$ brew options php56
$ brew install php56
Then config in your .bash_profile
or .bashrc
# Homebrew PHP CLI
export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"
You may not place the deprecated non-block-scoped stage
(as in the original question) inside parallel
.
As of JENKINS-26107, stage
takes a block argument. You may put parallel
inside stage
or stage
inside parallel
or stage
inside stage
etc. However visualizations of the build are not guaranteed to support all nestings; in particular
stage
nesting.parallel
branches inside a top-level stage, but currently no more.JENKINS-27394, if implemented, would display arbitrarily nested stage
s.
Ignore the chrome warning. There is no standard MIME type for OTF fonts.
font/opentype may silence the warning, but that doesn't make it the "right" thing to do.
Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.
Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.
Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf
I removed my .classpath
file in my project directory to correct this issue. No need to remove the Maven Nature from the project in Eclipse.
The specific error I was getting was: Project 'my-project-name' is missing required Java project: 'org.some.package-9.3.0 But my project wasn't dependent on org.some.package
in any way.
Perhaps an old version of the project relied on it and Maven wasn't properly updating the .classpath
file.
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {_x000D_
return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
var minutes = Math.floor(secs / 60);_x000D_
secs = secs%60;_x000D_
var hours = Math.floor(minutes/60)_x000D_
minutes = minutes%60;_x000D_
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
var d = new Date();_x000D_
var d1 = new Date(d.getTime()+s*1000);_x000D_
var hms = hhmmss(s);_x000D_
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
} _x000D_
*/
_x000D_
If you are redirecting with PHP, then you would simply use the sleep() command to sleep for however many seconds before redirecting.
But, I think what you are referring to is the meta refresh tag:
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
A note on relative paths to complement the other answers.
When doing infrastructure as code I'm usually using roles and tasks that accept relative paths, specially for files defined in those roles.
Special variables like playbook_dir and role_path are very useful to create the absolute paths needed to test for existence.
Be aware that the third parameter (value) in the examples given above: the value is a constant (e.g. 'Z' or c(20,30)).
Defining the third parameter using values from the data frame itself can lead to confusion.
E.g. with a simple data frame such as this (using dplyr::data_frame):
tmp <- data_frame(a=1:10, b=sample(LETTERS[24:26], 10, replace=T))
This will create somthing like this:
a b
(int) (chr)
1 1 X
2 2 Y
3 3 Y
4 4 X
5 5 Z
..etc
Now suppose you want wanted to do, was to multiply the values in column 'a' by 2, but only where column 'b' is "X". My immediate thought would be something like this:
with(tmp, replace(a, b=="X", a*2))
That will not provide the desired outcome, however. The a*2 will defined as a fixed vector rather than a reference to the 'a' column. The vector 'a*2' will thus be
[1] 2 4 6 8 10 12 14 16 18 20
at the start of the 'replace' operation. Thus, the first row where 'b' equals "X", the value in 'a' will be placed by 2. The second time, it will be replaced by 4, etc ... it will not be replaced by two-times-the-value-of-a in that particular row.
Try width:inherit
to make the image take the width of it's container <div>
. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>
, it will size to fit the image height.
img {
width:inherit;
}
.item {
border:1px solid pink;
width: 120px;
float: left;
margin: 3px;
padding: 3px;
}
UPDATE: In Oracle 12c onward we have an option to create auto increment field, its better than trigger and sequence.
See the below image
From SQL Statement
IDENTITY column is now available on Oracle 12c:
create table t1 (
c1 NUMBER GENERATED by default on null as IDENTITY,
c2 VARCHAR2(10)
);
or specify starting and increment values, also preventing any insert into the identity column (GENERATED ALWAYS) (again, Oracle 12c+ only)
create table t1 (
c1 NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1),
c2 VARCHAR2(10)
);
EDIT : if you face any error like "ORA-30673: column to be modified is not an identity column", then you need to create new column and delete the old one.
Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.
To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050
After that open the .npmrc files to see which file get updated.
Because thats coding convention. See here for more.
You could attach to the KeyDown event and then query the database for that portion of the text that the user has already entered. For example, if the user enters "T", search for things that start with "T". Then, when they enter the next letter, for example "e", search for things in the table that start with "Te".
The available items could be displayed in a "floating" ListBox, for example. You would need to place the ListBox just beneath the TextBox so that they can see the entries available, then remove the ListBox when they're done typing.
The shortest way:
python3 -m pip install package
python -m pip install package
First, create a quick function that will split a delimited list of values into a table, like this:
CREATE FUNCTION dbo.udf_SplitVariable
(
@List varchar(8000),
@SplitOn varchar(5) = ','
)
RETURNS @RtnValue TABLE
(
Id INT IDENTITY(1,1),
Value VARCHAR(8000)
)
AS
BEGIN
--Account for ticks
SET @List = (REPLACE(@List, '''', ''))
--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
SET @List = ''
END
--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN
INSERT INTO @RtnValue (value)
SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))
SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))
END
INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))
RETURN
END
Then call the function like this...
SELECT *
FROM A
LEFT OUTER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
WHERE f.Id IS NULL
This has worked really well on our project...
Of course, the opposite could also be done, if that was the case (though not your question).
SELECT *
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
And this really comes in handy when dealing with reports that have an optional multi-select parameter list. If the parameter is NULL you want all values selected, but if it has one or more values you want the report data filtered on those values. Then use SQL like this:
SELECT *
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value OR @ExcludeList IS NULL
This way, if @ExcludeList is a NULL value, the OR clause in the join becomes a switch that turns off filtering on this value. Very handy...
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")
The data.table
package also has unique
and duplicated
methods of it's own with some additional features.
Both the unique.data.table
and the duplicated.data.table
methods have an additional by
argument which allows you to pass a character
or integer
vector of column names or their locations respectively
library(data.table)
DT <- data.table(id = c(1,1,1,2,2,2),
val = c(10,20,30,10,20,30))
unique(DT, by = "id")
# id val
# 1: 1 10
# 2: 2 10
duplicated(DT, by = "id")
# [1] FALSE TRUE TRUE FALSE TRUE TRUE
Another important feature of these methods is a huge performance gain for larger data sets
library(microbenchmark)
library(data.table)
set.seed(123)
DF <- as.data.frame(matrix(sample(1e8, 1e5, replace = TRUE), ncol = 10))
DT <- copy(DF)
setDT(DT)
microbenchmark(unique(DF), unique(DT))
# Unit: microseconds
# expr min lq mean median uq max neval cld
# unique(DF) 44708.230 48981.8445 53062.536 51573.276 52844.591 107032.18 100 b
# unique(DT) 746.855 776.6145 2201.657 864.932 919.489 55986.88 100 a
microbenchmark(duplicated(DF), duplicated(DT))
# Unit: microseconds
# expr min lq mean median uq max neval cld
# duplicated(DF) 43786.662 44418.8005 46684.0602 44925.0230 46802.398 109550.170 100 b
# duplicated(DT) 551.982 558.2215 851.0246 639.9795 663.658 5805.243 100 a
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
if you write while(true). its means that loop will not stop in any situation for stop this loop you have to use break statement between while block.
package com.java.demo;
/**
* @author Ankit Sood Apr 20, 2017
*/
public class Demo {
/**
* The main method.
*
* @param args
* the arguments
*/
public static void main(String[] args) {
/* Initialize while loop */
while (true) {
/*
* You have to declare some condition to stop while loop
* In which situation or condition you want to terminate while loop.
* conditions like: if(condition){break}, if(var==10){break} etc...
*/
/* break keyword is for stop while loop */
break;
}
}
}
You need to set the g flag to replace globally:
date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')
Otherwise only the first occurrence will be replaced.
Here is the code I've been using for programatically importing .cer files into a new KeyStore.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
//VERY IMPORTANT. SOME OF THESE EXIST IN MORE THAN ONE PACKAGE!
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
//Put everything after here in your function.
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);//Make an empty store
InputStream fis = /* insert your file path here */;
BufferedInputStream bis = new BufferedInputStream(fis);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while (bis.available() > 0) {
Certificate cert = cf.generateCertificate(bis);
trustStore.setCertificateEntry("fiddler"+bis.available(), cert);
}
echo $'Create the snapshots\nSnapshot created\n'
I found a simpler solution with a dummy index file.
Create a Servlet (or use the one you wanted to respond to "/") which maps to "/index.html" (Solutions mentioned here use the mapping via XML, I used the 3.0 version with annotation @WebServlet) Then create a static (empty) file at the root of the static content named "index.html"
I was using Jetty, and what happened was that the server recognized the file instead of listing the directory but when asked for the resource, my Servlet took control instead. All other static content remained unaffected.
This happens from time to time in Eclipse. In the "Project" menu there's a "Clean" option, that usually takes care of the problem.
You can access JSON data by using fetch() in JavaScript
Update url parameter of fetch() with your url.
fetch(url)
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data);
})
Hope It helps, it worked perfectly for me.
I had this problem and I just realized that if in the server you see the user in the menu SERVER -> USERS AND PRIVILEGES and find the user who has % as HOSTNAME, you can use it instead the root user.
That's all
It should be (new minus old)/mod avg of old and new With a special case when both val are zeros
Information provided by @Gord
As of September 2019 pywin32
is now available from PyPI and installs the latest version (currently version 224). This is done via the pip
command
pip install pywin32
If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx
is the version you require, e.g. 224
pip install pywin32==xxx
This differs to the pip
command below as that one uses pypiwin32
which currently installs an older (namely 223)
Browsing the docs I see no reason for these commands to work for all python3.x
versions, I am unsure on python2.7
and below so you would have to try them and if they do not work then the solutions below will work.
Probably now undesirable solutions but certainly still valid as of September 2019
There is no version of specific version ofwin32api
. You have to get the pywin32
module which currently cannot be installed via pip
. It is only available from this link at the moment.
https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/
The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python
version :)
EDIT
Since I posted my answer there are other alternatives to downloading the win32api
module.
It is now available to download through pip
using this command;
pip install pypiwin32
Also it can be installed from this GitHub repository as provided in comments by @Heath
If you have Windows 10 and VS2019, and the .NET Framework 4.8, below you can see the Location of WSDL.exe
Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools
An unsigned application cannot be installed. When we run directly from eclipse, that apk is signed with debugger key and can be found in bin\ folder of the project. You can use that for test purpose distribution also.
If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.
class CallbackTest {
myCallback: Function;
}
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
comdlg32.dll is not really a COM dll (you can't register it).
What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx
.
You can't do that: you must specify fully resolved type, like Data<MyType>
. T
is just a variable, and as is meaningless.
But if you mean that T
will be known, just not statically, you need to create equivalent of TypeReference
dynamically. Other questions referenced may already mention this, but it should look something like:
public Data<T> read(InputStream json, Class<T> contentClass) {
JavaType type = mapper.getTypeFactory().constructParametricType(Data.class, contentClass);
return mapper.readValue(json, type);
}
I also had a similar problem and discovered that the BOOST_INCLUDE_DIR, BOOST_LIBRARYDIR and BOOST_ROOT env variables must hold absolute paths. HTH!
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\Roslyn
this is where you can find the c# compiler that supports c#7 otherwise it will use the .net 4 compilers which supports only c# 5
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
In insert()
public void insert(String tableImg, Object object,
ContentValues dataToInsert) {
db.insert(tablename, null, dataToInsert);
}
Hope it helps you.
-m1 is the last parent of the current branch that is being fixed, -m 2 is the original parent of the branch that got merged into this.
Tortoise Git can also help here if command line is confusing.
You can use this to get a name of any provided member:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
}
To get name of a variable:
string testVariable = "value";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => testVariable);
To get name of a parameter:
public class TestClass
{
public void TestMethod(string param1, string param2)
{
string nameOfParam1 = MemberInfoGetting.GetMemberName(() => param1);
}
}
You can use the nameof operator for parameters, variables and properties alike:
string testVariable = "value";
string nameOfTestVariable = nameof(testVariable);
My unorthodox but simple solution from scratch:
git clone
your repository into a fresh new directory.git remote add upstream <your github rep here>
git pull upstream master
git add .
git commit -m "your commit text here"
git push origin master
voila! worked like a charm in my case.
They are extension methods. Welcome to a whole new fluent world. :)
A slightly cleaner version of DTB's solution.
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var list = Enumerable.Repeat(0, 8).Select(x=>chars[random.Next(chars.Length)]);
return string.Join("", list);
Your style preferences may vary.
I used this:
def reverse(text):
s=""
l=len(text)
for i in range(l):
s+=text[l-1-i]
return s
There is one link where it elaborated very well & solution is also given. Try it if you got proper solution please post here so other can understand. Given solution is ok then like the post so other can try these solution.
for you reference original link :- https://bensonxion.wordpress.com/2012/05/07/serializing-an-ienumerable-produces-collection-was-modified-enumeration-operation-may-not-execute/
When we use .Net Serialization classes to serialize an object where its definition contains an Enumerable type, i.e. collection, you will be easily getting InvalidOperationException saying "Collection was modified; enumeration operation may not execute" where your coding is under multi-thread scenarios. The bottom cause is that serialization classes will iterate through collection via enumerator, as such, problem goes to trying to iterate through a collection while modifying it.
First solution, we can simply use lock as a synchronization solution to ensure that the operation to the List object can only be executed from one thread at a time. Obviously, you will get performance penalty that if you want to serialize a collection of that object, then for each of them, the lock will be applied.
Well, .Net 4.0 which makes dealing with multi-threading scenarios handy. for this serializing Collection field problem, I found we can just take benefit from ConcurrentQueue(Check MSDN)class, which is a thread-safe and FIFO collection and makes code lock-free.
Using this class, in its simplicity, the stuff you need to modify for your code are replacing Collection type with it, use Enqueue to add an element to the end of ConcurrentQueue, remove those lock code. Or, if the scenario you are working on do require collection stuff like List, you will need a few more code to adapt ConcurrentQueue into your fields.
BTW, ConcurrentQueue doesnât have a Clear method due to underlying algorithm which doesnât permit atomically clearing of the collection. so you have to do it yourself, the fastest way is to re-create a new empty ConcurrentQueue for a replacement.
Another solution is by using .animate() and appropriate CSS.
e.g.
$('#mydiv').animate({ marginLeft: "100%"} , 4000);
I think we better adopt a new file inclusion syntax (so won't mess up with
code blocks, I think the C style inclusion is totally wrong), and I wrote a small tool in Perl, naming cat.pl
,
because it works like cat
(cat a.txt b.txt c.txt
will merge three
files), but it merges files in depth, not in width. How to use?
$ perl cat.pl <your file>
The syntax in detail is:
@include <-=path=
%include <-=path=
It can properly handle file inclusion loops (if a.txt <- b.txt, b.txt <- a.txt, then what you expect?).
Example:
a.txt:
a.txt
a <- b
@include <-=b.txt=
a.end
b.txt:
b.txt
b <- a
@include <-=a.txt=
b.end
perl cat.pl a.txt > c.txt
, c.txt:
a.txt
a <- b
b.txt
b <- a
a.txt
a <- b
@include <-=b.txt= (note:won't include, because it will lead to infinite loop.)
a.end
b.end
a.end
More examples at https://github.com/district10/cat/blob/master/tutorial_cat.pl_.md.
I also wrote a Java version having an identical effect (not the same, but close).
Seems your initial data contains strings and not numbers. It would probably be best to ensure that the data is already of the required type up front.
However, you can convert strings to numbers like this:
pd.Series(['123', '42']).astype(float)
instead of float(series)
If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?
It might not be the best way but you may type the following
=IF(sheet1!A1<>"",sheet1!A1,"")
and drag it down to the maximum number of rows you expect.
Dictionary<string, int> dictionary = new Dictionary<string, int>();
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
reader.IsDbNull(ColumnIndex)
works as many answers says.
And I want to mention if you working with column names, just comparing types may be more comfortable.
if(reader["TeacherImage"].GetType() == typeof(DBNull)) { //logic }
As of Python 3.2, released Nov 2011, the smtplib has a new function send_message
instead of just sendmail
, which makes dealing with To/CC/BCC easier. Pulling from the Python official email examples, with some slight modifications, we get:
# Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.message import EmailMessage
# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
# Create a text/plain message
msg = EmailMessage()
msg.set_content(fp.read())
# me == the sender's email address
# you == the recipient's email address
# them == the cc's email address
# they == the bcc's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you
msg['Cc'] = them
msg['Bcc'] = they
# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
Using the headers work fine, because send_message respects BCC as outlined in the documentation:
send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg
With sendmail
it was common to add the CC headers to the message, doing something such as:
msg['Bcc'] = [email protected]
Or
msg = "From: [email protected]" +
"To: [email protected]" +
"BCC: [email protected]" +
"Subject: You've got mail!" +
"This is the message body"
The problem is, the sendmail function treats all those headers the same, meaning they'll get sent (visibly) to all To: and BCC: users, defeating the purposes of BCC. The solution, as shown in many of the other answers here, was to not include BCC in the headers, and instead only in the list of emails passed to sendmail
.
The caveat is that send_message
requires a Message object, meaning you'll need to import a class from email.message
instead of merely passing strings into sendmail
.
int num1, num2, num3;
num1 = num2 = num3 = 5;
Console.WriteLine(num1 + "=" + num2 + "=" + num3); // 5=5=5
I believe that multiple returns are usually good (in the code that I write in C#). The single-return style is a holdover from C. But you probably aren't coding in C.
There is no law requiring only one exit point for a method in all programming languages. Some people insist on the superiority of this style, and sometimes they elevate it to a "rule" or "law" but this belief is not backed up by any evidence or research.
More than one return style may be a bad habit in C code, where resources have to be explicitly de-allocated, but languages such as Java, C#, Python or JavaScript that have constructs such as automatic garbage collection and try..finally
blocks (and using
blocks in C#), and this argument does not apply - in these languages, it is very uncommon to need centralised manual resource deallocation.
There are cases where a single return is more readable, and cases where it isn't. See if it reduces the number of lines of code, makes the logic clearer or reduces the number of braces and indents or temporary variables.
Therefore, use as many returns as suits your artistic sensibilities, because it is a layout and readability issue, not a technical one.
I have talked about this at greater length on my blog.
Here it is some code:
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();
See more examples in this article, you may need to take a look to impersonation.
file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))
This is solve your encode error
also.
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
You must use a Module (rather than a Class) if you're creating Extension methods. In VB.NET I'm not aware of another option.
Being resistant to Modules myself, I just spent a worthless couple of hours trying to work out how to add some boilerplate code to resolve embedded assemblies in one, only to find out that Sub New()
(Module) and Shared Sub New()
(Class) are equivalent. (I didn't even know there was a callable Sub New()
in a Module!)
So I just threw the EmbeddedAssembly.Load
and AddHandler AppDomain.CurrentDomain.AssemblyResolve
lines in there and Bob became my uncle.
Addendum: I haven't checked it out 100% yet, but I have an inkling that Sub New()
runs in a different order in a Module than a Class, just going by the fact that I had to move some declarations to inside methods from outside to avoid errors.
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
You should set the android:exported attribute of the service to "true", in order to allow other components to invoke it. In the AndroidManifest.xml file, add the following attribute:
<service android:exported="true" ></service>
Then, you should be able to start the service via adb:
adb shell am startservice com.package.name/.YourServiceName
For more info about the android:exported attribute see this page.
People have mentioned a couple of the building blocks toward doing this efficiently, but nobody's really put the pieces together. The sieve of Eratosthenes is a good start, but with it you'll run out of memory long before you reach the limit you've set. That doesn't mean it's useless though -- when you're doing your loop, what you really care about are prime divisors. As such, you can start by using the sieve to create a base of prime divisors, then use those in the loop to test numbers for primacy.
When you write the loop, however, you really do NOT want to us sqrt(i) in the loop condition as a couple of answers have suggested. You and I know that the sqrt is a "pure" function that always gives the same answer if given the same input parameter. Unfortunately, the compiler does NOT know that, so if use something like '<=Math.sqrt(x)' in the loop condition, it'll re-compute the sqrt of the number every iteration of the loop.
You can avoid that a couple of different ways. You can either pre-compute the sqrt before the loop, and use the pre-computed value in the loop condition, or you can work in the other direction, and change i<Math.sqrt(x)
to i*i<x
. Personally, I'd pre-compute the square root though -- I think it's clearer and probably a bit faster--but that depends on the number of iterations of the loop (the i*i
means it's still doing a multiplication in the loop). With only a few iterations, i*i
will typically be faster. With enough iterations, the loss from i*i
every iteration outweighs the time for executing sqrt
once outside the loop.
That's probably adequate for the size of numbers you're dealing with -- a 15 digit limit means the square root is 7 or 8 digits, which fits in a pretty reasonable amount of memory. On the other hand, if you want to deal with numbers in this range a lot, you might want to look at some of the more sophisticated prime-checking algorithms, such as Pollard's or Brent's algorithms. These are more complex (to put it mildly) but a lot faster for large numbers.
There are other algorithms for even bigger numbers (quadratic sieve, general number field sieve) but we won't get into them for the moment -- they're a lot more complex, and really only useful for dealing with really big numbers (the GNFS starts to be useful in the 100+ digit range).
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
Option Explicit
Public myarray (1 To 10)
Public Count As Integer
myarray(1) = "A"
myarray(2) = "B"
myarray(3) = "C"
myarray(4) = "D"
myarray(5) = "E"
myarray(6) = "F"
myarray(7) = "G"
myarray(8) = "H"
myarray(9) = "I"
myarray(10) = "J"
Private Function unwrapArray()
For Count = 1 to UBound(myarray)
MsgBox "Letters of the Alphabet : " & myarray(Count)
Next
End Function
In plain English:
This fixed my issue:
Go to terminal shell and type mongo
.
Then type use db_name
.
Then type:
db.createUser(
{
user: "mongodb",
pwd: "dogmeatsubparflavour1337",
roles: [ { role: "dbOwner", db: "db_name" } ]
}
)
Also try: db.getUsers()
Quick sample:
const MongoClient = require('mongodb').MongoClient;
// MongoDB Connection Info
const url = 'mongodb://mongodb:[email protected]:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options
// Use Connect Method to connect to the Server
MongoClient.connect(url)
.then((db) => {
console.log(db);
console.log('Casually connected correctly to server.');
// Be careful with db.close() when working asynchronously
db.close();
})
.catch((error) => {
console.log(error);
});
I did quite a bit of investigation on that topic recently since I was not satisfied with the many libraries I found out there.
I ended up developing a library to address this, it is named valid8. As explained in the documentation, it is for value validation mostly (although it comes bundled with simple type validation functions too), and you might wish to associate it with a PEP484-based type checker such as enforce or pytypes.
This is how you would perform validation with valid8
alone (and mini_lambda
actually, to define the validation logic - but it is not mandatory) in your case:
# for type validation
from numbers import Integral
from valid8 import instance_of
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@validate_arg('a', instance_of(Integral))
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', instance_of(str), Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # InputValidationError for 'a' HasWrongType: Value should be an instance of <class 'numbers.Integral'>. Wrong value: [0.2].
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # InputValidationError for 'c' Successes: [] / Failures: {"instance_of_<class 'str'>": "HasWrongType: Value should be an instance of <class 'str'>. Wrong value: [0]", 'len(s) > 0': "TypeError: object of type 'int' has no len()"}.
my_function(0, 1, '') # InputValidationError for 'c' Successes: ["instance_of_<class 'str'>"] / Failures: {'len(s) > 0': 'False'}
And this is the same example leveraging PEP484 type hints and delegating type checking to enforce
:
# for type validation
from numbers import Integral
from enforce import runtime_validation, config
config(dict(mode='covariant')) # type validation will accept subclasses too
# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len
@runtime_validation
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', Len(s) > 0)
def my_function(a: Integral, b, c: str):
"""an example function I'd like to check the arguments of."""
# check that a is an int
# check that 0 < b < 10
# check that c is not an empty string
# check that it works
my_function(0.2, 1, 'r') # RuntimeTypeError 'a' was not of type <class 'numbers.Integral'>
my_function(0, 0, 'r') # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0) # RuntimeTypeError 'c' was not of type <class 'str'>
my_function(0, 1, '') # InputValidationError for 'c' [len(s) > 0] returned [False].
In the newer versions of GWT (starting either 2.3 or 2.4, i believe), you can also add
<collapse-all-properties />
to your gwt.xml for development purposes. That will tell the GWT compiler to create a single permutation which covers all locales and browsers. Therefore, you can still test in all browsers and languages, but are still only compiling a single permutation
I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain
taken from NSURLError.h
/*!
@enum NSURL-related Error Codes
@abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};
See the Parameter Expansion section in the Bash man
page. A[@]
returns the contents of the array, :1:2
takes a slice of length 2, starting at index 1.
A=( foo bar "a b c" 42 )
B=("${A[@]:1:2}")
C=("${A[@]:1}") # slice to the end of the array
echo "${B[@]}" # bar a b c
echo "${B[1]}" # a b c
echo "${C[@]}" # bar a b c 42
echo "${C[@]: -2:2}" # a b c 42 # The space before the - is necesssary
Note that the fact that "a b c" is one array element (and that it contains an extra space) is preserved.
You could add google()
to repositories block
allprojects {
repositories {
jcenter()
maven {
url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
}
maven {
url "https://jitpack.io"
}
google()
}
}
Adding to Andy's answer, there is additional utility to git rm
:
Safety: When doing git rm
instead of rm
, Git will block the removal if there is a discrepancy between the HEAD
version of a file and the staging index or working tree version. This block is a safety mechanism to prevent removal of in-progress changes.
Safeguarding: git rm --dry-run
. This option is a safeguard that will execute the git rm
command but not actually delete the files. Instead it will output which files it would have removed.
The dataframe.sort() method is - so my understanding - deprecated in pandas > 0.18. In order to solve your problem you should use dataframe.sort_values() instead:
f.sort_values(by=["c1","c2"], ascending=[False, True])
The output looks like this:
c1 c2
3 10
2 15
2 30
2 100
1 20
The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.
Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.
for ST3
$language = "language u wish"
if exists,
go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings
else
create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings
and set
{ "extensions": [ "yourextension" ] }
This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )
Easy.
var scrollIt = function(time) {
// time = scroll time in ms
var start = new Date().getTime(),
scroll = document.documentElement.scrollTop + document.body.scrollTop,
timer = setInterval(function() {
var now = Math.min(time,(new Date().getTime())-start)/time;
document.documentElement.scrollTop
= document.body.scrollTop = (1-time)/start*scroll;
if( now == 1) clearTimeout(timer);
},25);
}
One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.
<span class="error text-danger">Some Errors related to something</span>
Output looks like something below:
this way we can iterate into table data.
DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE TABLE #Temp (JobID INT)
INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID) FROM #Temp
WHILE @_MinJID <= @_MaxJID
BEGIN
INSERT INTO Mytable
(
JobID,
)
VALUES
(
@_MinJobID,
)
SET @_MinJID = @_MinJID + 1;
END
DROP TABLE #Temp
STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks
If you don't want to show warnings as well as errors use
// Turn off all error reporting
error_reporting(0);
I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.
In that example, e
is just a parameter for that function, but it's the event
object that gets passed in through it.
In iTerm -> Preferences -> Profiles Tab -> General section set Command to: /bin/zsh --login
Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = @"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen
Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.
In short it works ok for a small data set or just key points from a data set.
No, it's not possible, browsers have their own ways to implement tooltip. All you can do is to create some div that behaves like an HTML tooltip (mostly it's just 'show on hover') with Javascript, and then style it the way you want.
With this, you wouldn't have to worry about browser's zooming in or out, since the text inside the tooltip div is an actual HTML, it would scale accordingly.
See Jonathan's post for some good resource.
SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table
I have some general thoughts about the implementation of Task
:
using
.ConfigureAwait
was introduced in 4.5. Task
was introduced in 4.0. Task.ContinueWith
they do not b/c it was realised context switch is expensive and it is turned off by default.I have got a few posts on the subject but my take - in addition to Tugberk's nice answer - is that you should turn all APIs asynchronous and ideally flow the context . Since you are doing async, you can simply use continuations instead of waiting so no deadlock will be cause since no wait is done in the library and you keep the flowing so the context is preserved (such as HttpContext).
Problem is when a library exposes a synchronous API but uses another asynchronous API - hence you need to use Wait()
/Result
in your code.
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id);
in this case. But if you use find()
then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
An easier alternative for those who would prefer not to write all that configuration boilerplate manually...
1) Install Nerdle.AutoConfig from NuGet
2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)
public interface IServiceConfiguration
{
int Port { get; }
ReportType ReportType { get; }
}
3) You'll need a type to hold the collection, e.g.
public interface IServiceCollectionConfiguration
{
IEnumerable<IServiceConfiguration> Services { get; }
}
4) Add the config section like so (note camelCase naming)
<configSections>
<section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>
<serviceCollection>
<services>
<service port="6996" reportType="File" />
<service port="7001" reportType="Other" />
</services>
</serviceCollection>
5) Map with AutoConfig
var services = AutoConfig.Map<IServiceCollectionConfiguration>();
As the documentation states (link), you can use the channel resource type and operation List to get all the videos in an channel. This operation must be performed using argument 'channel id'.
Here is your answer. We can use both simultaniously. As i used both and they are working fine. The code is as follows:
<EditText
android:id="@+id/edittext_password_la"
android:layout_below="@+id/edittext_username_la"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dip"
android:inputType="textPassword"
android:hint="@string/string_password" />
This will help you.
Generally, there is a practice in machine learning community not to learn something that you don’t want to. For example, consider a classification problem where one's goal is to assign y labels to a given x input. If we use generative model
p(x,y)=p(y|x).p(x)
we have to model p(x) which is irrelevant for the task in hand. Practical limitations like data sparseness will force us to model p(x)
with some weak independence assumptions. Therefore, we intuitively use discriminative models for classification.
dpkg-query --showformat='${db:Status-Status}'
This produces a small output string which is unlikely to change and is easy to compare deterministically without grep
:
pkg=hello
status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
sudo apt install $pkg
fi
The $? = 0
check is needed because if you've never installed a package before, and after you remove certain packages such as hello
, dpkg-query
exits with status 1 and outputs to stderr:
dpkg-query: no packages found matching hello
instead of outputting not-installed
. The 2>&1
captures that error message too when it comes preventing it from going to the terminal.
For multiple packages:
pkgs='hello certbot'
install=false
for pkg in $pkgs; do
status="$(dpkg-query -W --showformat='${db:Status-Status}' "$pkg" 2>&1)"
if [ ! $? = 0 ] || [ ! "$status" = installed ]; then
install=true
break
fi
done
if "$install"; then
sudo apt install $pkgs
fi
The possible statuses are documented in man dpkg-query
as:
n = Not-installed
c = Config-files
H = Half-installed
U = Unpacked
F = Half-configured
W = Triggers-awaiting
t = Triggers-pending
i = Installed
The single letter versions are obtainable with db:Status-Abbrev
, but they come together with the action and error status, so you get 3 characters and would need to cut it.
So I think it is reliable enough to rely on the uncapitalized statuses (Config-files
vs config-files
) not changing instead.
dpkg -s
exit status
This unfortunately doesn't do what most users want:
pkgs='qemu-user pandoc'
if ! dpkg -s $pkgs >/dev/null 2>&1; then
sudo apt-get install $pkgs
fi
because for some packages, e.g. certbot
, doing:
sudo apt install certbot
sudo apt remove certbot
leaves certbot
in state config-files
, which means that config files were left in the machine. And in that state, dpkg -s
still returns 0
, because the package metadata is still kept around so that those config files can be handled more nicely.
To actually make dpkg -s
return 1 as desired, --purge
would be needed:
sudo apt remove --purge certbot
which actually moves it into not-installed
/dpkg-query: no packages found matching
.
Note that only certain packages leave config files behind. A simpler package like hello
goes directly from installed
to not-installed
without --purge
.
Tested on Ubuntu 20.10.
Python apt
package
There is a pre-installed Python 3 package called apt
in Ubuntu 18.04 which exposes an Python apt interface!
A script that checks if a package is installed and installs it if not can be seen at: How to install a package using the python-apt API
Here is a copy for reference:
#!/usr/bin/env python
# aptinstall.py
import apt
import sys
pkg_name = "libjs-yui-doc"
cache = apt.cache.Cache()
cache.update()
cache.open()
pkg = cache[pkg_name]
if pkg.is_installed:
print "{pkg_name} already installed".format(pkg_name=pkg_name)
else:
pkg.mark_install()
try:
cache.commit()
except Exception, arg:
print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))
Check if an executable is in PATH
instead
See: How can I check if a program exists from a Bash script?
See also
THIS DOESN'T USE PIPEs, but requires a single tempfile
I used this to put simplified timestamps into a lowtech daily maintenance batfile
We have already Short-formatted our System-Time to HHmm, (which is 2245 for 10:45PM)
I direct output of Maint-Routines to logfiles with a $DATE%@%TIME% timestamp;
. . . but %TIME% is a long ugly string (ex. 224513.56, for down to the hundredths of a sec)
SOLUTION OVERVIEW:
1. Use redirection (">") to send the command "TIME /T" everytime to OVERWRITE a temp-file in the %TEMP% DIRECTORY
2. Then use that tempfile as the input to set a new variable (I called it NOW)
3. Replace
echo $DATE%@%TIME% blah-blah-blah >> %logfile%with
echo $DATE%@%NOW% blah-blah-blah >> %logfile%
SUCCESSFUL TIMESYNCH [email protected]AFTER:
SUCCESSFUL TIMESYNCH 29Dec14@2252
ACTUAL CODE:
TIME /T > %TEMP%\DailyTemp.txt SET /p NOW=<%TEMP%\DailyTemp.txt echo $DATE%@%NOW% blah-blah-blah >> %logfile%
AFTERMATH:
All that remains afterwards is the appended logfile, and constantly overwritten tempfile. And if the Tempfile is ever deleted, it will be re-created as necessary.
Your helpful comments led me to the following solution:
class Word_Parser:
"""docstring for Word_Parser"""
def __init__(self, sentences):
self.sentences = sentences
def parser(self):
self.word_list = self.sentences.split()
word_list = []
word_list = self.word_list
return word_list
def sort_word_list(self):
self.sorted_word_list = sorted(self.sentences.split())
sorted_word_list = self.sorted_word_list
return sorted_word_list
def get_num_words(self):
self.num_words = len(self.word_list)
num_words = self.num_words
return num_words
test = Word_Parser("mary had a little lamb")
test.parser()
test.sort_word_list()
test.get_num_words()
print test.word_list
print test.sorted_word_list
print test.num_words
and returns: ['mary', 'had', 'a', 'little', 'lamb'] ['a', 'had', 'lamb', 'little', 'mary'] 5
Thank you all.
Git doesn't prompt for password and fails with similar cryptic message "fatal: protocol error: bad line length character: user" if you don't have your private key authentication setup as well.
https://www.digitalocean.com/community/tutorials/how-to-configure-ssh-key-based-authentication-on-a-linux-server tells how to specify public key on the server. Basically add the public key to ~/.ssh/authorized_keys or ~/.ssh/authorized_keys2
I had to struggle a bit on how to provide private key to the Git Bash on the windows machine. Dan McClain's answer in https://serverfault.com/questions/194567/how-do-i-tell-git-for-windows-where-to-find-my-private-rsa-key/382801#382801 describes that. One addition to his answer, in my case the private key file was expected to be named id_rsa.pub
I was also having the trouble to route to a different view using navlink.
My implementation was as follows and works perfectly;
<NavLink tag='li'>
<div
onClick={() =>
this.props.history.push('/admin/my- settings')
}
>
<DropdownItem className='nav-item'>
Settings
</DropdownItem>
</div>
</NavLink>
Wrap it with a div, assign the onClick handler to the div. Use the history object to push a new view.
try this:
@media (hover:<s>on-demand</s>) {
button:hover {
background-color: #color-when-NOT-touch-device;
}
}
UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).
Latest published version of the Support Library is 24.1.1, So you can use it like this,
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
Same as for other support components.
You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html
function getRangeDateString($timestamp) {
if ($timestamp) {
$currentTime=strtotime('today');
// Reset time to 00:00:00
$timestamp=strtotime(date('Y-m-d 00:00:00',$timestamp));
$days=round(($timestamp-$currentTime)/86400);
switch($days) {
case '0';
return 'Today';
break;
case '-1';
return 'Yesterday';
break;
case '-2';
return 'Day before yesterday';
break;
case '1';
return 'Tomorrow';
break;
case '2';
return 'Day after tomorrow';
break;
default:
if ($days > 0) {
return 'In '.$days.' days';
} else {
return ($days*-1).' days ago';
}
break;
}
}
}
I don't know how to break it to you, but I have a PhD from Cambridge, and I'm using 2.8 just fine.
More seriously, I hardly spent any time with 2.7 (it won't inter-op with a Java library I am using) and started using Scala just over a month ago. I have some experience with Haskell (not much), but just ignored the stuff you're worried about and looked for methods that matched my experience with Java (which I use for a living).
So: I am a "new user" and I wasn't put off - the fact that it works like Java gave me enough confidence to ignore the bits I didn't understand.
(However, the reason I was looking at Scala was partly to see whether to push it at work, and I am not going to do so yet. Making the documentation less intimidating would certainly help, but what surprised me is how much it is still changing and being developed (to be fair what surprised me most was how awesome it is, but the changes came a close second). So I guess what I am saying is that I'd rather prefer the limited resources were put into getting it into a final state - I don't think they were expecting to be this popular this soon.)
DateTime
is a non-nullable value type
DateTime? newdate = null;
You can use a Nullable<DateTime>
I prefer to use a looping variable, as it tends to read a bit nicer than just "while 1:", and no ugly-looking break
statement:
finished = False
while not finished:
... do something...
finished = evaluate_end_condition()
I believe the official way is still to go thorugh codecvt
facets (you need some sort of locale-aware translation), as in
resultCode = use_facet<codecvt<char, wchar_t, ConversionState> >(locale).
in(stateVar, scratchbuffer, scratchbufferEnd, from, to, toLimit, curPtr);
or something like that, I don't have working code lying around. But I'm not sure how many people these days use that machinery and how many simply ask for pointers to memory and let ICU or some other library handle the gory details.
The tibble
package now has a dedicated function that converts row names to an explicit variable.
library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head
Gives:
das_Auto mpg cyl disp hp drat wt qsec vs am gear carb
1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.
You should \usepackage{longtable}
.
We can parse csv files with quoted strings and delimited by say | with following code
while read -r line
do
field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')
echo "$field1 $field2"
done < "$csvFile"
awk
parses the string fields to variables and tr
removes the quote.
Slightly slower as awk
is executed for each field.
You Could always use and leave out the "when not matched section"
merge into table1 FromTable
using table2 ToTable
on ( FromTable.field1 = ToTable.field1
and FromTable.field2 =ToTable.field2)
when Matched then
update set
ToTable.fieldr = FromTable.fieldx,
ToTable.fields = FromTable.fieldy,
ToTable.fieldt = FromTable.fieldz)
when not matched then
insert (ToTable.field1,
ToTable.field2,
ToTable.fieldr,
ToTable.fields,
ToTable.fieldt)
values (FromTable.field1,
FromTable.field2,
FromTable.fieldx,
FromTable.fieldy,
FromTable.fieldz);
A random seed specifies the start point when a computer generates a random number sequence.
For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.
For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:
Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:
900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated
I had the same error, none of above tips didn't help.
In my case, it was caused by WebStorm, combined two imports into one.
import { ComponentOne, ComponentTwo } from '../component-dir';
I extracted this into two separate imports
import { ComponentOne } from '../component-dir/component-one.service';
import { ComponentTwo } from '../component-dir/component-two.model';
After this it works without error.
Actually, the solution provided before is not working. It doesn't work if you want to enter 100.00.
Replace:
double parsed = Double.parseDouble(cleanString);
String formato = NumberFormat.getCurrencyInstance().format((parsed/100));
With:
BigDecimal parsed = new BigDecimal(cleanString).setScale(2,BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR);
String formato = NumberFormat.getCurrencyInstance().format(parsed);
I must say that I made some modifications for my code. The thing is that you should be using BigDecimal's
From HandlerIntercepter
's javadoc:
HandlerInterceptor
is basically similar to a ServletFilter
, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured inweb.xml
, aHandlerInterceptor
in the application context.As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for
HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, aFilter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
With that being said:
So where is the difference between
Interceptor#postHandle()
andFilter#doFilter()
?
postHandle
will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse
since it's already committed.
doFilter
is much more versatile than the postHandle
. You can change the request or response and pass it to the chain or even block the request processing.
Also, in preHandle
and postHandle
methods, you have access to the HandlerMethod
that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.
What is the best practise in which use cases it should be used?
As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
I came up with the following solution based on some answers found here.
CODE:
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* @return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* @return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* @return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
}
USAGE:
Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);
This was bugging me too, since this was a standard feature in Sublime Text 2, but somehow automatic indentation no longer worked in Sublime Text 3 for HTML files.
My solution was to find the Miscellaneous.tmPreferences file from Sublime Text 2 (found under %AppData%/Roaming/Sublime Text 2/Packages/HTML) and copy those settings to the same file for ST3.
Now package handling has been made more difficult for ST3, but luckily you can just add the files to your %AppData%/Roaming/Sublime Text 3/Packages folder and they overwrite default settings in the install directory. Just save this file as "%AppData%/Roaming/Sublime Text 3/Packages/HTML/Miscellaneous.tmPreferences" and auto indent works again like it did in ST2.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Regarding elegance, the closest thing to the mathematical notation (a <= x <= b) slightly improves readability:
public static bool IsBetween(this int value, int min, int max)
{
return min <= value && value <= max;
}
For further illustration:
public static bool IsOutside(this int value, int min, int max)
{
return value < min || max < value;
}
A pointer to void
is a "generic" pointer type. A void *
can be converted to any other pointer type without an explicit cast. You cannot dereference a void *
or do pointer arithmetic with it; you must convert it to a pointer to a complete data type first.
void *
is often used in places where you need to be able to work with different pointer types in the same code. One commonly cited example is the library function qsort
:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
base
is the address of an array, nmemb
is the number of elements in the array, size
is the size of each element, and compar
is a pointer to a function that compares two elements of the array. It gets called like so:
int iArr[10];
double dArr[30];
long lArr[50];
...
qsort(iArr, sizeof iArr/sizeof iArr[0], sizeof iArr[0], compareInt);
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareDouble);
qsort(lArr, sizeof lArr/sizeof lArr[0], sizeof lArr[0], compareLong);
The array expressions iArr
, dArr
, and lArr
are implicitly converted from array types to pointer types in the function call, and each is implicitly converted from "pointer to int
/double
/long
" to "pointer to void
".
The comparison functions would look something like:
int compareInt(const void *lhs, const void *rhs)
{
const int *x = lhs; // convert void * to int * by assignment
const int *y = rhs;
if (*x > *y) return 1;
if (*x == *y) return 0;
return -1;
}
By accepting void *
, qsort
can work with arrays of any type.
The disadvantage of using void *
is that you throw type safety out the window and into oncoming traffic. There's nothing to protect you from using the wrong comparison routine:
qsort(dArr, sizeof dArr/sizeof dArr[0], sizeof dArr[0], compareInt);
compareInt
is expecting its arguments to be pointing to int
s, but is actually working with double
s. There's no way to catch this problem at compile time; you'll just wind up with a missorted array.
Use the following:
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'
Just for reference I have a 2 million record table, I ran a similar query. Salils answer took 4.48 seconds, the above took 2.25 seconds.
So if the table is BIG I would suggest this rather.
If this were a perfect world, 100% of code would be covered by unit tests. However, since this is NOT a perfect world, it's a matter of what you have time for. As a result, I recommend focusing less on a specific percentage, and focusing more on the critical areas. If your code is well-written (or at least a reasonable facsimile thereof) there should be several key points where APIs are exposed to other code.
Focus your testing efforts on these APIs. Make sure that the APIs are 1) well documented and 2) have test cases written that match the documentation. If the expected results don't match up with the docs, then you have a bug in either your code, documentation, or test cases. All of which are good to vet out.
Good luck!
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
This method works for me, it's not dynamic but straight to the point:
const fs = require('fs');
const express = require('express');
const app = express();
app.get( '/logo.gif', function( req, res ) {
fs.readFile( 'logo.gif', function( err, data ) {
if ( err ) {
console.log( err );
return;
}
res.write( data );
return res.end();
});
});
app.listen( 80 );
Please see http://visualgdb.com/KB/usbdebug-manual/ as this worked well for me. Had to download and install the USB drivers inside Android studio then actually install the drivers via device manager in windows 8.1
In the particular case you've provided, it's a conditional assignment. The part before the question mark (?) is a boolean condition, and the parts either side of the colon (:) are the values to assign based on the result of the condition (left side of the colon is the value for true, right side is the value for false).
If you've got git-bash
installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen
.
https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/
In PHP5, you should use the Document Object Model class instead. Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
If you like to remove last 5 characters, you can use:
path.substring(0,path.length() - 5)
( could contain off by one error ;) )
If you like to remove some variable string:
path.substring(0,path.lastIndexOf('yoursubstringtoremove));
(could also contain off by one error ;) )
Lexeme - A lexeme is a sequence of characters in the source program that matches the pattern for a token and is identified by the lexical analyzer as an instance of that token.
Token - Token is a pair consisting of a token name and an optional token value. The token name is a category of a lexical unit.Common token names are
Consider this expression in the programming language C:
sum = 3 + 2;
Tokenized and represented by the following table:
Lexeme Token category
------------------------------
sum | Identifier
= | Assignment operator
3 | Integer literal
+ | Addition operator
2 | Integer literal
; | End of statement
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
This is the solution I came up with for a class project:
public static String theMonth(int month){
String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
return monthNames[month];
}
The number you pass in comes from a Calendar.MONTH
call.
Use <packages xmlns="urn:packages">
in the place of <packages>
One more way for square matrix. No numpy, nor itertools, use (effective) in-place elements exchange.
def transpose(m):
for i in range(1, len(m)):
for j in range(i):
m[i][j], m[j][i] = m[j][i], m[i][j]
For jquery users, how about $.trim(s)
Another way is to select a column with the columns
array:
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
Use Numpy direct array indexing, as in MATLAB, Julia, ...
a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;
import numpy as np
list(np.array(a)[s])
# [11, 12, 15]
Better yet, just stay with Numpy arrays
a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])
Here is a decent solution for this problem, and it does not require application restart.
https://github.com/cmaftuleac/BundleLocalization
This implementation works by tweaking inside NSBundle. The idea is that you override the method localizedStringForKey on the instance of NSBundle object, and then call this method on a different bundle with a different language. Simple and elegant fully compatible with all types of resources.
You override __hash__
if you want special hash-semantics, and __cmp__
or __eq__
in order to make your class usable as a key. Objects who compare equal need to have the same hash value.
Python expects __hash__
to return an integer, returning Banana()
is not recommended :)
User defined classes have __hash__
by default that calls id(self)
, as you noted.
There is some extra tips from the documentation.:
Classes which inherit a
__hash__()
method from a parent class but change the meaning of__cmp__()
or__eq__()
such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting__hash__ = None
in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raise TypeError).
You can get an input value without adding 'onChange' function.
Just add to the input element a 'ref attr:
And then use this.refs to get the input value when you need it.
Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args]
.
Of course this assumes that .NET is installed on the target machine.
Here's the code. Feel free to copy!
using System;
using System.Diagnostics;
using System.Text;
namespace dotNetLauncher
{
class Program
{
/*
If you make .NET Core applications, they have to be launched like .NET blah.dll args here
This is a convenience EXE file that launches .NET Core applications via name.exe
Just rename the output exe to the name of the .NET Core DLL file you wish to launch
*/
static void Main(string[] args)
{
var exePath = AppDomain.CurrentDomain.BaseDirectory;
var exeName = AppDomain.CurrentDomain.FriendlyName;
var assemblyName = exeName.Substring(0, exeName.Length - 4);
StringBuilder passInArgs = new StringBuilder();
foreach(var arg in args)
{
bool needsSurroundingQuotes = false;
if (arg.Contains(" ") || arg.Contains("\""))
{
passInArgs.Append("\"");
needsSurroundingQuotes = true;
}
passInArgs.Append(arg.Replace("\"","\"\""));
if (needsSurroundingQuotes)
{
passInArgs.Append("\"");
}
passInArgs.Append(" ");
}
string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";
var p = new Process
{
StartInfo = new ProcessStartInfo("dotnet", callingArgs)
{
UseShellExecute = false
}
};
p.Start();
p.WaitForExit();
}
}
}
In Martin Fowler's UML Distilled, he states (no pun intended) in Chapter 10 State Machine Diagrams (emphasis mine):
A state diagram can be implemented in three main ways: nested switch, the State pattern, and state tables.
Let's use a simplified example of the states of a mobile phone's display:
Fowler gave an example of C# code, but I've adapted it to my example.
public void HandleEvent(PhoneEvent anEvent) {
switch (CurrentState) {
case PhoneState.ScreenOff:
switch (anEvent) {
case PhoneEvent.PressButton:
if (powerLow) { // guard condition
DisplayLowPowerMessage(); // action
// CurrentState = PhoneState.ScreenOff;
} else {
CurrentState = PhoneState.ScreenOn;
}
break;
case PhoneEvent.PlugPower:
CurrentState = PhoneState.ScreenCharging;
break;
}
break;
case PhoneState.ScreenOn:
switch (anEvent) {
case PhoneEvent.PressButton:
CurrentState = PhoneState.ScreenOff;
break;
case PhoneEvent.PlugPower:
CurrentState = PhoneState.ScreenCharging;
break;
}
break;
case PhoneState.ScreenCharging:
switch (anEvent) {
case PhoneEvent.UnplugPower:
CurrentState = PhoneState.ScreenOff;
break;
}
break;
}
}
Here's an implementation of my example with the GoF State pattern:
Taking inspiration from Fowler, here's a table for my example:
Source State Target State Event Guard Action -------------------------------------------------------------------------------------- ScreenOff ScreenOff pressButton powerLow displayLowPowerMessage ScreenOff ScreenOn pressButton !powerLow ScreenOn ScreenOff pressButton ScreenOff ScreenCharging plugPower ScreenOn ScreenCharging plugPower ScreenCharging ScreenOff unplugPower
Nested switch keeps all the logic in one spot, but the code can be hard to read when there are a lot of states and transitions. It's possibly more secure and easier to validate than the other approaches (no polymorphism or interpreting).
The State pattern implementation potentially spreads the logic over several separate classes, which may make understanding it as a whole a problem. On the other hand, the small classes are easy to understand separately. The design is particularly fragile if you change the behavior by adding or removing transitions, as they're methods in the hierarchy and there could be lots of changes to the code. If you live by the design principle of small interfaces, you'll see this pattern doesn't really do so well. However, if the state machine is stable, then such changes won't be needed.
The state tables approach requires writing some kind of interpreter for the content (this might be easier if you have reflection in the language you're using), which could be a lot of work to do up front. As Fowler points out, if your table is separate from your code, you could modify the behavior of your software without recompiling. This has some security implications, however; the software is behaving based on the contents of an external file.
There is a fluent interface (aka internal Domain Specific Language) approach, too, which is probably facilitated by languages that have first-class functions. The Stateless library exists and that blog shows a simple example with code. A Java implementation (pre Java8) is discussed. I was shown a Python example on GitHub as well.
I suspect you did not know that there are different &
escapes in HTML. The W3C you can see the codes. ×
means ×
in HTML code. Use &times
instead.
pre-made code attached here. you can use it by just copying and pasting in your code:
https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv
No mention of Merge?
DataSet newdataset = new DataSet();
newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
Instead of using the /regex/g
syntax, you can construct a new RegExp object:
var replace = "regex";
var re = new RegExp(replace,"g");
You can dynamically create regex objects this way. Then you will do:
"mystring".replace(re, "newstring");
As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.
(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)
Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)
This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}
Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)
This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).
The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}
I think it is this one you need:
Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')
And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
Use this code for sending attachment with upload file option using html form in phpmailer
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Your Name *">
<input type="email" name="email" placeholder="Email *">
<textarea name="msg" placeholder="Your Message"></textarea>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="userfile" />
<input name="contact" type="submit" value="Submit Enquiry" />
</form>
<?php
if(isset($_POST["contact"]))
{
/////File Upload
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible invalid file upload !\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
////// Email
require_once("class.phpmailer.php");
require_once("class.smtp.php");
$mail_body = array($_POST['name'], $_POST['email'] , $_POST['msg']);
$new_body = "Name: " . $mail_body[0] . ", Email " . $mail_body[1] . " Description: " . $mail_body[2];
$d=strtotime("today");
$subj = 'New enquiry '. date("Y-m-d h:i:sa", $d);
$mail = new PHPMailer(); // create a new object
//$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only ,false = Disable
$mail->Host = "mail.yourhost.com";
$mail->Port = '465';
$mail->SMTPAuth = true; // enable
$mail->SMTPSecure = true;
$mail->IsHTML(true);
$mail->Username = "[email protected]"; //[email protected]
$mail->Password = "password";
$mail->SetFrom("[email protected]", "Your Website Name");
$mail->Subject = $subj;
$mail->Body = $new_body;
$mail->AddAttachment($uploadfile);
$mail->AltBody = 'Upload';
$mail->AddAddress("[email protected]");
if(!$mail->Send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo '<p> Success </p> ';
}
}
?>
Use this link for reference.
I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.
When you do a "git add" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob.
So it is possible to recover a file even if it was not committed but it has to have been added.
git init
echo hello >> test.txt
git add test.txt
Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset...
git reset --hard
git fsck
you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a
git show ce01362
will give you the file content "hello" back
To find unreferenced commits I found a tip somewhere suggesting this.
gitk --all $(git log -g --pretty=format:%h)
I have it as a tool in git gui and it is very handy.
As Victor pointed out, the problem is with the alias. This can be avoided though, by putting the expression directly into the WHERE x IN y clause:
SELECT `users`.`first_name`,`users`.`last_name`,`users`.`email`,SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE SUBSTRING(`locations`.`raw`,-6,4) NOT IN #this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
However, I guess this is very inefficient, since the subquery has to be executed for every row of the outer query.
looks like outerWidth is broken in the latest version of jquery.
The discrepancy happens when
the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"
var SelecetdSteps = Context.FFTrakingSubCriticalSteps
.Where(x => x.MeetingId == meetid)
.Select(x =>
x.StepID
);
var crtiticalsteps = Context.MT_CriticalSteps.Where(x =>x.cropid==FFT.Cropid).Select(x=>new
{
StepID= x.crsid,
x.Name,
Checked=false
});
var quer = from ax in crtiticalsteps
where (!SelecetdSteps.Contains(ax.StepID))
select ax;
Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification
simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification
will not show without one.
addAction
is only available since 4.1. Prior to that you would use the PendingIntent
to launch an Activity
. You seem to specify a PendingIntent
, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
Example for SignalR 2.2.1 (May 2017)
Server
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
Client
(almost the same as Mehrdad Bahrainy reply)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
Console.WriteLine("Please Enter Message");
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}
It all depends on what you want to do, and what you want the derived classes to be able to see.
class A
{
private:
int _privInt = 0;
int privFunc(){return 0;}
virtual int privVirtFunc(){return 0;}
protected:
int _protInt = 0;
int protFunc(){return 0;}
public:
int _publInt = 0;
int publFunc()
{
return privVirtFunc();
}
};
class B : public A
{
private:
virtual int privVirtFunc(){return 1;}
public:
void func()
{
_privInt = 1; // wont work
_protInt = 1; // will work
_publInt = 1; // will work
privFunc(); // wont work
privVirtFunc(); // wont work
protFunc(); // will work
publFunc(); // will return 1 since it's overridden in this class
}
}
If your bound property is DateTime, then all you need is
Binding={Property, StringFormat=d}
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend
statement is called before the complete
statement i
will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
I had similar problem, got this resolved by the following CSS:
body {
margin: 0 !important;
padding: 0 !important;
}
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
This will work:
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
The ?
character signifies that the preceding group should be matched zero or one times. The group (-|\s)
will match either a -
or a |
character. Adding ?
after the second occurrence of this group in your regex allows you to match a sequence of 10 consecutive digits.
another improved function version. Mix of existing answers with small improvements (port support) and bugfixes (checking keys properly).
/**
* @param string $url original url to modify - can be relative, partial etc
* @param array $paramsOverride associative array, can be empty
* @return string modified url
*/
protected function overrideUrlQueryParams($url, $paramsOverride){
if (!is_array($paramsOverride)){
return $url;
}
$url_parts = parse_url($url);
if (isset($url_parts['query'])) {
parse_str($url_parts['query'], $params);
} else {
$params = [];
}
$params = array_merge($params, $paramsOverride);
$res = '';
if(isset($url_parts['scheme'])) {
$res .= $url_parts['scheme'] . ':';
}
if(isset($url_parts['host'])) {
$res .= '//' . $url_parts['host'];
}
if(isset($url_parts['port'])) {
$res .= ':' . $url_parts['port'];
}
if (isset($url_parts['path'])) {
$res .= $url_parts['path'];
}
if (count($params) > 0) {
$res .= '?' . http_build_query($params);
}
return $res;
}
Use butterknife to bind the drawable resource to a variable by adding this to the top of your class (before any methods).
@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;
then inside one of your methods add
layout.setBackground(background);
That's all you need
As of 2016, you can do this more simply than in any of the answers already given:
$('#myChosenBox').val();
where "myChosenBox" is the id of the original select input. Or, in the change event:
$('#myChosenBox').on('change', function(e, params) {
alert(e.target.value); // OR
alert(this.value); // OR
alert(params.selected); // also in Panagiotis Kousaris' answer
}
In the Chosen doc, in the section near the bottom of the page on triggering events, it says "Chosen triggers a number of standard and custom events on the original select field." One of those standard events is the change event, so you can use it in the same way as you would with a standard select input. You don't have to mess around with using Chosen's applied classes as selectors if you don't want to. (For the change
event, that is. Other events are often a different matter.)
https://stackoverflow.com/a/40919650/4976373
Unfortunately, I believe that your app "contains encryption" in terms of US BIS even if you just use HTTPS (if your app is not an exception included in question 2).
Quote from FAQ on iTunes Connect:
"How do I know if I can follow the Exporter Registration and Reporting (ERN) process?
If your app uses, accesses, implements or incorporates industry standard encryption algorithms for purposes other than those listed as exemptions under question 2, you need to submit for an ERN authorization. Examples of standard encryption are: AES, SSL, https. This authorization requires that you submit an annual report to two U.S. Government agencies with information about your app every January. "
"2nd Question: Does your product qualify for any exemptions provided under category 5 part 2?
There are several exemptions available in US export regulations under Category 5 Part 2 (Information Security & Encryption regulations) for applications and software that use, access, implement or incorporate encryption.
All liabilities associated with misinterpretation of the export regulations or claiming exemption inaccurately are borne by owners and developers of the apps.
You can answer “YES” to the question if you meet any of the following criteria:
(i) if you determine that your app is not classified under Category 5, Part 2 of the EAR based on the guidance provided by BIS at encryption question. The Statement of Understanding for medical equipment in Supplement No. 3 to Part 774 of the EAR can be accessed at Electronic Code of Federal Regulations site. Please visit the Question #15 in the FAQ section of the encryption page for sample items BIS has listed that can claim Note 4 exemptions.
(ii) your app uses, accesses, implements or incorporates encryption for authentication only
(iii) your app uses, accesses, implements or incorporates encryption with key lengths not exceeding 56 bits symmetric, 512 bits asymmetric and/or 112 bit elliptic curve
(iv) your app is a mass market product with key lengths not exceeding 64 bits symmetric, or if no symmetric algorithms, not exceeding 768 bits asymmetric and/or 128 bits elliptic curve.
Please review Note 3 in Category 5 Part 2 to understand the criteria for mass market definition.
(v) your app is specially designed and limited for banking use or ‘money transactions.’ The term ‘money transactions’ includes the collection and settlement of fares or credit functions.
(vi) the source code of your app is “publicly available”, your app distributed at free of cost to general public, and you have met the notification requirements provided under 740.13.(e).
Please visit encryption web page in case you need further help in determining if your app qualifies for any exemptions.
If you believe that your app qualifies for an exemption, please answer “YES” to the question."
The problem is your query returned false
meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.
As replace()
creates/returns a new string rather than modifying the original (tt
), you need to set the variable (tt
) equal to the new string returned from the replace
function.
tt = tt.replace(/,/g, '.')
You can delete the index by Kibana Console:
To get all index:
GET /_cat/indices?v
To delete a specific index:
DELETE /INDEX_NAME_TO_DELETE
Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).
There are many ways to reverse bits depending on what you mean the "simplest way".
Probably the most logical, consists in rotating the byte while applying a mask on the first bit (n & 1)
:
unsigned char reverse_bits(unsigned char b)
{
unsigned char r = 0;
unsigned byte_len = 8;
while (byte_len--) {
r = (r << 1) | (b & 1);
b >>= 1;
}
return r;
}
As the length of an unsigner char is 1 byte, which is equal to 8 bits, it means we will scan each bit while (byte_len--)
We first check if b as a bit on the extreme right with (b & 1)
;
if so we set bit 1 on r with |
and move it just 1 bit to the left by
multiplying r by 2 with (r << 1)
Then we divide our unsigned char b by 2 with b >>=1
to erase
the bit located at the extreme right of variable b.
As a reminder, b >>= 1; is equivalent to b /= 2;
This solution is attributed to Rich Schroeppel in the Programming Hacks section
unsigned char reverse_bits3(unsigned char b)
{
return (b * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff;
}
The multiply operation (b * 0x0202020202ULL) creates five separate copies of the 8-bit byte pattern to fan-out into a 64-bit value.
The AND operation (& 0x010884422010ULL) selects the bits that are in the correct (reversed) positions, relative to each 10-bit groups of bits.
Together the multiply and the AND operations copy the bits from the original byte so they each appear in only one of the 10-bit sets. The reversed positions of the bits from the original byte coincide with their relative positions within any 10-bit set.
The last step (% 0x3ff), which involves modulus division by 2^10 - 1 has the effect of merging together each set of 10 bits (from positions 0-9, 10-19, 20-29, ...) in the 64-bit value. They do not overlap, so the addition steps underlying the modulus division behave like OR operations.
unsigned char reverse(unsigned char b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
This is the most upvoted answer and despite some explanations, I think that for most people it feels difficult to visualize whats 0xF0, 0xCC, 0xAA, 0x0F, 0x33 and 0x55 truly means.
It does not take advantage of '0b' which is a GCC extension and is included since the C++14 standard, release in December 2014, so a while after this answer dating from April 2010
Integer constants can be written as binary constants, consisting of a sequence of ‘0’ and ‘1’ digits, prefixed by ‘0b’ or ‘0B’. This is particularly useful in environments that operate a lot on the bit level (like microcontrollers).
Please check below code snippets to remember and understand even better this solution where we move half by half:
unsigned char reverse(unsigned char b) {
b = (b & 0b11110000) >> 4 | (b & 0b00001111) << 4;
b = (b & 0b11001100) >> 2 | (b & 0b00110011) << 2;
b = (b & 0b10101010) >> 1 | (b & 0b01010101) << 1;
return b;
}
NB: The >> 4
is because there are 8 bits in 1 byte, which is an unsigned char so we want to take the other half, and so on.
We could easily apply this solution to 4 bytes with only two additional lines and following the same logic. Since both mask complement each other we can even use ~ in order to switch bits and saving some ink:
uint32_t reverse_integer_bits(uint32_t b) {
uint32_t mask = 0b11111111111111110000000000000000;
b = (b & mask) >> 16 | (b & ~mask) << 16;
mask = 0b11111111000000001111111100000000;
b = (b & mask) >> 8 | (b & ~mask) << 8;
mask = 0b11110000111100001111000011110000;
b = (b & mask) >> 4 | (b & ~mask) << 4;
mask = 0b11001100110011001100110011001100;
b = (b & mask) >> 2 | (b & ~mask) << 2;
mask = 0b10101010101010101010101010101010;
b = (b & mask) >> 1 | (b & ~mask) << 1;
return b;
}
The above logic can be summarized with a loop that would work on any type of unsigned:
template <class T>
T reverse_bits(T n) {
short bits = sizeof(n) * 8;
T mask = ~T(0); // equivalent to uint32_t mask = 0b11111111111111111111111111111111;
while (bits >>= 1) {
mask ^= mask << (bits); // will convert mask to 0b00000000000000001111111111111111;
n = (n & ~mask) >> bits | (n & mask) << bits; // divide and conquer
}
return n;
}
You may use a table that store the reverse value of each byte with (i * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff
, initialized through a lambda (you will need to compile it with g++ -std=c++1z
since it only works since C++17), and then return the value in the table will give you the accordingly reversed bit:
#include <cstdint>
#include <array>
uint8_t reverse_bits(uint8_t n) {
static constexpr array<uint8_t, 256> table{[]() constexpr{
constexpr size_t SIZE = 256;
array<uint8_t, SIZE> result{};
for (size_t i = 0; i < SIZE; ++i)
result[i] = (i * 0x0202020202ULL & 0x010884422010ULL) % 0x3ff;
return result;
}()};
return table[n];
}
Try it yourself with inclusion of above function:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
template <class T>
void print_binary(T n)
{ T mask = 1ULL << ((sizeof(n) * 8) - 1); // will set the most significant bit
for(; mask != 0; mask >>= 1) putchar('0' | !!(n & mask));
putchar('\n');
}
int main() {
uint32_t n = 12;
print_binary(n);
n = reverse_bits(n);
print_binary(n);
unsigned char c = 'a';
print_binary(c);
c = reverse_bits(c);
print_binary(c);
uint16_t s = 12;
print_binary(s);
s = reverse_bits(s);
print_binary(s);
uint64_t l = 12;
print_binary(l);
l = reverse_bits(l);
print_binary(l);
return 0;
}
Last but not least, if simplest means fewer lines, why not give a try to inline assembly?
You can test below code snippet by adding -masm=intel
when compiling:
unsigned char reverse_bits(unsigned char c) {
__asm__ __volatile__ (R"(
mov cx, 8
daloop:
ror di
adc ax, ax
dec cx
jnz short daloop
;)");
}
Explanations line by line:
mov cx, 8 ; we will reverse the 8 bits contained in one byte
daloop: ; while loop
shr di ; Shift Register `di` (containing value of the first argument of callee function) to the Right
rcl ax ; Rotate Carry Left: rotate ax left and add the carry from shr di, the carry is equal to 1 if one bit was "lost" from previous operation
dec cl ; Decrement cx
jnz short daloop; Jump if cx register is Not equal to Zero, else end loop and return value contained in ax register
Try this.
This works even for tables with constraints (foreign key relationships). Alternatively you can just drop the database and recreate, but you may not have the necessary permissions to do that.
mysqldump -u[USERNAME] -p[PASSWORD] \
--add-drop-table --no-data [DATABASE] | \
grep -e '^DROP \| FOREIGN_KEY_CHECKS' | \
mysql -u[USERNAME] -p[PASSWORD] [DATABASE]
In order to overcome foreign key check effects, add show table
at the end of the generated script and run many times until the show table
command results in an empty set.
Today() does return value in DATE format.
Select your "Days left field" and paste this formula in the field =DAYS360(today(),C2)
Go to Format > Number > More formats >Custom number format and select the number with no decimal numbers.
I tested, it works, at least in new version of Sheets, March 2015.
try this
$(this).parent().css("backgroundImage", "url('../images/r-srchbg_white.png') no-repeat");
In page header, add
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">
In page stylesheet, add
html, body {
overflow-x: hidden;
overflow-y: hidden;
}
It is both html and body!
We had to change our application to build against the JDK 1.8 using Window->Preferences->Java->Installed JREs. However, after changing that, the JRE System Library specified in the Project Explorer was still incorrect. To fix this, right click on "JRE System Library [wrong-jre-here]" and change from Execution environment: to "Workspace Default (yer-default-here)"
Try this:
#include <stdio.h>
int main()
{
char s[] = "fffffffe";
int x;
sscanf(s, "%x", &x);
printf("%u\n", x);
}
i had
':'
in my project name e.g 'HKUSTx:part-2' renaming it 'HKUSTx-part-2' worked for me
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript()
function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment
link multiple times, tinymce.js
will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript()
documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript()
function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup()
as follows:
$.ajaxSetup({
cache: true
});
You can look in sys.types or use TYPE_ID:
IF TYPE_ID(N'MyType') IS NULL ...
Just a precaution: using type_id won't verify that the type is a table type--just that a type by that name exists. Otherwise gbn's query is probably better.
I think you will want to use ThreadSafeClientConnManager.
You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html
Or in the AndroidHttpClient
which uses it internally.
A Drawable
can be drawn onto a Canvas
, and a Canvas
can be backed by a Bitmap
:
(Updated to handle a quick conversion for BitmapDrawable
s and to ensure that the Bitmap
created has a valid size)
public static Bitmap drawableToBitmap (Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable)drawable).getBitmap();
}
int width = drawable.getIntrinsicWidth();
width = width > 0 ? width : 1;
int height = drawable.getIntrinsicHeight();
height = height > 0 ? height : 1;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
You don't see anything, because of buffering. The output is shown, when there are enough lines or end of file is reached. tail -f
means wait for more input, but there are no more lines in file
and so the pipe to grep
is never closed.
If you omit -f
from tail
the output is shown immediately:
tail file | grep A1 | awk '{print $NF}'
@EdMorton is right of course. Awk can search for A1
as well, which shortens the command line to
tail file | awk '/A1/ {print $NF}'
or without tail, showing the last column of all lines containing A1
awk '/A1/ {print $NF}' file
Thanks to @MitchellTracy's comment, tail
might miss the record containing A1
and thus you get no output at all. This may be solved by switching tail
and awk
, searching first through the file and only then show the last line:
awk '/A1/ {print $NF}' file | tail -n1
Conclusion from another discussion here:
Are there any drawbacks with inline functions?
Apparently, There is nothing wrong with using inline functions.
But it is worth noting the following points!
Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. - Google Guidelines
The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost - Source
There are few situations where an inline function may not work:
The __inline
keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not __inline
is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the __inline
keyword to be ignored. -Source
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
I had an quite unusual case of this error, but maybe someone would benefit from it.
I had this error with missing .dll file of one of projects in solution (with target framework netstandard 2.0) I'm working on and at once error with reference (to Microsoft.Office.Interop.Word) this project uses.
This solution was cloned from git repository, and same solution compiled well for other people in my team.
I tried every propsed solution for issue - restarting VS, computer; cleaning project; checking and unchecking build checkboxes; checking if build order is proper etc.
I figured out that manifest of this project was not selected by default (dropdown of manifest in project properties was empty and disabled). Therefore I tried to add it, but nothing worked.
At last I started comparing this project .csproj file with one in other, older version of this project, which compiled without problem. After a bit of usless tries I figured out, that path to Microsoft.Office.Interop.Word is the same in both projects, even thought it was a relative path starting with lots of "go up" symbols ( ..\ ). And not working project was one level lower than other.
Adding one more "go up" symbol ( ..\ ) in reference path to Microsoft.Office.Interop.Word inside project .csproj file solved the issue.
I have no idea why this path was created that way and doesn't update in my case, while it work properly for others in my team.
queue<int> q1, q2;
int i = 0;
void push(int v) {
if( q1.empty() && q2.empty() ) {
q1.push(v);
i = 0;
}
else {
if( i == 0 ) {
while( !q1.empty() ) q2.push(q1.pop());
q1.push(v);
i = 1-i;
}
else {
while( !q2.empty() ) q1.push(q2.pop());
q2.push(v);
i = 1-i;
}
}
}
int pop() {
if( q1.empty() && q2.empty() ) return -1;
if( i == 1 ) {
if( !q1.empty() )
return q1.pop();
else if( !q2.empty() )
return q2.pop();
}
else {
if( !q2.empty() )
return q2.pop();
else if( !q1.empty() )
return q1.pop();
}
}
For permanent solution:
The problem is with your pg_hba. This line:
local all postgres peer
Should be
local all postgres md5
Then restart your postgresql server after changing this file.
If you're on Linux, command would be
sudo service postgresql restart
Old question but adding answer so that one can get help
Its two step process:
Suppose, a table1
has a foreign key with column name fk_table2_id
, with constraint name fk_name
and table2
is referred table with key t2
(something like below in my diagram).
table1 [ fk_table2_id ] --> table2 [t2]
First step, DROP old CONSTRAINT: (reference)
ALTER TABLE `table1`
DROP FOREIGN KEY `fk_name`;
notice constraint is deleted, column is not deleted
Second step, ADD new CONSTRAINT:
ALTER TABLE `table1`
ADD CONSTRAINT `fk_name`
FOREIGN KEY (`fk_table2_id`) REFERENCES `table2` (`t2`) ON DELETE CASCADE;
adding constraint, column is already there
Example:
I have a UserDetails
table refers to Users
table:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`)
:
:
First step:
mysql> ALTER TABLE `UserDetails` DROP FOREIGN KEY `FK_User_id`;
Query OK, 1 row affected (0.07 sec)
Second step:
mysql> ALTER TABLE `UserDetails` ADD CONSTRAINT `FK_User_id`
-> FOREIGN KEY (`User_id`) REFERENCES `Users` (`User_id`) ON DELETE CASCADE;
Query OK, 1 row affected (0.02 sec)
result:
mysql> SHOW CREATE TABLE UserDetails;
:
:
`User_id` int(11) DEFAULT NULL,
PRIMARY KEY (`Detail_id`),
KEY `FK_User_id` (`User_id`),
CONSTRAINT `FK_User_id` FOREIGN KEY (`User_id`) REFERENCES
`Users` (`User_id`) ON DELETE CASCADE
:
If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m
Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini
file which is present in your Eclipse home directory.
To get the size of the JVM during Runtime you can use Runtime.totalMemory()
which returns the total amount of memory in the Java virtual machine, measured in bytes.
Hopefully this helps:
x = True
y = True
while x == True:
while y == True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y":
x,y = False,False #breaks from both loops
if ok == "n" or ok == "N":
break #breaks from just one
By default, there is not any proper answer to disable saving a password in your browser. But luckily there is a way around and it works in almost all the browsers.
To achieve this, add a dummy input just before the actual input with autocomplete="off" and some custom styling to hide it and providing tabIndex.
Some browsers' (Chrome) autocomplete will fill in the first password input it finds, and the input before that, so with this trick it will only fill in an invisible input that doesn't matter.
<div className="password-input">
<input
type="password"
id="prevent_autofill"
autoComplete="off"
style={{
opacity: '0',
position: 'absolute',
height: '0',
width: '0',
padding: '0',
margin: '0'
}}
tabIndex="-2"
/>
<input
type="password"
autoComplete="off"
className="password-input-box"
placeholder="Password"
onChange={e => this.handleChange(e, 'password')}
/>
</div>
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}