I solved an error similar to this by putting the <script>
inside a contentplaceholder
inside the <head>
instead of putting the <script>
outside the said contentplaceholder
inside the <head>
The actual solution to this problem is to approach it differently.
Probably your goal is some sort of initialization which typically happens at the top level of an application.
The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)
Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.
This is what the top level of your application should look like:
import {application} from './server'
application();
Just to address this from a C++20 Standardese perspective (working from N4860)...
A class is a type. The keywords "class
" and "struct
" (and "union
") are - in the C++ grammar - class-keys, and the only functional significance of the choice of class
or struct
is:
The class-key determines whether ... access is public or private by default (11.9).
That the class
keyword results in private-by-default members, and `struct keyword results in public-by-default members, is documented by the examples in 11.9.1:
class X { int a; // X::a is private by default: class used
...vs...
struct S { int a; // S::a is public by default: struct used
1.9 also says:
In the absence of an access-specifier for a base class,
public
is assumed when the derived class is defined with the class-keystruct
andprivate
is assumed when the class is defined with the class-keyclass
.
There's a requirement:
In a redeclaration, partial specialization, explicit specialization or explicit instantiation of a class template, the class-key shall agree in kind with the original class template declaration (9.2.8.3).
...in any elaborated-type-specifier, the
enum
keyword shall be used to refer to an enumeration (9.7.1), theunion
class-key shall be used to refer to aunion
(11.5), and either theclass
orstruct
class-key shall be used to refer to a non-union class (11.1).
The following example (of when consistency is not required) is provided:
struct S { } s; class S* p = &s; // OK
Still, some compilers may warn about this.
Interestingly, while the types you create with struct
, class
and union
are all termed "classes", we have...
A standard-layout struct is a standard layout class defined with the class-key
struct
or the class-keyclass
.
...so in Standardese, when there's talk of a standard-layout struct it's using "struct" to imply "not a union"s.
I'm curious if there are similar use of "struct" in other terminology, but it's too big a job to do an exhaustive search of the Standard. Comments about that welcome.
This was a pain, using netBeans IDE 7.2.
Add a resource folder to the src folder:
After the clean/build this structure is propogated into the Build folder:
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
Windows API and Windows SDK if you want to build everything yourself (or) Windows API and Visual C Express. Get the 2008 edition. This is a full blown IDE and a remarkable piece of software by Microsoft for Windows development.
All operating systems are written in C. So, any application, console/GUI you write in C is the standard way of writing for the operating system.
I hate to answer my own question, but in this case I think I need to. After checking it out, @Falmarri was on the right track with his answer. The problem is that Android's CheckBox control already uses the android:paddingLeft property to get the text where it is.
The red line shows the paddingLeft offset value of the entire CheckBox
If I just override that padding in my XML layout, it messes up the layout. Here's what setting paddingLeft="0" does:
Turns out you can't fix this in XML. You have do it in code. Here's my snippet with a hardcoded padding increase of 10dp.
final float scale = this.getResources().getDisplayMetrics().density;
checkBox.setPadding(checkBox.getPaddingLeft() + (int)(10.0f * scale + 0.5f),
checkBox.getPaddingTop(),
checkBox.getPaddingRight(),
checkBox.getPaddingBottom());
This gives you the following, where the green line is the increase in padding. This is safer than hardcoding a value, since different devices could use different drawables for the checkbox.
UPDATE - As people have recently mentioned in answers below, this behavior has apparently changed in Jelly Bean (4.2). Your app will need to check which version its running on, and use the appropriate method.
For 4.3+ it is simply setting padding_left. See htafoya's answer for details.
You could write a simple shell script, for example:
#!/bin/bash
mkdir "$1"
chmod 777 "$1"
Once saved, and the executable flag enabled, you could run it instead of mkdir and chmod:
./scriptname path/foldername
However, alex's answer is much better because it spawns one process instead of three. I didn't know about the -m
option.
Try to edit your my.cf and comment the original sql_mode and add sql_mode = "".
vi /etc/mysql/my.cnf
sql_mode = ""
save and quit...
service mysql restart
Using vmin
and vmax
forces the range for the colors. Here's an example:
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
cdict = {
'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}
cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)
data = 2*( np.sin(X) + np.sin(3*Y) )
def do_plot(n, f, title):
#plt.clf()
plt.subplot(1, 3, n)
plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
plt.title(title)
plt.colorbar()
plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()
As I didn't want to break anything, I did this to be able to use newer versions of Python3 than Python v3.4 :
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in auto mode
$ sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
update-alternatives: using /usr/bin/python3.7 to provide /usr/local/bin/python3 (python3) in auto mode
$ update-alternatives --list python3
/usr/bin/python3.6
/usr/bin/python3.7
$ sudo update-alternatives --config python3
There are 2 choices for the alternative python3 (providing /usr/local/bin/python3).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python3.7 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/bin/python3.7 2 manual mode
Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python3.6 to provide /usr/local/bin/python3 (python3) in manual mode
$ ls -l /usr/local/bin/python3 /etc/alternatives/python3
lrwxrwxrwx 1 root root 18 2019-05-03 02:59:03 /etc/alternatives/python3 -> /usr/bin/python3.6*
lrwxrwxrwx 1 root root 25 2019-05-03 02:58:53 /usr/local/bin/python3 -> /etc/alternatives/python3*
I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.
Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing =
's. Example:
JSON array-of-strings:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"
The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded %
signs and so on. Base64 is very neutral because it doesn't use special characters.
No issues with the latest kartoza/qgis-desktop
I ran
docker pull kartoza/qgis-desktop
followed by
docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest
I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.
I use this to get all indices:
$ curl --silent 'http://127.0.0.1:9200/_cat/indices' | cut -d\ -f3
With this list you can work on...
$ curl -s 'http://localhost:9200/_cat/indices' | head -5
green open qa-abcdefq_1458925279526 1 6 0 0 1008b 144b
green open qa-test_learnq_1460483735129 1 6 0 0 1008b 144b
green open qa-testimportd_1458925361399 1 6 0 0 1008b 144b
green open qa-test123p_reports 1 6 3868280 25605 5.9gb 870.5mb
green open qa-dan050216p_1462220967543 1 6 0 0 1008b 144b
To get the 3rd column above (names of the indices):
$ curl -s 'http://localhost:9200/_cat/indices' | head -5 | cut -d\ -f3
qa-abcdefq_1458925279526
qa-test_learnq_1460483735129
qa-testimportd_1458925361399
qa-test123p_reports
qa-dan050216p_1462220967543
NOTE: You can also use awk '{print $3}'
instead of cut -d\ -f3
.
You can also suffix the query with a ?v
to add a column header. Doing so will break the cut...
method so I'd recommend using the awk..
selection at this point.
$ curl -s 'http://localhost:9200/_cat/indices?v' | head -5
health status index pri rep docs.count docs.deleted store.size pri.store.size
green open qa-abcdefq_1458925279526 1 6 0 0 1008b 144b
green open qa-test_learnq_1460483735129 1 6 0 0 1008b 144b
green open qa-testimportd_1458925361399 1 6 0 0 1008b 144b
green open qa-test123p_reports 1 6 3868280 25605 5.9gb 870.5mb
If headerInSection isn't show, can try this.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45;
}
This returns a height for the header of a given section.
There are a few possibilities:
For starters, to eliminate (3), what happens if you telnet to that port?
Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.
If you want to manually verify the cert, post more details from the openssl s_client
output. Or use openssl x509 -text -in /path/to/cert
to print it out to your terminal.
For those using Rails(4.2) Internationalization (I18n):
Set the placeholder attribute to true:
f.text_field :attr, placeholder: true
and in your local file (ie. en.yml):
en:
helpers:
placeholder:
model_name:
attr: "some placeholder text"
Correct and more clear way is :
<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> My inline Style </div>
It is made more simple by following approach :
// JS
const styleObject = {
"font-size" : "10px",
"height" : "100px",
"width" : "100%"
}
// HTML
<div style={styleObject}> My inline Style </div>
Inline style
attribute expects object. Hence its written in {}
, and it becomes double {{}}
as one is for default react standards.
You can use LINQ str.Take(n)
or str.SubString(0, n)
, where the latter will throw an ArgumentOutOfRangeException
exception for n > str.Length
.
Mind that the LINQ version returns a IEnumerable<char>
, so you'd have to convert the IEnumerable<char>
to string
: new string(s.Take(n).ToArray())
.
pip wheel
is another option you should consider:
pip wheel mypackage -w .\outputdir
It will download packages and their dependencies to a directory (current working directory by default), but it performs the additional step of converting any source packages to wheels.
It conveniently supports requirements files:
pip wheel -r requirements.txt -w .\outputdir
Add the --no-deps
argument if you only want the specifically requested packages:
pip wheel mypackage -w .\outputdir --no-deps
I find that using a long if/else chain (or switch), in addition to the list of findViewById(btn).setOnClickListener(this)
is ugly. how about creating new View.OnlickListeners with override, in-line:
findViewById(R.id.signInButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { signIn(); }});
findViewById(R.id.signOutButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { signOut(); }});
findViewById(R.id.keyTestButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { decryptThisTest(); }});
findViewById(R.id.getBkTicksButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { getBookTickers(); }});
findViewById(R.id.getBalsButton).setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v) { getBalances(); }});
[firstNameTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
Maybe simple, economic way (less signs to use)...
$array = [];
We can read in php manual :
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:
<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%; display: inline-block;">RIGHT</p>
All previous answers are correct, you have three options for what you are asking
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'multi', 'str']
>>> vars(a)
{'multi': 4, 'str': '2'}
>>> a.__dict__
{'multi': 4, 'str': '2'}
2018 already... I've found this fantastic online tool http://mapshaper.org/ to convert from ESRI shapefiles to SVG, TopoJSON, GeoJSON.
Here is the explanation of how to use it https://www.statsilk.com/maps/convert-esri-shapefile-map-geojson-format
Fast and straightforward! :)
MySQL multiple instances present on Ubuntu.
step 1 : if it's listed as installed, you got it. Else you need to get it.
sudo ps -A | grep mysql
step 2 : remove the one MySQL
sudo apt-get remove mysql
sudo service mysql restart
step 3 : restart lamp
sudo /opt/lampp/lampp restart
you forgot to add add alpha1 in module area
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
use maven repository in project area that's it
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
You can do it, without writing JavaScript code
<head>
<script src="/path/to/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="/path/to/jquery.Aplus.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
...
<a href="delete.php?id=22" class="confirm" title="Are you sure?">Link</a>
...
</body>
On ubuntu you can add this PPA Repository and use it to install python 3.7: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.7
Or a different PPA that provides several Python versions is Deadsnakes: https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa
See also here: https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get (I know it says 3.6 in the url, but the deadsnakes ppa also contains 3.7 so you can use it for 3.7 just the same)
If you want "official" you'd have to install it from the sources from the site, get the code (which you already downloaded) and do this:
tar -xf Python-3.7.0.tar.xz
cd Python-3.7.0
./configure
make
sudo make install <-- sudo is required.
This might take a while
While former answer is absolutely correct, I prefer using the JOIN ON
syntax to be sure that I know how do I join and on what fields. It would look something like this:
SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';
This syntax seperates completely the WHERE
clause from the JOIN
clause, making the statement more readable and easier for you to debug.
Another simple way is to use the pivot
function to format the data as you need first.
df.plot()
does the rest
df = pd.DataFrame([
['red', 0, 0],
['red', 1, 1],
['red', 2, 2],
['red', 3, 3],
['red', 4, 4],
['red', 5, 5],
['red', 6, 6],
['red', 7, 7],
['red', 8, 8],
['red', 9, 9],
['blue', 0, 0],
['blue', 1, 1],
['blue', 2, 4],
['blue', 3, 9],
['blue', 4, 16],
['blue', 5, 25],
['blue', 6, 36],
['blue', 7, 49],
['blue', 8, 64],
['blue', 9, 81],
], columns=['color', 'x', 'y'])
df = df.pivot(index='x', columns='color', values='y')
df.plot()
pivot effectively turns the data into:
I think this will do it:
SELECT * FROM MyTable WHERE mydate > now()::date - 365;
This error also occurred when I compiled with MinGW using gcc with the following options:
-lstdc++ -lm
, rather than g++
I did not notice these options, and added: -static-libgcc -static-libstdc++
I still got the error, and finally realized I was using gcc, and changed the compiler to g++ and removed -stdc++ and -lm
, and everything linked fine.
(I was using LINK.c rather than LINK.cpp... use make -pn | less
to see what everything does!)
I don't know why the previous author was using gcc with -stdc++. I don't see any reason not to use g++ which will link with stdc++ automatically... and as far as I know, provide other benefits (it is the c++ compiler after all).
i it integer, int to Integer
Integer intObj = new Integer(i);
add to collection
list.add(String.valueOf(intObj));
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
I think the best way to do this with basic R is:
for( i in rownames(df) )
print(df[i, "column1"])
The advantage over the for( i in 1:nrow(df))
-approach is that you do not get into trouble if df
is empty and nrow(df)=0
.
This answer using Pandas is adapted from above, as rolling_mean
is not part of Pandas anymore
# the recommended syntax to import pandas
import pandas as pd
import numpy as np
# prepare some fake data:
# the date-time indices:
t = pd.date_range('1/1/2010', '12/31/2012', freq='D')
# the data:
x = np.arange(0, t.shape[0])
# combine the data & index into a Pandas 'Series' object
D = pd.Series(x, t)
Now, just call the function rolling
on the dataframe with a window size, which in my example below is 10 days.
d_mva10 = D.rolling(10).mean()
# d_mva is the same size as the original Series
# though obviously the first w values are NaN where w is the window size
d_mva10[:11]
2010-01-01 NaN
2010-01-02 NaN
2010-01-03 NaN
2010-01-04 NaN
2010-01-05 NaN
2010-01-06 NaN
2010-01-07 NaN
2010-01-08 NaN
2010-01-09 NaN
2010-01-10 4.5
2010-01-11 5.5
Freq: D, dtype: float64
In Arch base distributions:
sudo pacman -S python-psycopg2
pip2 install psycopg2 # Use pip or pip3 to python3
You can use killall command as well .
-o, --older-than Match only processes that are older (started before) the time specified. The time is specified as a float then a unit. The units are s,m,h,d,w,M,y for seconds, minutes, hours, days,
-e, --exact Require an exact match for very long names.
-r, --regexp Interpret process name pattern as an extended regular expression.
This worked like a charm.
I will try to explain the results of all the commands you tried.
scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)
First of all, List
is a type alias to scala.collection.immutable.List
(defined in Predef.scala).
Using the List companion object is more straightforward way to instantiate a List
. Ex: List(1.0,5.5)
scala> l
res0: List[Double] = List(1.0, 5.5)
scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)
:::
returns a list resulting from the concatenation of the given list prefix and this list
The original List is NOT modified
scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)
List(l)
is a List[List[Double]]
Definitely not what you want.
:+
returns a new list consisting of all elements of this list followed by elem.
The type is List[Any]
because it is the common superclass between List[Double]
and Double
scala> l
res3: List[Double] = List(1.0, 5.5)
l is left unmodified because no method on immutable.List
modified the List.
How about .toDateString()
?
Alternatively, use .getDate()
, .getMonth()
, and .getYear()
?
In my mind, if you want to group things by date, you simply want to access the date, not set it. Through having some set way of accessing the date field, you can compare them and group them together, no?
Check out all the fun Date methods here: MDN Docs
Edit: If you want to keep it as a date object, just do this:
var newDate = new Date(oldDate.toDateString());
Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
None of the solutions above worked for me, but html_entity_decode($json_string)
did the trick
I will rather do it manually
...database/migrations
folderphp artisan migrate
, log into your phpmyadmin or SQL(whichever the case is) and in your database, delete the table created by the migrationWorks for me, hope it helps!
You can resolve this in several ways:
g++
in stead of gcc
: g++ -g -o MatSim MatSim.cpp
-lstdc++
: gcc -g -o MatSim MatSim.cpp -lstdc++
<string.h>
by <string>
This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.
You can declare it yourself quite easily:
interface StringConstructor {
format: (formatString: string, ...replacement: any[]) => string;
}
String.format('','');
This is assuming that String.format is defined elsewhere. e.g. in Microsoft Ajax Toolkit : http://www.asp.net/ajaxlibrary/Reference.String-format-Function.ashx
this will also work
data.groupby(data['date'].dt.year)
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
If you want to create an empty data.frame with dynamic names (colnames in a variable), this can help:
names <- c("v","u","w")
df <- data.frame()
for (k in names) df[[k]]<-as.numeric()
You can change the types as well if you need so. like:
names <- c("u", "v")
df <- data.frame()
df[[names[1]]] <- as.numeric()
df[[names[2]]] <- as.character()
There is also another convention, used by many open source projects including Spring.
interface User {
}
class DefaultUser implements User {
}
class AnotherClassOfUser implements User {
}
I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.
Do you want to disable error reporting, or just prevent the user from seeing it? It’s usually a good idea to log errors, even on a production site.
# in your PHP code:
ini_set('display_errors', '0'); # don't show any errors...
error_reporting(E_ALL | E_STRICT); # ...but do log them
They will be logged to your standard system log, or use the error_log
directive to specify exactly where you want errors to go.
<form name="myForm" id="myForm" method="post" onsubmit="return validateForm();">
First Name: <input type="text" id="name" /> <br />
<span id="nameErrMsg" class="error"></span> <br />
<!-- ... all your other stuff ... -->
</form>
<p>
1.word should be atleast 5 letter<br>
2.No space should be encountered<br>
3.No numbers and special characters allowed<br>
4.letters can be repeated upto 3(eg: aa is allowed aaa is not allowed)
</p>
<button id="validateTestButton" value="Validate now" onclick="validateForm();">Validate now</button>
validateForm = function () {
return checkName();
}
function checkName() {
var x = document.myForm;
var input = x.name.value;
var errMsgHolder = document.getElementById('nameErrMsg');
if (input.length < 5) {
errMsgHolder.innerHTML =
'Please enter a name with at least 5 letters';
return false;
} else if (!(/^\S{3,}$/.test(input))) {
errMsgHolder.innerHTML =
'Name cannot contain whitespace';
return false;
}else if(!(/^[a-zA-Z]+$/.test(input)))
{
errMsgHolder.innerHTML=
'Only alphabets allowed'
}
else if(!(/^(?:(\w)(?!\1\1))+$/.test(input)))
{
errMsgHolder.innerHTML=
'per 3 alphabets allowed'
}
else {
errMsgHolder.innerHTML = '';
return undefined;
}
}
.error {
color: #E00000;
}
It is simple,for Example
-(void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"%s", __PRETTY_FUNCTION__);
}
Output: -[AppDelegate applicationWillEnterForeground:]
Deleting "Derived Data" worked for me.
In Xcode go to File > Workspace Settings > Click the arrow next to the Derived Data file path > move the "Derived Data" folder to the trash.
I presume you're running Linux on an amd64 machine.
The Folder your executable is residing in (lib32
) suggests a 32-bit executable which requires 32-bit libraries.
These seem not to be present on your system, so you need to install them manually.
The package name depends on your distribution, for Debian it's ia32-libs
, for Fedora libstdc++.<version>.i686
.
Suppose your class is called MyStudent. Here's how you define your class constructor:
Public Class MyStudent
Public StudentId As Integer
'Here's the class constructor:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class
Here's how you call it:
Dim student As New MyStudent(studentId)
Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.
Use:
docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)
... it does a "docker inspect" for all containers.
Working combinations of OS, JDK and eclipse bitness.
Kindly use 1 of the above combinations.
I had the same problem today. Try it!
sudo chown -R [yourgroup] /home/[youruser]/.composer/cache/repo/https---packagist.org/
sudo chown -R [yourgroup] /home/[youruser]/.composer/cache/files/
This example uses regex_search to perform a substring search.
- name: make conditional variable
command: "file -s /dev/xvdf"
register: fsm_out
- name: makefs
command: touch "/tmp/condition_satisfied"
when: fsm_out.stdout | regex_search(' data')
ansible version: 2.4.3.0
In my opinion setting the "validate_password_policy" to "low" or uninstalling the "validate password plugin" is not the right thing to do. You must never compromise with security of your database (unless you don't really care). I am wondering why people are even suggesting these options when you simply can pick a good password.
To overcome this problem, I executed following command in mysql: SHOW VARIABLES LIKE 'validate_password%' as suggested by @JNevill. My "validate_password_policy" was set to Medium, along with other things. Here is the screenshot of its execution: Validate Password Policy
The result is self explanatory. For a valid password (when Password policy is set to medium):
So a valid password must obey the policy. Examples of valid password for above rules maybe:
You can pick any combination as long as it satisfies the policy.
For other "validate_password_policy" you can simply look the values for different options and pick your password accordingly (I haven't tried for "STRONG").
https://dev.mysql.com/doc/refman/5.6/en/validate-password-options-variables.html
you have to follow some naming strategy when you work with spring jpa. The column name should be in lowercase or uppercase.
@Column(name="TESTNAME")
private String testName;
or
@Column(name="testname")
private String testName;
keep in mind that, if you have your column name "test_name" format in the database then you have to follow the following way
@Column(name="TestName")
private String testName;
or
@Column(name="TEST_NAME")
private String testName;
or
@Column(name="test_name")
private String testName;
Be careful to check if
display_errors
or
error_reporting
is active (not a comment) somewhere else in the ini file.
My development server refused to display errors after upgrade to Kubuntu 16.04 - I had checked php.ini numerous times ... turned out that there was a diplay_errors = off; about 100 lines below my
display_errors = on;
So remember the last one counts!
I don't know about y'all but for my own lazy purposes I just got the text fields from 'document' by ID and set the values as parameters to my back-end JS function:
//index.js_x000D_
_x000D_
<TextField_x000D_
id="field1"_x000D_
..._x000D_
/>_x000D_
_x000D_
<TextField_x000D_
id="field2"_x000D_
..._x000D_
/>_x000D_
_x000D_
<Button_x000D_
..._x000D_
onClick={() => { printIt(document.getElementById('field1').value,_x000D_
document.getElementById('field2').value) _x000D_
}}>_x000D_
_x000D_
_x000D_
//printIt.js_x000D_
_x000D_
export function printIt(text1, text2) {_x000D_
console.log('on button clicked');_x000D_
alert(text1);_x000D_
alert(text2);_x000D_
};
_x000D_
It works just fine.
You cannot directly create a table stored as a sequence file and insert text into it. You must do this:
Example:
CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;
CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;
DROP TABLE test_txt;
If you're just after padding numbers with zeros to achieve fixed length, just add the nearest multiple of 10 eg. for 2 digits, add 10^2, then remove the first 1 before displaying output.
This solution works to pad/format single numbers of any length, or a whole sequence of numbers using a for loop.
# Padding 0s zeros:
# Pure bash without externals eg. awk, sed, seq, head, tail etc.
# works with echo, no need for printf
pad=100000 ;# 5 digit fixed
for i in {0..99999}; do ((j=pad+i))
echo ${j#?}
done
Tested on Mac OSX 10.6.8, Bash ver 3.2.48
I realize that I'm a bit late with this, but you can also call sleep and pass the disired time in. For example, If I wanted to wait for 3 seconds I can do:
/bin/sleep 3
4 seconds would look like this:
/bin/sleep 4
Because Java bytecode does not retain the names of method or constructor arguments.
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
For anyone looking to set the value of a nested variable, here is how to do it:
const _ = require('lodash'); //import lodash module
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
Documentation: https://lodash.com/docs/4.17.15#set
Also, documentation if you want to get a value: https://lodash.com/docs/4.17.15#get
class obj(object):
def __init__(self, d):
for a, b in d.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, obj(b) if isinstance(b, dict) else b)
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = obj(d)
>>> x.b.c
2
>>> x.d[1].foo
'bar'
You Could do something like this .....
Your Table
CREATE TABLE TestTable
(
ID INT,
Data NVARCHAR(50)
)
GO
INSERT INTO TestTable
VALUES (1,'AABBCC'),
(2,'FFDD'),
(3,'TTHHJJKKLL')
GO
SELECT * FROM TestTable
My Suggestion
CREATE TABLE #DestinationTable
(
ID INT,
Data NVARCHAR(50)
)
GO
SELECT * INTO #Temp FROM TestTable
DECLARE @String NVARCHAR(2)
DECLARE @Data NVARCHAR(50)
DECLARE @ID INT
WHILE EXISTS (SELECT * FROM #Temp)
BEGIN
SELECT TOP 1 @Data = DATA, @ID = ID FROM #Temp
WHILE LEN(@Data) > 0
BEGIN
SET @String = LEFT(@Data, 2)
INSERT INTO #DestinationTable (ID, Data)
VALUES (@ID, @String)
SET @Data = RIGHT(@Data, LEN(@Data) -2)
END
DELETE FROM #Temp WHERE ID = @ID
END
SELECT * FROM #DestinationTable
Result Set
ID Data
1 AA
1 BB
1 CC
2 FF
2 DD
3 TT
3 HH
3 JJ
3 KK
3 LL
DROP Temp Tables
DROP TABLE #Temp
DROP TABLE #DestinationTable
We had the same ORA-01775 error but in our case, the schema user was missing some 'grant select' on a couple of the public synonyms.
I was having the same issue. I tried with the compatibility option, but in Windows 10 it doesn't show the compatibility option. The following steps solved the problem for me:
taskschd.msc
as administratorSo somehow setting up the task in taskschd.msc
as a regular user wasn't working, even though my account is an admin one.
Hope this helps anyone having the same issue
As Alex says, it works very well. The only tricky part is to remember to make any changes in the cmake files, rather than from within Visual Studio. So on all platforms, the workflow is similar to if you'd used plain old makefiles.
But it's fairly easy to work with, and I've had no issues with cmake generating invalid files or anything like that, so I wouldn't worry too much.
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
As in Internet Explorer, the javascript method "includes" doesn't support which is leading to the error as below
dijit.form.FilteringSelect TypeError: Object doesn't support property or method 'includes'
So I have changed the JavaScript string method from "includes" to "indexOf" as below
//str1 doesn't match str2 w.r.t index, so it will try to add object
var str1="acd", str2="b";
if(str1.indexOf(str2) == -1)
{
alert("add object");
}
else
{
alert("object not added");
}
I think leverage this functionality using Java
long time= System.currentTimeMillis();
this will return current time in milliseconds mode . this will surely work
long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);
Here is my logcat using the above function
05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157
If you got any doubt with millisecond value .Check Here
EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds
that mentioned in log to match with time in log you might get a different value based your system timezone
EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support
Working code :
{
DataBaseEntity db = new DataBaseEntity (); //This is EF entity
string dateCheck="5/21/2018";
var list= db.tbl
.where(x=>(x.DOE.Value.Month
+"/"+x.DOE.Value.Day
+"/"+x.DOE.Value.Year)
.ToString()
.Contains(dateCheck))
}
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
Use [label sizeToFit];
to adjust the text in UILabel
Even though this is much later than the request, it might help others. Docmosis provides a Java API for creating documents in doc,pdf,odt format using documents as templates. It uses OpenOffice as the engine to perform the format conversions. Document manipulation and population is performed by Docmosis itself.
We're not necessarily talking theoretical limits here, we're talking about real world limits of the 2GB max file size AND database schema.
The schema is on even footing with the row count in determining how many rows you can have.
We have used Access MDBs to store exports of MS-SQL data for statistical analysis by some of our corporate users. In those cases we've exported our core table structure, typically four tables with 20 to 150 columns varying from a hundred bytes per row to upwards of 8000 bytes per row. In these cases, we would bump up against a few hundred thousand rows of data were permissible PER MDB that we would ship them.
So, I just don't think that this question has an answer in absence of your schema.
To achieve this, there are simply two steps,
Step 1: Go to AndroidManifest.xml
and add this parameter in the <activity>
tag - android:parentActivityName=".home.HomeActivity"
Example:
<activity
android:name=".home.ActivityDetail"
android:parentActivityName=".home.HomeActivity"
android:screenOrientation="portrait" />
Step 2: In ActivityDetail
add your action
for previous page/activity
Example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
You can use code like this:
char *MyFunction(some arguments...)
{
char *pointer = malloc(size for the new array);
if (!pointer)
An error occurred, abort or do something about the error.
return pointer; // Return address of memory to the caller.
}
When you do this, the memory should later be freed, by passing the address to free.
There are other options. A routine might return a pointer to an array (or portion of an array) that is part of some existing structure. The caller might pass an array, and the routine merely writes into the array, rather than allocating space for a new array.
The time zone is a session parameter. So, you can change the timezone for the current session.
See the doc.
set timezone TO 'GMT';
Or, more closely following the SQL standard, use the SET TIME ZONE
command. Notice two words for "TIME ZONE" where the code above uses a single word "timezone".
SET TIME ZONE 'UTC';
The doc explains the difference:
SET TIME ZONE extends syntax defined in the SQL standard. The standard allows only numeric time zone offsets while PostgreSQL allows more flexible time-zone specifications. All other SET features are PostgreSQL extensions.
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate
http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');
I oversimplified this (I use http.onload(function() {})
instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value
parameters (i.e. PHP won't show any $_POST
variables). You must pass the form header in to get that, and do that before http.send()
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
If you're using JSON and not URL-encoded data, pass application/json
instead
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
It looks like body-parser
did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency
After looking through some of the modules in mscdex's answer, I found that express-busboy
was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.
console.log(req.files)
using body-parser (Express 3) output an object that looked like this:
{ file:
{ fieldName: 'file',
originalFilename: '360px-Cute_Monkey_cropped.jpg',
name: '360px-Cute_Monkey_cropped.jpg'
path: 'uploads/6323-16v7rc.jpg',
type: 'image/jpeg',
headers:
{ 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
'content-type': 'image/jpeg' },
ws:
WriteStream { /* ... */ },
size: 48614 } }
compared to console.log(req.files)
using express-busboy (Express 4):
{ file:
{ field: 'file',
filename: '360px-Cute_Monkey_cropped.jpg',
file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
truncated: false
uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }
If you are trying this on a latest Mac OS X Mavericks, command line tools come with the Xcode 5.x
So make sure you have installed & updated Xcode to latest
after which make sure Xcode command line tools is pointed correctly using this command
xcode-select -p
Which might show some path like
/Applications/Xcode.app/Contents/Developer
Change the path to correct path using the switch command:
sudo xcode-select --switch /Library/Developer/CommandLineTools/
this should help you set it to correct path, after which you can use the same above command -p to check if it is set correctly
Since Java 8, List inherits a default "forEach" method which you can combine with the method reference "System.out::println" like this:
list.forEach(System.out::println);
/** SUBTRACT ARRAYS **/
function subtractarrays(array1, array2){
var difference = [];
for( var i = 0; i < array1.length; i++ ) {
if( $.inArray( array1[i], array2 ) == -1 ) {
difference.push(array1[i]);
}
}
return difference;
}
You can then call the function anywhere in your code.
var I_like = ["love", "sex", "food"];
var she_likes = ["love", "food"];
alert( "what I like and she does't like is: " + subtractarrays( I_like, she_likes ) ); //returns "Naughty :P"!
This works in all cases and avoids the problems in the methods above. Hope that helps!
"
is valid in both HTML5 and HTML4.
'
is valid in HTML5, but not HTML4. However, most browsers support '
for HTML4 anyway.
Maybe this is an old question and that´s the reason why these answers didn't work for me ... using Visual Studio 2019, after some investigating, this is the solution I've found:
this.InvokePaint(this, new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.
How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try This Code
Visibility works fine in this code
This is an old thread but apparently the C++ Faq
has a section (Archived 2013 version) on this. This apparently will be updated if the author is contacted so this will probably be more up to date in the long run, but here is the current version:
Depends on what you mean. If you mean, Is it possible to convert C++ to readable and maintainable C-code? then sorry, the answer is No — C++ features don't directly map to C, plus the generated C code is not intended for humans to follow. If instead you mean, Are there compilers which convert C++ to C for the purpose of compiling onto a platform that yet doesn't have a C++ compiler? then you're in luck — keep reading.
A compiler which compiles C++ to C does full syntax and semantic checking on the program, and just happens to use C code as a way of generating object code. Such a compiler is not merely some kind of fancy macro processor. (And please don't email me claiming these are preprocessors — they are not — they are full compilers.) It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.
Here are some products that perform compilation to C:
- Comeau Computing offers a compiler based on Edison Design Group's front end that outputs C code.
- LLVM is a downloadable compiler that emits C code. See also here and here. Here is an example of C++ to C conversion via LLVM.
Cfront, the original implementation of C++, done by Bjarne Stroustrup and others at AT&T, generates C code. However it has two problems: it's been difficult to obtain a license since the mid 90s when it started going through a maze of ownership changes, and development ceased at that same time and so it doesn't get bug fixes and doesn't support any of the newer language features (e.g., exceptions, namespaces, RTTI, member templates).
Contrary to popular myth, as of this writing there is no version of g++ that translates C++ to C. Such a thing seems to be doable, but I am not aware that anyone has actually done it (yet).
Note that you typically need to specify the target platform's CPU, OS and C compiler so that the generated C code will be specifically targeted for this platform. This means: (a) you probably can't take the C code generated for platform X and compile it on platform Y; and (b) it'll be difficult to do the translation yourself — it'll probably be a lot cheaper/safer with one of these tools.
One more time: do not email me saying these are just preprocessors — they are not — they are compilers.
For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant
. There's a tutorial, or you could just dive straight in:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
PyEnchant
comes with a few dictionaries (en_GB, en_US, de_DE, fr_FR), but can use any of the OpenOffice ones if you want more languages.
There appears to be a pluralisation library called inflect
, but I've no idea whether it's any good.
The URI to open a specific channel in Slack app is:
slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>
You will probably need these resources of the Slack API to get IDs of your team and channel:
Here's the full documentation from Slack
You can use $inject service to inject a service in you config
app.config(function($provide){ $provide.decorator("$exceptionHandler", function($delegate, $injector){ return function(exception, cause){ var $rootScope = $injector.get("$rootScope"); $rootScope.addError({message:"Exception", reason:exception}); $delegate(exception, cause); }; }); });
Source: http://odetocode.com/blogs/scott/archive/2014/04/21/better-error-handling-in-angularjs.aspx
The javax.mail-api
artifact is only good for compiling against.
You actually need to run code, so you need a complete implementation of JavaMail API. Use this:
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
NOTE: The version number will probably differ. Check the latest version here.
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
I see this hasn't been answered as final.
I see you have max-width as 100% and width as 600. Flip those.
A simple way also is:
<img src="image.png" style="max-width:600px;width:100%">
I use this often, and then you can control individual images as well, and not have it on all img tags. You could CSS it also like below.
.image600{
width:100%;
max-width:600px;
}
<img src="image.png" class="image600">
I had the similar problem. Just after adding below dependency
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
<type>bundle</type>
</dependency>
caused the problem. I deleted that dependency even then I'm getting the same error. I don't know what happened. I tried updating the maven dependency configuration which solved my issue.
We were seeing this same issue in one of our old projects that was targeting Framework 4.5.2. I tried several scenarios including all of the ones listed above: target 4.6.1, add System.ValueTuple package, delete bin, obj, and .vs folders. No dice. Repeat the same process for 4.7.2. Then tried removing the System.ValueTuple package since I was targeting 4.7.2 as one commenter suggested. Still nothing. Checked csproj file reference path. Looks right. Even dropped back down to 4.5.2 and installing the package again. All this with several VS restarts and deleting the same folders several times. Literally nothing worked.
I had to refactor to use a struct instead. I hope others don't continue to run into this issue in the future but thought this might be helpful if you end up as stumped up as we were.
If you are not a big fan of operator overloading, or just more of a functional type:
// use flatMap
let result = [
["merge", "me"],
["We", "shall", "unite"],
["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]
// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]
core.autocrlf=input
is the right setting for what you want, but you might have to do a git update-index --refresh
and/or a git reset --hard
for the change to take effect.
With core.autocrlf
set to input
, git will not apply newline-conversion on check-out (so if you have LF in the repo, you'll get LF), but it will make sure that in case you mess up and introduce some CRLFs in the working copy somehow, they won't make their way into the repo.
I had the same error, and in my case X and y were dataframes so I had to convert them to matrices first:
X = X.values.astype(np.float)
y = y.values.astype(np.float)
Edit: The originally suggested X.as_matrix() is Deprecated
Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.
Client to call REST webservice:
package in.india.client.downloadfiledemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;
public class DownloadFileClient {
private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";
public DownloadFileClient() {
try {
Client client = Client.create();
WebResource objWebResource = client.resource(BASE_URI);
ClientResponse response = objWebResource.path("/")
.type(MediaType.TEXT_HTML).get(ClientResponse.class);
System.out.println("response : " + response);
if (response.getStatus() == Status.OK.getStatusCode()
&& response.hasEntity()) {
MultiPart objMultiPart = response.getEntity(MultiPart.class);
java.util.List<BodyPart> listBodyPart = objMultiPart
.getBodyParts();
BodyPart filenameBodyPart = listBodyPart.get(0);
BodyPart fileLengthBodyPart = listBodyPart.get(1);
BodyPart fileBodyPart = listBodyPart.get(2);
String filename = filenameBodyPart.getEntityAs(String.class);
String fileLength = fileLengthBodyPart
.getEntityAs(String.class);
File streamedFile = fileBodyPart.getEntityAs(File.class);
BufferedInputStream objBufferedInputStream = new BufferedInputStream(
new FileInputStream(streamedFile));
byte[] bytes = new byte[objBufferedInputStream.available()];
objBufferedInputStream.read(bytes);
String outFileName = "D:/"
+ filename;
System.out.println("File name is : " + filename
+ " and length is : " + fileLength);
FileOutputStream objFileOutputStream = new FileOutputStream(
outFileName);
objFileOutputStream.write(bytes);
objFileOutputStream.close();
objBufferedInputStream.close();
File receivedFile = new File(outFileName);
System.out.print("Is the file size is same? :\t");
System.out.println(Long.parseLong(fileLength) == receivedFile
.length());
}
} catch (UniformInterfaceException e) {
e.printStackTrace();
} catch (ClientHandlerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
new DownloadFileClient();
}
}
Service to response client:
package in.india.service.downloadfiledemo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.multipart.MultiPart;
@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {
@GET
public Response getFile() {
java.io.File objFile = new java.io.File(
"D:/DanGilbert_2004-480p-en.mp4");
MultiPart objMultiPart = new MultiPart();
objMultiPart.type(new MediaType("multipart", "mixed"));
objMultiPart
.bodyPart(objFile.getName(), new MediaType("text", "plain"));
objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
"plain"));
objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));
return Response.ok(objMultiPart).build();
}
}
JAR needed:
jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar
WEB.XML:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>DownloadFileDemo</display-name>
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>in.india.service.downloadfiledemo</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:
curl -o <filename-to-save-as> -u <username>:<password> <url>
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
If you try to count the number of rows in the already autofiltered range like this:
Rowz = rnData.SpecialCells(xlCellTypeVisible).Rows.Count
It will only count the number of rows in the first contiguous visible area of the autofiltered range. E.g. if the autofilter range is rows 1 through 10 and rows 3, 5, 6, 7, and 9 are filtered, four rows are visible (rows 2, 4, 8, and 10), but it would return 2 because the first contiguous visible range is rows 1 (the header row) and 2.
A more accurate alternative is this (assuming that ws
contains the worksheet with the filtered data):
Rowz = ws.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
We have to subtract 1 to remove the header row. We need to include the header row in our counted range because SpecialCells will throw an error if no cells are found, which we want to avoid.
The Cells
property will give you an accurate count even if the Range has multiple Areas, unlike the Rows
property. So we just take the first column of the autofilter range and count the number of visible cells.
INSERT INTO test VALUES('a line\nanother line');
\n
just works fine here
You don't escape quotes in regular expressions
this.Vals.replace(/["']/g, "")
You can either do this with the following:
Calendar cal = Calendar.getInstance();
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date date = cal.getTime();
If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:
// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();
if (condition1)
{
predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}
if (condition2)
{
predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}
if (condition3)
{
predicate = predicate.And(d => d.SomeIntProperty >= 4);
}
return originalCollection.Where<YourDataClass>(predicate.Compile());
The full source of mentioned PredicateBuilder
is bellow (but you could also check the original page with a few more examples):
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T> () { return f => true; }
public static Expression<Func<T, bool>> False<T> () { return f => false; }
public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}
}
Note: I've tested this approach with Portable Class Library project and have to use .Compile()
to make it work:
Where(predicate .Compile() );
Usually form is submitted on Enter when you have focus on input elements.
We can disable Enter key (code 13
) on input elements within a form:
$('form input').on('keypress', function(e) {
return e.which !== 13;
});
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:
def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
println "Match #$i: ${g[1]}"
}
Match #0: HELLO
Match #1: THERE
Match #2: WORLD
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:
// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...
static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.
Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.
Windows automatically chooses the proper icon from the file, depending on where it is to be displayed.
For more information on icon design and the sizes/bit depths you should include, see these references:
Just install pillow with pip install pillow
and it will work.
running the various solutions on some real world data - 12M rows varchar length ~30, around 9k dodgy rows, no full text index in play, the patIndex solution is the fastest, and it also selects the most rows.
(pre-ran km. to set the cache to a known state, ran the 3 processes, and finally ran km again - the last 2 runs of km gave times within 2 seconds)
patindex solution by Gerhard Weiss -- Runtime 0:38, returns 9144 rows
select dodgyColumn from myTable fcc
WHERE patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,dodgyColumn ) >0
the substring-numbers solution by MT. -- Runtime 1:16, returned 8996 rows
select dodgyColumn from myTable fcc
INNER JOIN dbo.Numbers32k dn ON dn.number<(len(fcc.dodgyColumn ))
WHERE ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))<32
OR ASCII(SUBSTRING(fcc.dodgyColumn , dn.Number, 1))>127
udf solution by Deon Robertson -- Runtime 3:47, returns 7316 rows
select dodgyColumn
from myTable
where dbo.udf_test_ContainsNonASCIIChars(dodgyColumn , 1) = 1
I've found that the solution the works best for me is to just perform the merge and abort it if there are conflicts. This particular syntax feels clean and simple to me. This is Strategy 2 below.
However, if you want to ensure you don't mess up your current branch, or you're just not ready to merge regardless of the existence of conflicts, simply create a new sub-branch off of it and merge that:
git checkout mybranch
git checkout -b mynew-temporary-branch
git merge some-other-branch
That way you can simply throw away the temporary branch if you just want to see what the conflicts are. You don't need to bother "aborting" the merge, and you can go back to your work -- simply checkout 'mybranch' again and you won't have any merged code or merge conflicts in your branch.
This is basically a dry-run.
git checkout mybranch
git merge some-other-branch
If git reports conflicts (and ONLY IF THERE ARE conflicts) you can then do:
git merge --abort
If the merge is successful, you cannot abort it (only reset).
If you're not ready to merge, use the safer way above.
[EDIT: 2016-Nov - I swapped strategy 1 for 2, because it seems to be that most people are looking for "the safe way". Strategy 2 is now more of a note that you can simply abort the merge if the merge has conflicts that you're not ready to deal with. Keep in mind if reading comments!]
You can actually use C# generics for this to make it real easy:
var file = new List<string>(System.IO.File.ReadAllLines("C:\\path"));
file.RemoveAt(12);
File.WriteAllLines("C:\\path", file.ToArray());
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
HashMap
is mutable; there's no need for a builder.
Map<String, Integer> map = Maps.newHashMap();
map.put("a", 1);
map.put("b", 2);
it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...)
That's not correct, and you will be unable to cite an authoriitative source for that claim. It should be changed whenever you make a change that is incompatible under the rules given in the Versioning of Serializable Objects section of the Object Serialization Specification, which specifically does not include additional fields or change of field order, and when you haven't provided readObject(), writeObject(),
and/or readResolve()
or /writeReplace()
methods and/or a serializableFields
declaration that could cope with the change.
Actually you don't even need the block:
Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'
File.open(playlist_name, 'w').puts(music)
From the documentation:
UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL. UPSERT syntax was added to SQLite with version 3.24.0 (pending).
An UPSERT is an ordinary INSERT statement that is followed by the special ON CONFLICT clause
Image source: https://www.sqlite.org/images/syntax/upsert-clause.gif
Strings.xml
<string name="my_text"><Data><![CDATA[<b>Your text</b>]]></Data></string>
To set
textView.setText(Html.fromHtml(getString(R.string.activity_completed_text)));
use the val() method:
$(document).ready(function () {
var j = $("textarea");
if (j.val().length > 0) {
alert(j.val());
}
});
Primes are unique numbers. They are unique in that, the product of a prime with any other number has the best chance of being unique (not as unique as the prime itself of-course) due to the fact that a prime is used to compose it. This property is used in hashing functions.
Given a string “Samuel”, you can generate a unique hash by multiply each of the constituent digits or letters with a prime number and adding them up. This is why primes are used.
However using primes is an old technique. The key here to understand that as long as you can generate a sufficiently unique key you can move to other hashing techniques too. Go here for more on this topic about http://www.azillionmonkeys.com/qed/hash.html
http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
As others have said, # coding:
specifies the encoding the source file is saved in. Here are some examples to illustrate this:
A file saved on disk as cp437 (my console encoding), but no encoding declared
b = 'über'
u = u'über'
print b,repr(b)
print u,repr(u)
Output:
File "C:\ex.py", line 1
SyntaxError: Non-ASCII character '\x81' in file C:\ex.py on line 1, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for details
Output of file with # coding: cp437
added:
über '\x81ber'
über u'\xfcber'
At first, Python didn't know the encoding and complained about the non-ASCII character. Once it knew the encoding, the byte string got the bytes that were actually on disk. For the Unicode string, Python read \x81, knew that in cp437 that was a ü, and decoded it into the Unicode codepoint for ü which is U+00FC. When the byte string was printed, Python sent the hex value 81
to the console directly. When the Unicode string was printed, Python correctly detected my console encoding as cp437 and translated Unicode ü to the cp437 value for ü.
Here's what happens with a file declared and saved in UTF-8:
++ber '\xc3\xbcber'
über u'\xfcber'
In UTF-8, ü is encoded as the hex bytes C3 BC
, so the byte string contains those bytes, but the Unicode string is identical to the first example. Python read the two bytes and decoded it correctly. Python printed the byte string incorrectly, because it sent the two UTF-8 bytes representing ü directly to my cp437 console.
Here the file is declared cp437, but saved in UTF-8:
++ber '\xc3\xbcber'
++ber u'\u251c\u255dber'
The byte string still got the bytes on disk (UTF-8 hex bytes C3 BC
), but interpreted them as two cp437 characters instead of a single UTF-8-encoded character. Those two characters where translated to Unicode code points, and everything prints incorrectly.
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
If you are not familiar with the code and you want to find ViewController coresponding to given view, then you can try:
po (UIView *)0x7fe523bd3000 po [(UIView *)0x7fe523bd3000 nextResponder] po [[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] po [[[(UIView *)0x7fe523bd3000 nextResponder] nextResponder] nextResponder] ...
In most cases you will get UIView, but from time to time there will be UIViewController based class.
You have an extra closing }
in your function.
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <== remove this brace
}, false);
};
You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.
Given:
uint n = 3;
int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only
//i will be negative if n > Int32.MaxValue
int i = (int)n; //same behavior as unchecked
or
int i = Convert.ToInt32(n); //same behavior as checked
--EDIT
Included info as mentioned by Kenan E. K.
If the fallback keys are not too many you can do something like this
value = my_dict.get('first_key') or my_dict.get('second_key')
Postman 4.0.5 has a feature named Manage Cookies located below the Send button which manages the cookies separately from Chrome it seems.
In case this helps someone, for me, none of the above was sufficient. I still couldn't build, VS still couldn't find the references. The key was simply to close and reopen the solution after restoring the packages.
Here's the scenario (using Visual Studio 2012):
You open a Solution that has missing packages. The references show that VS can't find them. There are many ways to restore the missing packages, including
nuget restore
if you have the command line nuget installedBut no matter what the approach, those references will still be shown as missing. And when you build it will fail. Sigh. However if you close the solution and re-open it, now VS checks those nice <HintPath>
s again, finds that the packages are back where they belong, and all is well with the world.
Is Visual Studio still not seeing that you have the package? Still showing a reference that it can't resolve? Make sure that the version of package you restored is exactly the same as the <HintPath>
in your .csproj file. Even a minor bug fix number (e.g. 1.10.1 to 1.10.2) will cause the reference to fail. You can fix this either by directly editing your csproj xml, or else by removing the reference and making a new one pointing at the newly-restored version in the packages directory.
Increasing number of max-connections will not solve the problem.
We were experiencing the same situation on our servers. This is what happens
User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.
You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour
SET interactive_timeout=3600
I had two charts.
<div id="barChart"></div>
<div id="bubbleChart"></div>
This removed all charts.
d3.select("svg").remove();
This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after
d3.select("#barChart").remove();
Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.
d3.select("#barChart").select("svg").remove();
var svg = d3.select('#barChart')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.
Yes, you can simulate a mouse click by creating an event and dispatching it:
function click(x,y){
var ev = document.createEvent("MouseEvent");
var el = document.elementFromPoint(x,y);
ev.initMouseEvent(
"click",
true /* bubble */, true /* cancelable */,
window, null,
x, y, 0, 0, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/, null
);
el.dispatchEvent(ev);
}
Beware of using the click
method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click()
does the right thing but have not confirmed.
Use the keys()
iterator to iterate over all the properties, and call get()
for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
You will also get 'root element is missing' when the BOM strikes :). BOM = byte order mark. This is an extra character that gets added to the start of a file when it is saved with the wrong encoding.
This can happen sometimes in Visual Studio when working with XML files. You can either code something to remove it from all your files, or if you know which file it is you can force visual studio to save it with a specific encoding (utf-8 or ascii IIRC).
If you open the file in an editor other than VS (try notepad++), you will see two funny characters before the <? xml declaration.
To fix this in VS, open the file in VS and then depending on the version of VS
Latest Versions of mysql don't support DATEADD instead use the syntax
DATE_ADD(date,INTERVAL expr type)
To get the last 3 months data use,
DATE_ADD(NOW(),INTERVAL -90 DAY)
DATE_ADD(NOW(), INTERVAL -3 MONTH)
To answer the exact question:
import "github.com/golang/protobuf/ptypes"
Timestamp, _ = ptypes.TimestampProto(time.Now())
To obtain the id of the documents in a collection, you must use snapshotChanges()
this.shirtCollection = afs.collection<Shirt>('shirts');
// .snapshotChanges() returns a DocumentChangeAction[], which contains
// a lot of information about "what happened" with each change. If you want to
// get the data and the id use the map operator.
this.shirts = this.shirtCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Shirt;
const id = a.payload.doc.id;
return { id, ...data };
});
});
Documentation https://github.com/angular/angularfire2/blob/7eb3e51022c7381dfc94ffb9e12555065f060639/docs/firestore/collections.md#example
In Class1:
Class2 inst = new Class2();
inst.UpdateEmployee();
How about more simply:
import datetime
now = datetime.datetime.now()
datetime.date(now.year, 1 if now.month==12 else now.month+1, 1) - datetime.timedelta(days=1)
This command list the tasks related to the 'node' and have each of them terminated.
kill -9 $( ps -ae | grep 'node' | awk '{print $1}')
$columns = implode(", ",array_keys($data));
$escaped_values = array_map(array($con, 'real_escape_string'),array_values($data));
$values = implode("', '", $escaped_values);
return $sql = "INSERT INTO `reservations`($columns) VALUES ('$values')";
This is improvement to the solution given by Shiplu Mokaddim
Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified
It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:
iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.
The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.
Update:
There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.
http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions
Fastest way to do this is using "SELECT INTO" command e.g.
SELECT * INTO #TempTableName
FROM....
This will create a new table, you don't have to create it in advance.
How about this one? lot cleaner and all in single line.
foreach ((array) $items as $item) {
// ...
}
This is one sample dao test using junit in spring project.
import java.util.List;
import junit.framework.Assert;
import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
@Autowired
private MemberDao memberDao;
@Test
public void testFindById()
{
Member member = memberDao.findById(0l);
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testFindByEmail()
{
Member member = memberDao.findByEmail("[email protected]");
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testRegister()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
Long id = member.getId();
Assert.assertNotNull(id);
Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
Member newMember = memberDao.findById(id);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
@Test
public void testFindAllOrderedByName()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
List<Member> members = memberDao.findAllOrderedByName();
Assert.assertEquals(2, members.size());
Member newMember = members.get(0);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
}
While dbenham's answer is pretty good, relying on IF DEFINED
can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.
While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF
with IF /?
reveals that,
The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.
In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR
check to me, both in regards to underlying logic and readability. For example:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.
If you wanted to have it all on one line, written-wise, you could just chain them together with &&
like:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
@zzzz's answer is mostly complete, but just to save others from having to dig through the referenced documentation you can run a single test in a package as follows:
go test packageName -run TestName
Note that you want to pass in the name of the test, not the file name where the test exists.
The -run
flag actually accepts a regex so you could limit the test run to a class of tests. From the docs:
-run regexp
Run only those tests and examples matching the regular
expression.
The accepted answer has an off by one error for multi line files which don't end in newline. A one line file ending without a newline would return 1, but a two line file ending without a newline would return 1 too. Here's an implementation of the accepted solution which fixes this. The endsWithoutNewLine checks are wasteful for everything but the final read, but should be trivial time wise compared to the overall function.
public int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean endsWithoutNewLine = false;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
endsWithoutNewLine = (c[readChars - 1] != '\n');
}
if(endsWithoutNewLine) {
++count;
}
return count;
} finally {
is.close();
}
}
$ mysqladmin variables | grep sock
Try this instead, this will output the demanded result, getting rid of unrelated info.
Referer and user-agent are request header, not response header.
That means they are sent by browser, or your ajax call (which you can modify the value), and they are decided before you get HTTP response.
So basically you are not asking for a HTTP header, but a browser setting.
The value you get from document.referer and navigator.userAgent may not be the actual header, but a setting of browser.
I use the following
void split(string in, vector<string>& parts, char separator) {
string::iterator ts, curr;
ts = curr = in.begin();
for(; curr <= in.end(); curr++ ) {
if( (curr == in.end() || *curr == separator) && curr > ts )
parts.push_back( string( ts, curr ));
if( curr == in.end() )
break;
if( *curr == separator ) ts = curr + 1;
}
}
PlasmaHH, I forgot to include the extra check( curr > ts) for removing tokens with whitespace.
You can use cyrilletuzi's LocalStorage Asynchronous Angular 2+ Service.
Install:
$ npm install --save @ngx-pwa/local-storage
Usage:
// your.service.ts
import { LocalStorage } from '@ngx-pwa/local-storage';
@Injectable()
export class YourService {
constructor(private localStorage: LocalStorage) { }
}
// Syntax
this.localStorage
.setItem('user', { firstName:'Henri', lastName:'Bergson' })
.subscribe( () => {} );
this.localStorage
.getItem<User>('user')
.subscribe( (user) => { alert(user.firstName); /*should be 'Henri'*/ } );
this.localStorage
.removeItem('user')
.subscribe( () => {} );
// Simplified syntax
this.localStorage.setItemSubscribe('user', { firstName:'Henri', lastName:'Bergson' });
this.localStorage.removeItemSubscribe('user');
More info here:
https://www.npmjs.com/package/@ngx-pwa/local-storage
https://github.com/cyrilletuzi/angular-async-local-storage
A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.
Maps do not support the [subscript]
notation used by Objects. That syntax implicitly casts the subscript
value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key)
, .set(key, value)
and .has(key)
.
var m = new Map();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
m.set(key1, 'value1');_x000D_
m.set(key2, 'value2');_x000D_
_x000D_
console.assert(m.has(key2), "m should contain key2.");_x000D_
console.assert(!m.has(key3), "m should not contain key3.");
_x000D_
Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2
and key3
because their string representations would be the same:
var o = new Object();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
o[key1] = 'value1';_x000D_
o[key2] = 'value2';_x000D_
_x000D_
console.assert(o.hasOwnProperty(key2), "o should contain key2.");_x000D_
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
_x000D_
Eclipse Photon user here, found it under the toolbar's Windows > Preferences > Install/Update > "Uninstall or update" link > Click stuff and hit the "Uninstall" button.
Here's a short one-liner using regular expressions:
print [re.compile(r"8").sub("", m) for m in mylist]
If we separate the regex operations and improve the namings:
pattern = re.compile(r"8") # Create the regular expression to match
res = [pattern.sub("", match) for match in mylist] # Remove match on each element
print res
Still looking for a solution? I got mine from this link .
All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".
var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));
Yes, you have to add:
You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.
Got it working! I should have been building a JSONArray
of JSONObject
s and then add the array to a final "Addresses" JSONObject
. Observe the following:
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel
I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.
writer.writerow(("ColName1", "ColName2", "ColName"))
for i in range(len(first_col_list)):
writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))
If you want to get a UTF-16 encoded code unit as a char
, you can parse the integer and cast to it as others have suggested.
If you want to support all code points, use Character.toChars(int)
. This will handle cases where code points cannot fit in a single char
value.
Doc says:
Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.
I found this component. https://github.com/jsdf/react-native-htmlview
This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.
You could use the third-party frozendict
module to freeze your dict and make it hashable.
from frozendict import frozendict
my_dict = frozendict(my_dict)
For handling nested objects, you could go with:
import collections.abc
def make_hashable(x):
if isinstance(x, collections.abc.Hashable):
return x
elif isinstance(x, collections.abc.Sequence):
return tuple(make_hashable(xi) for xi in x)
elif isinstance(x, collections.abc.Set):
return frozenset(make_hashable(xi) for xi in x)
elif isinstance(x, collections.abc.Mapping):
return frozendict({k: make_hashable(v) for k, v in x.items()})
else:
raise TypeError("Don't know how to make {} objects hashable".format(type(x).__name__))
If you want to support more types, use functools.singledispatch
(Python 3.7):
@functools.singledispatch
def make_hashable(x):
raise TypeError("Don't know how to make {} objects hashable".format(type(x).__name__))
@make_hashable.register
def _(x: collections.abc.Hashable):
return x
@make_hashable.register
def _(x: collections.abc.Sequence):
return tuple(make_hashable(xi) for xi in x)
@make_hashable.register
def _(x: collections.abc.Set):
return frozenset(make_hashable(xi) for xi in x)
@make_hashable.register
def _(x: collections.abc.Mapping):
return frozendict({k: make_hashable(v) for k, v in x.items()})
# add your own types here
Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data
. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):
POST
to /users
to create the user entity.POST
the image to /images
, making sure to return a Location
header to where the image can be retrieved per the HTTP spec.PATCH
to /users/carPhoto
and assign it the ID of the photo given in the Location
header of step 2.My Attempt ( JsFiddle)
Javascript
$(document).ready(function () {
$('#buttons input[type=button]').on('click', function () {
var qty = $(this).data('quantity');
var price = $('#totalPrice').text();
$('#count').val(price * qty);
});
});
Html
Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
<input id='qty2' type="button" data-quantity='2' value="2
Qty">
<input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4
Qty">
</div>
<br>Total
<input type="text" id="count" value="1">
Decimal and Numeric are the same functionally but there is still data type precedence, which can be crucial in some cases.
SELECT SQL_VARIANT_PROPERTY(CAST(1 AS NUMERIC) + CAST(1 AS DECIMAL),'basetype')
The resulting data type is numeric because it takes data type precedence.
Exhaustive list of data types by precedence:
In python, we start defining a function with "def" and generally, but not necessarily, end the function with "return".
A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2
Now, the code of this function will be:
def A_function (x):
return x + 2
After defining the function, you can use that for any variable and get result. Such as:
print A_function (2)
>>> 4
We could just write the code slightly differently, such as:
def A_function (x):
y = x + 2
return y
print A_function (2)
That would also give "4".
Now, we can even use this code:
def A_function (x):
x = x + 2
return x
print A_function (2)
That would also give 4. See, that the "x" beside return actually means (x+2), not x of "A_function(x)".
I guess from this simple example, you would understand the meaning of return command.
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
Hope that helps. :)
Get the graphviz-2.24.msi Graphviz.org. Then get zgrviewer.
Zgrviewer requires java (probably 1.5+). You might have to set the paths to the Graphviz binaries in Zgrviewer's preferences.
File -> Open -> Open with dot -> SVG pipeline (standard) ... Pick your .dot file.
You can zoom in, export, all kinds of fun stuff.
Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div>
as a wrapper around elements with .w-100.
Try this:
<div class="btn-group d-flex" role="group>
<button type="button" class="btn btn-primary w-100">Submit</button>
<button type="button" class="btn btn-primary w-100">Cancel</button>
</div>
What you assign one object to another, all you're doing is copying the reference to the object, not the contents of it. What you need to do is take your object B and manually copy the contents of object A into it.
If you do this often, you might consider implementing a clone()
method on the class that will create a new object of the same type, and copy all of it's contents into the new object.
On Gitlab, markdown supports this : [[_TOC_]]
If you need simple mechanism to import from text/parse multiline CSV you could use:
CREATE TABLE t -- OR INSERT INTO tab(col_names)
AS
SELECT
t.f[1] AS col1
,t.f[2]::int AS col2
,t.f[3]::date AS col3
,t.f[4] AS col4
FROM (
SELECT regexp_split_to_array(l, ',') AS f
FROM regexp_split_to_table(
$$a,1,2016-01-01,bbb
c,2,2018-01-01,ddd
e,3,2019-01-01,eee$$, '\n') AS l) t;
I think what the OP is looking for is a simple, windows-like solution.
here ya go:
You can parse a string into an integer with int.parse()
. For example:
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
Note that int.parse()
accepts 0x
prefixed strings. Otherwise the input is treated as base-10.
You can parse a string into a double with double.parse()
. For example:
var myDouble = double.parse('123.45');
assert(myDouble is double);
print(myDouble); // 123.45
parse()
will throw FormatException if it cannot parse the input.
Here is how I did it using Angular 4.
Template
<div class="col-xs-12 col-md-3">
<h2>Categories</h2>
<div class="cat-list-body">
<div class="cat-item" *ngFor="let cat of web.menu | async">
<label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label>
</div>
</div>
</div>
add this function to the Component.
scroll(id) {
console.log(`scrolling to ${id}`);
let el = document.getElementById(id);
el.scrollIntoView();
}
Unchecking "Is Library" in the project Properties worked for me.
Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:
insert into blob_fun values(1, hextoraw('453d7a34'));
453d7a34
is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.
May help to someone:
I'm sending data from react
application to golang
server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*")
. Error has fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
you can also see many examples in R cookbook
olddata_wide <- read.table(header=TRUE, text='
subject sex control cond1 cond2
1 M 7.9 12.3 10.7
2 F 6.3 10.6 11.1
3 F 9.5 13.1 13.8
4 M 11.5 13.4 12.9
')
# Make sure the subject column is a factor
olddata_wide$subject <- factor(olddata_wide$subject)
olddata_long <- read.table(header=TRUE, text='
subject sex condition measurement
1 M control 7.9
1 M cond1 12.3
1 M cond2 10.7
2 F control 6.3
2 F cond1 10.6
2 F cond2 11.1
3 F control 9.5
3 F cond1 13.1
3 F cond2 13.8
4 M control 11.5
4 M cond1 13.4
4 M cond2 12.9
')
# Make sure the subject column is a factor
olddata_long$subject <- factor(olddata_long$subject)
This border is used to show that the element is focused (i.e. you can type in the input or press the button with Enter). You can remove it with outline property, though:
textarea:focus, input:focus{
outline: none;
}
You may want to add some other way for users to know what element has keyboard focus though for usability.
Chrome will also apply highlighting to other elements such as DIV's used as modals. To prevent the highlight on those and all other elements as well, you can do:
*:focus {
outline: none;
}
Please notice that removing outline from input is an accessibility bad practice. Users using screen readers will not be able to see where their pointer is focused at. More info at a11yproject
I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:
RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]
The above line fixed it for me. where *folder_name* is the magento root folder.
Hope this helps!
Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:
lstDepartment.ClearSelection();
foreach (var item in lstDepartment.Items)
{
if (item.Value == otherDropDownList.SelectedValue)
{
item.Selected = true;
}
}
|
is a metacharacter in regex. You'd need to escape it:
String[] value_split = rat_values.split("\\|");
I had the same problem when trying out Android Studio. I already had projects running on the ADT under SDK 18. No need to hack the manifest files.
Fixed by:
export ANDROID_HOME= pathtobundle/adt-bundle-linux-x86_64-20130729/sdk
If you don't have the ADT installed, and just want the SDK, it seems like a good solution is to install everything and then point Android Studio to the just the packaged SDK.
cd pathtobundle
wget http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20130729.zip
unzip *.zip
As someone else said, you may need to run the SDK Manager to install the desired packages before running Studio.