I was working on a fresh project and got the similar type of problem.
I just ran ng update --all
and my problem was solved.
For ubuntu 16.04, there is firewall issue. You need to open 8080 port using following command:
sudo ufw allow 8080
Detailed steps are given here: https://www.digitalocean.com/community/tutorials/how-to-install-jenkins-on-ubuntu-16-04
Yet another method to solve: updating registry. In my case I could not alter GPO, and -UseBasicParsing breaks parts of the access to the website. Also I had a service user without log in permissions, so I could not log in as the user and run the GUI.
To fix,
In the file
On Xiaomi Mi5s with MIUI8.3 (Android 6) Xiaomi.EU Rom:
Settings/ Other Settings / Developer Options / Switch on: Allow USB Debug, Allow USB install and Allow USB Debug (Security options)
{Sorry for the translation, my device has spanish}
use DIRECTORY option.
Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907
DIRECTORY
Default: DATA_PUMP_DIR
Purpose
Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.
Syntax and Description
DIRECTORY=directory_object
The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.
A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.
Example
The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".
> impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp
LOGFILE=dpump_dir2:expfull.log
This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.
Suppose this is your json
{
"date":"11/05/2016",
"venue": "{\"ID\":12,\"CITY\":Delhi}"
}
if you again want deserialize venue, modify json as below
{
"date":"11/05/2016",
"venue": "{\"ID\":\"12\",\"CITY\":\"Delhi\"}"
}
then try to deserialize to respective class by taking the value of venue
If you encounter this error during trying to run ember server
command please rm -rf tmp
directory. Then run ember s
again. It helped me.
Personally, I have create a file.sh (right 755) in the root directory, file who do this job, on order of the crontab.
Crontab code:
10 2 * * * root /root/backupautomatique.sh
File.sh code:
rm -f /home/mordb-148-251-89-66.sql.gz #(To erase the old one)
mysqldump mor | gzip > /home/mordb-148-251-89-66.sql.gz (what you have done)
scp -P2222 /home/mordb-148-251-89-66.sql.gz root@otherip:/home/mordbexternes/mordb-148-251-89-66.sql.gz
(to send a copy somewhere else if the sending server crashes, because too old, like me ;-))
You need to add your source files with git add
or the GUI equivalent so that Git will begin tracking them.
Use git status
to see what Git thinks about the files in any given directory.
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
I know the original posters question was solved, but I came here via Google, and the various answers eventually led me to discovering that my SQL was dumped with a different default charset than the one used to import it. I got the same error as the original question, but as our dump was piped into another MySQL client, we couldn't go the route of opening it with another tool and saving it differently.
For us, the solution turned out to be the --default-character-set=utf8mb4
option, to be used both on the call of mysqldump
as well as the call to import it via mysql
. Of course, the value of the parameter may differ for others facing the same problem, it's just important to keep it the same, as the servers (or the tools) default setting might be any charset.
def word_replace(filename,old,new):
c=0
with open(filename,'r+',encoding ='utf-8') as f:
a=f.read()
b=a.split()
for i in range(0,len(b)):
if b[i]==old:
c=c+1
old=old.center(len(old)+2)
new=new.center(len(new)+2)
d=a.replace(old,new,c)
f.truncate(0)
f.seek(0)
f.write(d)
print('All words have been replaced!!!')
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat
contains:
"This is the original content"
Then you can simply write:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
root@h1:bin[0]# mount h2:/ /x
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#
ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
You can use jhat
(Java Heap Analysis Tool) to read the generated file:
jhat [ options ] <heap-dump-file>
The jhat command parses a java heap dump file and launches a webserver. jhat enables you to browse heap dumps using your favorite webbrowser.
Note that you should have a hprof
binary format output to be able to parse it with jhat
. You can use format=b
option to generate the dump in this format.
-dump:format=b,file=<filename>
The most pythonic way to do this to use map
function.
df.columns = df.columns.map(' '.join).str.strip()
Output print(df.columns)
:
Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
's_PC sum', 'tempf amax', 'tempf amin', 'year'],
dtype='object')
df.columns = [f'{f} {s}' if s != '' else f'{f}'
for f, s in df.columns]
print(df.columns)
Output:
Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
's_PC sum', 'tempf amax', 'tempf amin', 'year'],
dtype='object')
subprocess.check_output(...)
calls the process, raises if its error code is nonzero, and otherwise returns its stdout. It's just a quick shorthand so you don't have to worry about PIPE
s and things.
In working with a similar problem I created the following function after combining a lot of resources I ran into on the web, and adding my own cookie handling. Hopefully this is useful to someone else.
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Certificates
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
Maybe you can try the following without XPath
from simplified_scrapy.simplified_doc import SimplifiedDoc
html = '''
<html>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.</p>
<p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
'''
# What XPath can do, so can it
doc = SimplifiedDoc(html)
# The result is the same as doc.getElementByTag('body').getElementByTag('div').getElementByTag('h1').text
print (doc.body.div.h1.text)
print (doc.div.h1.text)
print (doc.h1.text) # Shorter paths will be faster
print (doc.div.getChildren())
print (doc.div.getChildren('p'))
The mktemp(1)
man page explains it fairly well:
Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.
In a script, I invoke mktemp something like
mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.
mktemp
is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others
By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…
My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...
For instance, if inserting into a temp table:
CREATE TABLE #TempTable
(field1 varchar(max), field2 varchar(max), ...
ROW_ID int IDENTITY(1,1) NOT NULL)
Note that the ROW_ID
field MUST always be specified as LAST field!
I think this is what you want, I already tested this code and works
The tools used are: (all these tools can be downloaded as Nuget packages)
http://fluentassertions.codeplex.com/
http://autofixture.codeplex.com/
https://nuget.org/packages/AutoFixture.AutoMoq
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
var sut = fixture.CreateAnonymous<Transfer>();
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
.Throws<System.IO.IOException>();
sut.Invoking(x =>
x.TransferFiles(
myInterface.Object,
It.IsAny<string>(),
It.IsAny<string>()
))
.ShouldThrow<System.IO.IOException>();
Edited:
Let me explain:
When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer
So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code
When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs
In this case your external dependency is IFileConnection
so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected
var fixture = new Fixture().Customize(new AutoMoqCustomization());
: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
: This freezes the IFileConnection
dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object
var sut = fixture.CreateAnonymous<Transfer>();
: Here AutoFixture is creating the SUT for us
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>();
Here you are configuring the dependency to throw an exception whenever the Get
method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception
sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();
: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles
real method from the SUT and as parameters it receives the mocked IFileConnection
so whenever you call the IFileConnection.Get
in the normal flow of your SUT TransferFiles
method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>()
(from the FluentAssertions library)
References recommended:
http://martinfowler.com/articles/mocksArentStubs.html
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/presentations/
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:
f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()
f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()
To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
adding log4j-1.2.12.jar file has resolved the issue for me
If the line before your error contains COMMENT ''
either populate the comment in the script or remove the empty comment definition. I've found this in scripts generated by MySQL Workbench.
Iconv to the rescue.
For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.
The cleanup function is executed on the EXIT
signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.
#!/bin/bash
# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`
# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
echo "Could not create temp dir"
exit 1
fi
# deletes the temp directory
function cleanup {
rm -rf "$WORK_DIR"
echo "Deleted temp working directory $WORK_DIR"
}
# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# implementation of script starts here
...
Directory of bash script from here.
Bash traps.
private function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen ($url, 'rb');
if ($file) {
$newf = fopen ($newfname, 'wb');
if ($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
You should delete the file in the folder first , then the folder.This way you will recursively call the method.
You can use the File.deleteOnExit()
method
https://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
The datetime
module documentation says:
Return a datetime corresponding to date_string, parsed according to format. This is equivalent to
datetime(*(time.strptime(date_string, format)[0:6]))
.
See that [0:6]
? That gets you (year, month, day, hour, minute, second)
. Nothing else. No mention of timezones.
Interestingly, [Win XP SP2, Python 2.6, 2.7] passing your example to time.strptime
doesn't work but if you strip off the " %Z" and the " EST" it does work. Also using "UTC" or "GMT" instead of "EST" works. "PST" and "MEZ" don't work. Puzzling.
It's worth noting this has been updated as of version 3.2 and the same documentation now also states the following:
When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance.
Note that this doesn't work with %Z, so the case is important. See the following example:
In [1]: from datetime import datetime
In [2]: start_time = datetime.strptime('2018-04-18-17-04-30-AEST','%Y-%m-%d-%H-%M-%S-%Z')
In [3]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: None
In [4]: start_time = datetime.strptime('2018-04-18-17-04-30-+1000','%Y-%m-%d-%H-%M-%S-%z')
In [5]: print("TZ NAME: {tz}".format(tz=start_time.tzname()))
TZ NAME: UTC+10:00
Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'
# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)
# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'
Each of the values in the $permissions
variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.
Courtesy of this page.
Looks like you have a dos line ending file. The clue is the ^M
.
You need to re-save the file using Unix line endings.
You might have a dos2unix
command line utility that will also do this for you.
sed
doesn't support \t
, nor other escape sequences like \n
for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed
.
That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:
#!/usr/bin/env python
import sys
import re
def main(args):
if len(args) < 2:
print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
raise SystemExit
p = re.compile(args[0], re.MULTILINE | re.DOTALL)
s = sys.stdin.read()
print p.sub(args[1], s),
if __name__ == '__main__':
main(sys.argv[1:])
Use below command on UNIX terminal :
java -XshowSettings
This will display all java properties and system settings.
In this look for java.io.tmpdir
value.
The command-line program for 7-Zip is 7z or 7za. Here's a helpful post on the options available. The -r (recurse) option stores paths.
IMO, you need to work with such directories as usual, but instead of checking permissions before use, provide the correct way to handle UnauthorizedAccessException and react accordingly. This method is easier and much less error prone.
I create the database myself using the command line. Then try to import again, it works.
Combining other answers, why not use the ms timestamp with a random value appended; repeat until no conflict, which in practice will be almost never.
For example: File-ccyymmdd-hhmmss-mmm-rrrrrr.txt
I suggest you use null to represent a null value.
What is the exception you get?
BTW:
There is no year called 0 or 0000. (Though some dates allow this year)
And there is no 0 month of the year or 0 day of the month. (Which may be the cause of your problem)
You don't need a derived table at all for this.
Just put the INTO
after the first SELECT
SELECT top(100)*
INTO tmpFerdeen
FROM Customers
UNION All
SELECT top(100)*
FROM CustomerEurope
UNION All
SELECT top(100)*
FROM CustomerAsia
UNION All
SELECT top(100)*
FROM CustomerAmericas
How about:
Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")
It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.
The .NET implementation of UrlEncode
does not comply with RFC 3986.
Some characters are not encoded but should be. The !()*
characters are listed in the RFC's section 2.2 as a reserved characters that must be encoded yet .NET fails to encode these characters.
Some characters are encoded but should not be. The .-_
characters are not listed in the RFC's section 2.2 as a reserved character that should not be encoded yet .NET erroneously encodes these characters.
The RFC specifies that to be consistent, implementations should use upper-case HEXDIG, where .NET produces lower-case HEXDIG.
impdp
exports the DDL of a dmp
backup to a file if you use the SQLFILE
parameter. For example, put this into a text file
impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
Then check ddl_dump.txt
for the tablespaces, users, and schemas in the backup.
According to the documentation, this does not actually modify the database:
The SQL is not actually executed, and the target system remains unchanged.
I don't think HTTP is limited to POST in multipart or x-www-form-urlencoded. The Content-Type Header is orthogonal to the HTTP POST method (you can fill MIME type which suits you). This is also the case for typical HTML representation based webapps (e.g. json payload became very popular for transmitting payload for ajax requests).
Regarding Restful API over HTTP the most popular content-types I came in touch with are application/xml and application/json.
I would try to represent binary data as own asset/resource. It adds another call but decouples stuff better. Example images:
POST /images
Content-type: multipart/mixed; boundary="xxxx"
... multipart data
201 Created
Location: http://imageserver.org/../foo.jpg
In later resources you could simply inline the binary resource as link:
<main-resource>
...
<link href="http://imageserver.org/../foo.jpg"/>
</main-resource>
We use a CTE wrapped in Dynamic SQL (because our application requires dynamic sorting of data server side) within a stored procedure. I can provide a basic example if you'd like.
I haven't had a chance to look at the T/SQL that LINQ produces. Can someone post a sample?
We don't use LINQ or straight access to the tables as we require the extra layer of security (granted the dynamic SQL breaks this somewhat).
Something like this should do the trick. You can add in parameterized values for parameters, etc.
exec sp_executesql 'WITH MyCTE AS (
SELECT TOP (10) ROW_NUMBER () OVER ' + @SortingColumn + ' as RowID, Col1, Col2
FROM MyTable
WHERE Col4 = ''Something''
)
SELECT *
FROM MyCTE
WHERE RowID BETWEEN 10 and 20'
The best that I've been able to do is
$(this).closest('.modal').modal('toggle');
This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.
You can however do this:
$(".modal:visible").modal('toggle');
This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
id -u
is much better than whoami
, since some systems like android may not provide the word root.
Example:
# whoami
whoami
whoami: unknown uid 0
Suppose you have something like:
I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py
It does what I need, little documentation, but feel free to copy ideas from there ;-)
(Seems to work fine with my backups at least.)
Use this
word-wrap: break-word;
overflow-wrap: break-word;
word-break: break-all;
Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:
f"({self.goals} goals, ${self.penalties})"
This is similar to the previous .format
standard, but lets one easily do things like:
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result: 12.35'
fromDic.ToList().ForEach(x =>
{
if (toDic.ContainsKey(x.Key))
toDic.Remove(x.Key);
toDic.Add(x);
});
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
Yes, you can:
You can create a C-language project by using C++ project templates. In the generated project, locate files that have a .cpp file name extension and change it to .c. Then, on the Project Properties page for the project (not for the solution), expand Configuration Properties, C/C++ and select Advanced. Change the Compile As setting to Compile as C Code (/TC).
https://docs.microsoft.com/en-us/cpp/ide/visual-cpp-project-types?view=vs-2017
This is what helped me to understand the entire issue:
And in the following another example of a problematic query.
Problematic:
SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM `gameplay`
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY)
AND cookieid = #
Solved by adding this to the end:
GROUP BY timestamp, userid, cookieid, questionid, answerid, elapsed, ipaddress
Note: See the error message in PHP, it tells you where the problem lies.
Example:
MySQL query error 1140: In aggregated query without GROUP BY, expression #4 of SELECT list contains nonaggregated column 'db.gameplay.timestamp'; this is incompatible with sql_mode=only_full_group_by - Query: SELECT COUNT(*) as attempts, SUM(elapsed) as elapsedtotal, userid, timestamp, questionid, answerid, SUM(correct) as correct, elapsed, ipaddress FROM gameplay WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 DAY) AND userid = 1
In this case, expression #4 was missing in the GROUP BY.
There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype
Therefore you need only query for NOT TRUE:
SELECT * from table_name WHERE boolean_column IS NOT TRUE;
both seem to be working.
see fiddle: http://jsfiddle.net/maniator/PSxkS/
Eclipse > Help > Eclipse Marketplace...
Search for m2e
Install Maven Integration for Eclipse (Juno and newer)
. [It works for Indigo also]
You can make the copy constructor private and provide no implementation:
private:
SymbolIndexer(const SymbolIndexer&);
Or in C++11, explicitly forbid it:
SymbolIndexer(const SymbolIndexer&) = delete;
This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).
http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html
http://digital.ni.com/public.nsf/allkb/4EA929B78B5718238625789D0071F307
This error occurs because the default value is true for the Embed Interop Types property of the TestStand API Interop assembly referenced in the new project. To resolve this error, change the value of the Embed Interop Types property to False by following these steps: Select the TestStand Interop Assembly reference in the references section of your project in the Solution Explorer. Find the Embed Interop Types property in the Property Browser, and change the value to False
Easy solution in Python3+:
import time
todaysdate = time.strftime("%d/%m/%Y")
#with '.' isntead of '/'
todaysdate = time.strftime("%d.%m.%Y")
See any reference manual, such as the man page:
f,F
The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal point appears, at least one digit appears before it. (The SUSv2 does not know about F and says that character string representations for infinity and NaN may be made available. The C99 standard specifies '[-]inf' or '[-]infinity' for infinity, and a string starting with 'nan' for NaN, in the case of f conversion, and '[-]INF' or '[-]INFINITY' or 'NAN*' in the case of F conversion.)
g,G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
By default, it begins by processing the first target that does not begin with a .
aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.
The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.
Watch out using Crypto!!!
It is a wonderful library but it has an issue in python3.8 'cause from the library time was removed the attribute clock(). To fix it just modify the source in /usr/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py
line 77 changing t = time.clock()
int t = time.perf_counter()
I use something like this in my document.ready
var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device
$("#container").width(width+"px");
$("#container").height(height+"px");
try this
var insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
The best answer according to the Python programming FAQ would be:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct
In Python, we handle exceptions similar to other language, but the difference is some syntax difference, for example,
try:
#Your code in which exception can occur
except <here we can put in a particular exception name>:
# We can call that exception here also, like ZeroDivisionError()
# now your code
# We can put in a finally block also
finally:
# Your code...
If you want a timestamp instead of just a date with sysdate, you can specify a timezone using systimestamp:
select systimestamp at time zone 'UTC' from dual
outputs: 29-AUG-17 06.51.14.781998000 PM UTC
column-span: all; /* W3C */
-webkit-column-span: all; /* Safari & Chrome */
-moz-column-span: all; /* Firefox */
-ms-column-span: all; /* Internet Explorer */
-o-column-span: all; /* Opera */
http://www.quackit.com/css/css3/properties/css_column-span.cfm
That would do the trick in a Mac :
ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')
That resolved to ping 192.168.1.2
in my machine.
Pro tip: $(...)
means run whatever is inside the parentheses in a subshell and return that as the value.
This one finally gave me the answer I was looking for. It lets you retrieve all the names and phone numbers of the contacts on the phone.
package com.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class TestContacts extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur != null && cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt.equals(cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)))) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
int i = 0;
int pCount = pCur.getCount();
String[] phoneNum = new String[pCount];
String[] phoneType = new String[pCount];
while (pCur != null && pCur.moveToNext()) {
phoneNum[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneType[i] = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.TYPE));
i++;
}
}
}
}
}
}
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.
For us, everything was fine, emails are very small and not a lot of them are sent and sudently it gave this error. It appeared that a technicien installed ASTARO which was preventing email to be sent. and we were getting this error so yes the error is a bit cryptic but I hope this could help others.
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
Restart the adb server, from android studio: Tools -> "Troubleshhot Device Connection"
You need to check that the myString
object is null
:
if (myString != null) {
doSomething
}
Here's an upstart solution I've been using for my personal projects:
Place it in /etc/init/node_app_daemon.conf
:
description "Node.js Daemon"
author "Adam Eberlin"
stop on shutdown
respawn
respawn limit 3 15
script
export APP_HOME="/srv/www/MyUserAccount/server"
cd $APP_HOME
exec sudo -u user /usr/bin/node server.js
end script
This will also handle respawning your application in the event that it crashes. It will give up attempts to respawn your application if it crashes 3 or more times in less than 15 seconds.
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
Easiest way for checking file is empty or not:
if [ -s /path-to-file/filename.txt ]
then
echo "File is not empty"
else
echo "File is empty"
fi
You can also write it on single line:
[ -s /path-to-file/filename.txt ] && echo "File is not empty" || echo "File is empty"
Here are a couple of optimizations you can apply you speed up things. Just thinking out loud.
Since the number of rows can be in the millions, you will want a caching system just for the JSON data from the server. I can't imagine anybody wanting to download all X million items, but if they did, it would be a problem. This little test on Chrome for an array on 20M+ integers crashes on my machine constantly.
var data = [];
for(var i = 0; i < 20000000; i++) {
data.push(i);
}
console.log(data.length);?
You could use LRU or some other caching algorithm and have an upper bound on how much data you're willing to cache.
For the table cells themselves, I think constructing/destroying DOM nodes can be expensive. Instead, you could just pre-define X number of cells, and whenever the user scrolls to a new position, inject the JSON data into these cells. The scrollbar would virtually have no direct relationship to how much space (height) is required to represent the entire dataset. You could arbitrarily set the table container's height, say 5000px, and map that to the total number of rows. For example, if the containers height is 5000px and there are a total of 10M rows, then the starting row ˜ (scroll.top/5000) * 10M
where scroll.top
represents the scroll distance from the top of the container. Small demo here.
To detect when to request more data, ideally an object should act as a mediator that listens to scroll events. This object keeps track of how fast the user is scrolling, and when it looks like the user is slowing down or has completely stopped, makes a data request for the corresponding rows. Retrieving data in this fashion means your data is going to be fragmented, so the cache should be designed with that in mind.
Also the browser limits on maximum outgoing connections can play an important part. A user may scroll to a certain position which will fire an AJAX request, but before that finishes the user can scroll to some other portion. If the server is not responsive enough the requests would get queued up and the application will look unresponsive. You could use a request manager through which all requests are routed, and it can cancel pending requests to make space.
You can check the application-specific data in your emulator as follows,
adb shell
in cmd/data/data/
and navigate into your applicationThere you can find the cache data and databases specific to your application
The answer to the question is $("[id$='txtTitle']")
, as Mark Hurd answered, but for those who, like me, want to find all the elements with an id which starts with a given string (for example txtTitle), try this (doc) :
$("[id^='txtTitle']")
If you want to select elements which id contains a given string (doc) :
$("[id*='txtTitle']")
If you want to select elements which id is not a given string (doc) :
$("[id!='myValue']")
(it also matches the elements that don't have the specified attribute)
If you want to select elements which id contains a given word, delimited by spaces (doc) :
$("[id~='myValue']")
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen (doc) :
$("[id|='myValue']")
FYI. You can now just update VS 2012:
"We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web."
on Windows if MySQL is install as a service you can change the binpath of the service. For example
sc config MySQL57 binPath= "\"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe\" --defaults-file=\"<myini path>" MySQL57"
space after binpath is important. You must escape double quotes
I usually use PHP's built in error handlers that can handle every possible error outside of syntax and still render a nice 'Down for maintenance' page otherwise:
I had a similar problem to you. I'm not that keen on the other answers here because they don't really allow you to style the newline behaviour very easily. I'm not sure if you have control over the original data, but the solution I adopted was to switch "items" from being an array of strings to being an array of arrays, where each item in the second array contained a line of text. That way you can do something like:
<div ng-repeat="item in items">
<p ng-repeat="para in item.description">
{{para}}
</p>
</div>
This way you can apply classes to the paragraphs and style them nicely with CSS.
First check to see if it can be cast.
if (readData is T) {
return (T)readData;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
To change database owner:
ALTER AUTHORIZATION ON DATABASE::YourDatabaseName TO sa
As of SQL Server 2014 you can still use sp_changedbowner
as well, even though Microsoft promised to remove it in the "future" version after SQL Server 2012. They removed it from SQL Server 2014 BOL though.
According to current Backbone documentation....
view.remove()
Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.
boost::ptr_vector<int>
will work.
Edit: was a suggestion to use std::vector< boost::ref<int> >
, which will not work because you can't default-construct a boost::ref
.
In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.
<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>
It is actually possible:
foo( 'blah', (new ReflectionFunction('foo'))->getParameters()[1]->getDefaultValue(), 'test');
Whether you would want to do so is another story :)
The reasons to avoid this solution are:
But it can actually be useful in situations where:
you don't want/can't change the original function.
you could change the function but:
null
(or equivalent) is not an option (see DiegoDD's comment)func_num_args()
About the performance, a very simple test shows that using the Reflection API to get the default parameters makes the function call 25 times slower, while it still takes less than one microsecond. You should know if you can to live with that.
Of course, if you mean to use it in a loop, you should get the default value beforehand.
You're probably going to have to break up your timestamp into ymd:HM and use DIV 5 to split the minutes up into 5-minute bins -- something like
select year(a.timestamp),
month(a.timestamp),
hour(a.timestamp),
minute(a.timestamp) DIV 5,
name,
count(b.name)
FROM time a, id b
WHERE a.user = b.user AND a.id = b.id AND b.name = 'John'
AND a.timestamp BETWEEN '2010-11-16 10:30:00' AND '2010-11-16 11:00:00'
GROUP BY year(a.timestamp),
month(a.timestamp),
hour(a.timestamp),
minute(a.timestamp) DIV 12
...and then futz the output in client code to appear the way you like it. Or, you can build up the whole date string using the sql concat operatorinstead of getting separate columns, if you like.
select concat(year(a.timestamp), "-", month(a.timestamp), "-" ,day(a.timestamp),
" " , lpad(hour(a.timestamp),2,'0'), ":",
lpad((minute(a.timestamp) DIV 5) * 5, 2, '0'))
...and then group on that
I try to write working code example, I test it and everything works.
Hare is code:
HTML:
<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />
Javascript:
//function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
var val = $(element).val(); //get file value
var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention
if ($.inArray(ext, extentionsArray) == -1) {
alert('false extension!');
}
var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
if (fileSize > maxSize) {
alert("Large file");// if Maxsize from Model > real file size alert this
}
}
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
You can certainly us the a Select Agregation statement as Postulated by Ben James, However This will result in a view with as many columns as you have tables. An alternate method may be as follows:
SELECT COUNT(user_table.id) AS TableCount,'user_table' AS TableSource FROM user_table
UNION SELECT COUNT(cat_table.id) AS TableCount,'cat_table' AS TableSource FROM cat_table
UNION SELECT COUNT(course_table.id) AS TableCount, 'course_table' AS TableSource From course_table;
The Nice thing about an approch like this is that you can explicitly write the Union statements and generate a view or create a temp table to hold values that are added consecutively from a Proc cals using variables in place of your table names. I tend to go more with the latter, but it really depends on personal preference and application. If you are sure the tables will never change, you want the data in a single row format, and you will not be adding tables. stick with Ben James' solution. Otherwise I'd advise flexibility, you can always hack a cross tab struc.
You need to load the URL Helper in order to use base_url()
. In your controller, do:
$this->load->helper('url');
Then in your view you can do:
echo base_url();
In plain JS add { passive: false }
as third argument
document.addEventListener('wheel', function(e) {
e.preventDefault();
doStuff(e);
}, { passive: false });
awk one liner
$ awk '{printf (NR>1?",":"") $2}' file
+12.0,+15.5,+9.0,+13.5
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
i had same problem. i updated to new version of VirtualBox 5.2.26 and checked to make sure Bridge Adapter was enabled in the installation process now is working
Debian appears to include the following:
I'll test symlinks of each for mpic, etc., and see if that helps the likes of HDF5-openmpi enabled find mpi.h.
Take that back Debian includes symlinks via their alternatives system and it still cannot find the proper paths between HDF5 openmpi packages and mpi.h referenced in the H5public.h header.
You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:
gitk HEAD @{u}
I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:
git push -f
The -f
makes this a “forced push” and overwrites the branch on the server. That is very dangerous when you are working in team. But
since you are on your own and sure that your local state is correct
this should be fine. You risk losing commit history if that is not the case.
Minimal webpack config for jsx with sourcemaps:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: `./src/index.jsx` ,
output: {
path: path.resolve(__dirname,"build"),
filename: "bundle.js"
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
};
Running it:
Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
Asset Size Chunks Chunk Names
bundle.js 1.5 MB 0 [emitted] main
bundle.js.map 1.72 MB 0 [emitted] main
+ 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$
The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:
htmlspecialchars
htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into < b >. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.
echo htmlspecialchars('An example <br>'); // This will print - An example < br >
echo htmlspecialchars('µ †'); // This will print - µ †
htmlentities
htmlentities ( string $string) is very similar to htmlspecialchars and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike htmlspecialchars, htmlentities converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.
echo htmlentities('An example <br>'); // This will print - An example < br >
echo htmlentities('µ †'); // This will print - µ †
As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:
var v = {}; //put everything here
var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x; //so on...
console.log(v); //it's all there
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Using Git from the command line with Bash you can do the following:
git commit -m "this is
> a line
> with new lines
> maybe"
Simply type and press Enter when you want a new line, the ">" symbol means that you have pressed Enter, and there is a new line. Other answers work also.
(Swift 3) Add text box and uipickerview to the storyboard then add delegate and data source to uipickerview and add delegate to textbox. Follow video for assistance https://youtu.be/SfjZwgxlwcc
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var textBox: UITextField!
@IBOutlet weak var dropDown: UIPickerView!
var list = ["1", "2", "3"]
public func numberOfComponents(in pickerView: UIPickerView) -> Int{
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return list.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
self.view.endEditing(true)
return list[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.textBox.text = self.list[row]
self.dropDown.isHidden = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.textBox {
self.dropDown.isHidden = false
//if you don't want the users to se the keyboard type:
textField.endEditing(true)
}
}
}
I found a solution for myself
var acService = new google.maps.places.AutocompleteService();
var autocompleteItems = [];
acService.getPlacePredictions({
types: ['(regions)']
}, function(predictions) {
predictions.forEach(function(prediction) {
if (prediction.types.some(function(x) {
return x === "country" || x === "administrative_area1" || x === "locality";
})) {
if (prediction.terms.length < 3) {
autocompleteItems.push(prediction);
}
}
});
});
this solution only show city and country..
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
I have a lot of issues with most of the answers posted - they either use deprecated libraries that have been ported over with limited features, or provide a solution with too much magic on the execution of the request, making it difficult to error handle. If they do not fall into one of the above categories, they're 3rd party libraries or deprecated.
Some of the solutions works alright purely in http requests, but the solutions fall short for any other kind of request, which is ludicrous. A highly customized solution is not necessary here.
Simply using the python built-in library asyncio
is sufficient enough to perform asynchronous requests of any type, as well as providing enough fluidity for complex and usecase specific error handling.
import asyncio
loop = asyncio.get_event_loop()
def do_thing(params):
async def get_rpc_info_and_do_chores(id):
# do things
response = perform_grpc_call(id)
do_chores(response)
async def get_httpapi_info_and_do_chores(id):
# do things
response = requests.get(URL)
do_chores(response)
async_tasks = []
for element in list(params.list_of_things):
async_tasks.append(loop.create_task(get_chan_info_and_do_chores(id)))
async_tasks.append(loop.create_task(get_httpapi_info_and_do_chores(ch_id)))
loop.run_until_complete(asyncio.gather(*async_tasks))
How it works is simple. You're creating a series of tasks you'd like to occur asynchronously, and then asking a loop to execute those tasks and exit upon completion. No extra libraries subject to lack of maintenance, no lack of functionality required.
If you are using MVC 5.1 or upper there is simplier and clearer way: just use data annotation (from System.ComponentModel.DataAnnotations
namespace) like below:
public enum Color
{
[Display(Name = "Dark red")]
DarkRed,
[Display(Name = "Very dark red")]
VeryDarkRed,
[Display(Name = "Red or just black?")]
ReallyDarkRed
}
And in view, just put it into proper html helper:
@Html.EnumDropDownListFor(model => model.Color)
Using PyV8, I can do this. However, I have to replace document.write
with return
because there's no DOM and therefore no document
.
import PyV8
ctx = PyV8.JSContext()
ctx.enter()
js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
"""
print ctx.eval(js.replace("document.write", "return "))
Or you could create a mock document object
class MockDocument(object):
def __init__(self):
self.value = ''
def write(self, *args):
self.value += ''.join(str(i) for i in args)
class Global(PyV8.JSClass):
def __init__(self):
self.document = MockDocument()
scope = Global()
ctx = PyV8.JSContext(scope)
ctx.enter()
ctx.eval(js)
print scope.document.value
Just finish it up.
string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";
DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
DataSet ds = new DataSet();
using (SqlCommand cmd = new SqlCommand(
sqlCommand, new SqlConnection(connectionString)))
{
cmd.Connection.Open();
DataTable table = new DataTable();
table.Load(cmd.ExecuteReader());
ds.Tables.Add(table);
}
return ds;
}
I got the same use case today(31/07/2018) and found this to be a workaround. It is based on my research and it worked for me. Expectation - To achieve the following in TypeScript:
var myStaticClass = {
property: 10,
method: function(){}
}
I did this:
//MyStaticMembers.ts
namespace MyStaticMembers {
class MyStaticClass {
static property: number = 10;
static myMethod() {...}
}
export function Property(): number {
return MyStaticClass.property;
}
export function Method(): void {
return MyStaticClass.myMethod();
}
}
Hence we shall consume it as below:
//app.ts
/// <reference path="MyStaticMembers.ts" />
console.log(MyStaticMembers.Property);
MyStaticMembers.Method();
This worked for me. If anyone has other better suggestions please let us all hear it !!! Thanks...
Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.
There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.
There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are
None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals
From the docs:
Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog
: modal-lg
and modal-sm
(as of 3.1).
Also the modal dialogue will scale itself on small screens (as of 3.1.1).
For completeness sake, on a Swedish keyboard it's CTRL + å .
Also, I guess logical, but worth mentioning CTRL + shift + å (for capital Å), selects everything inside the braces and goes to the matching one.
Or do a non-recursive checkout of /trunk, then just do a manual update on the 3 directories you need.
Using an absolute or relative string as the filename.
name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()
**Divide a list to lists of n size**
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
public final class PartitionUtil<T> extends AbstractList<List<T>> {
private final List<T> list;
private final int chunkSize;
private PartitionUtil(List<T> list, int chunkSize) {
this.list = new ArrayList<>(list);
this.chunkSize = chunkSize;
}
public static <T> PartitionUtil<T> ofSize(List<T> list, int chunkSize) {
return new PartitionUtil<>(list, chunkSize);
}
@Override
public List<T> get(int index) {
int start = index * chunkSize;
int end = Math.min(start + chunkSize, list.size());
if (start > end) {
throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
}
return new ArrayList<>(list.subList(start, end));
}
@Override
public int size() {
return (int) Math.ceil((double) list.size() / (double) chunkSize);
}
}
Function call :
List<List<String>> containerNumChunks = PartitionUtil.ofSize(list, 999)
more details: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/
cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
alert('successful : ' + html);
$("#result").html("Successful");
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
pandas.Series.astype
You can do something like this :
weather["Temp"] = weather.Temp.astype(float)
You can also use pd.to_numeric
that will convert the column from object to float
Example :
s = pd.Series(['apple', '1.0', '2', -3])
print(pd.to_numeric(s, errors='ignore'))
print("=========================")
print(pd.to_numeric(s, errors='coerce'))
Output:
0 apple
1 1.0
2 2
3 -3
=========================
dtype: object
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64
In your case you can do something like this:
weather["Temp"] = pd.to_numeric(weather.Temp, errors='coerce')
convert_objects
Example is as follows
>> pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can use this as follows:
weather["Temp"] = weather.Temp.convert_objects(convert_numeric=True)
NaN
... so be careful while using it.If you have ListView in any Parent panel (ListView dock fill), you can use simply method...
private void ListViewHeaderWidth() {
int HeaderWidth = (listViewInfo.Parent.Width - 2) / listViewInfo.Columns.Count;
foreach (ColumnHeader header in listViewInfo.Columns)
{
header.Width = HeaderWidth;
}
}
At the moment of writing (end of July 2017) with the Blue Ocean plugin you can check the syntax of a declarative pipeline directly in the visual pipeline editor. The editor, works from the Blue Ocean UI when you click "configure" only for github projects (this is a known issue and they are working to make it work also on git etc).
But, as explained in this question you can open the editor browsing to:
[Jenkins URL]/blue/organizations/jenkins/pipeline-editor/
Then click in the middle of the page, and press Ctrl+S
, this will open a textarea where you can paste a pipeline declarative script. When you click on Update, if there is a syntax error, the editor will let you know where the syntax error is. Like in this screenshot:
If there is no syntax error, the textarea will close and the page will visualize your pipeline. Don't worry it won't save anything (if it's a github project it would commit the Jenkinsfile change).
I'm new to Jenkins and this is quite helpful, without this I had to commit a Jenkinsfile many times, till it works (very annoying!). Hope this helps. Cheers.
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX
and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
I recommend using a autocomplete environment(pyscripter or scipy for example). If you lookup example code, make sure they use the same version of Python(if they don't make sure you change the code).
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};
This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT
query and you will get the order of columns, as paxdiablo already said:
SELECT name, colnew, qty, rate FROM{tablename}
and in my opinion, your column name to get the value from the cursor:
private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));
so if the index changes your application will not face any problems.
This is the safe way in the sense that otherwise, if you are using CREATE temptable
or RENAME table
or CREATE
, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.
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.
//sample01_x000D_
(function(_){_[0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this[1].bind(this))},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this[2].bind(this))},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
])_x000D_
_x000D_
//sample02_x000D_
(function(_){_.next=function(){_[++_.i].apply(_,arguments)},_[_.i=0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this.next)},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this.next)},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);_x000D_
_x000D_
//sample03_x000D_
(function(_){_.next=function(){return _[++_.i].bind(_)},_[_.i=0]()})([_x000D_
function(){$('#art1').animate({'width':'10px'},100,this.next())},_x000D_
function(){$('#art2').animate({'width':'10px'},100,this.next())},_x000D_
function(){$('#art3').animate({'width':'10px'},100)},_x000D_
]);
_x000D_
M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.
[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.
<a href="#"><i class="fab fa-facebook-square"></i></a>
<a href="#"><i class="fab fa-twitter-square"></i></a>
<a href="#"><i class="fas fa-basketball-ball"></i></a>
<a href="#"><i class="fab fa-google-plus-square"></i></a>
All you have to do is wrap your font-awesome icon link in your HTML
with an anchor tag.
Following this format:
<a href="Link here"> <font-awesome icon code> </a>
Personally, any time I'd need to go out of my way to use std::for_each
(write special-purpose functors / complicated boost::lambda
s), I find BOOST_FOREACH
and C++0x's range-based for clearer:
BOOST_FOREACH(Monster* m, monsters) {
if (m->has_plan())
m->act();
}
vs
std::for_each(monsters.begin(), monsters.end(),
if_then(bind(&Monster::has_plan, _1),
bind(&Monster::act, _1)));
I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:
If you have in your java source
package mypackage;
and your class is hello.java with
public class hello {
and in that hello.java you have
public static void main(String[] args) {
Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then
java -cp . mypackage.hello
Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also
Thanks Stack overflow for a wealth of info.
The CSS properties "column-count", "column-gap", and "column-span" can do this in a way that keeps all the columns of the pseudo-table inside the same wrapper (HTML stays nice and neat).
The only caveats are that you can only define 1 column or all columns, and column-span doesn't yet work in Firefox, so some additional CSS is necessary to ensure it will displays correctly. https://www.w3schools.com/css/css3_multiple_columns.asp
.split-me {_x000D_
-webkit-column-count: 3;_x000D_
-webkit-column-gap: 0;_x000D_
-moz-column-count: 3;_x000D_
-moz-column-gap: 0;_x000D_
column-count: 3;_x000D_
column-gap: 0;_x000D_
}_x000D_
_x000D_
.cols {_x000D_
/* column-span is 1 by default */_x000D_
column-span: 1;_x000D_
}_x000D_
_x000D_
div.three-span {_x000D_
column-span: all !important;_x000D_
}_x000D_
_x000D_
/* alternate style for column-span in Firefox */_x000D_
@-moz-document url-prefix(){_x000D_
.three-span {_x000D_
position: absolute;_x000D_
left: 8px;_x000D_
right: 8px;_x000D_
top: auto;_x000D_
width: auto;_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
<p>The column width stays fully dynamic, just like flex-box, evenly scaling on resize.</p>_x000D_
_x000D_
<div class='split-me'>_x000D_
<div class='col-1 cols'>Text inside Column 1 div.</div>_x000D_
<div class='col-2 cols'>Text inside Column 2 div.</div>_x000D_
<div class='col-3 cols'>Text inside Column 3 div.</div>_x000D_
<div class='three-span'>Text div spanning 3 columns.</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
<style>_x000D_
/* Non-Essential Visual Styles */_x000D_
_x000D_
html * { font-size: 12pt; font-family: Arial; text-align: center; }_x000D_
.split-me>* { padding: 5px; } _x000D_
.cols { border: 2px dashed black; border-left: none; }_x000D_
.col-1 { background-color: #ddffff; border-left: 2px dashed black; }_x000D_
.col-2 { background-color: #ffddff; }_x000D_
.col-3 { background-color: #ffffdd; }_x000D_
.three-span {_x000D_
border: 2px dashed black; border-top: none;_x000D_
text-align: center; background-color: #ddffdd;_x000D_
}_x000D_
</style>
_x000D_
Try edit your isValidURL
function as follows:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
This should do the trick.
The CSS property touch-action may get you what you are looking for, though it may not work in all your target browsers.
html, body {
width: 100%; height: 100%;
overflow: hidden;
touch-action: none;
}
A ReactJS dumb component to render pagination. You can also use this Library:
https://www.npmjs.com/package/react-js-pagination
Some Examples are Here:
http://vayser.github.io/react-js-pagination/
OR
You can also Use this https://codepen.io/PiotrBerebecki/pen/pEYPbY
Here are some reference for you:
Primary & foreign key Constraint.
Primary Key: A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.
Foreign Key: A foreign key (sometimes called a referencing key) is a key used to link two tables together. Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key (it remains a primary key in the original table).
Index, on the other hand, is an attribute that you can apply on some columns so that the data retrieval done on those columns can be speed up.
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:
def gen():
return (something for something in get_some_stuff())
print gen()[:2] # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
The command is bundle update
(there is no "r" in the "bundle").
To check if bundler is installed do : gem list bundler
or even which bundle
and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler
.
Here's an example in VB.NET
Public Function ShowtheDialog(caption As String, text As String, selStr As String) As String
Dim prompt As New Form()
prompt.Width = 280
prompt.Height = 160
prompt.Text = caption
Dim textLabel As New Label() With { _
.Left = 16, _
.Top = 20, _
.Width = 240, _
.Text = text _
}
Dim textBox As New TextBox() With { _
.Left = 16, _
.Top = 40, _
.Width = 240, _
.TabIndex = 0, _
.TabStop = True _
}
Dim selLabel As New Label() With { _
.Left = 16, _
.Top = 66, _
.Width = 88, _
.Text = selStr _
}
Dim cmbx As New ComboBox() With { _
.Left = 112, _
.Top = 64, _
.Width = 144 _
}
cmbx.Items.Add("Dark Grey")
cmbx.Items.Add("Orange")
cmbx.Items.Add("None")
cmbx.SelectedIndex = 0
Dim confirmation As New Button() With { _
.Text = "In Ordnung!", _
.Left = 16, _
.Width = 80, _
.Top = 88, _
.TabIndex = 1, _
.TabStop = True _
}
AddHandler confirmation.Click, Sub(sender, e) prompt.Close()
prompt.Controls.Add(textLabel)
prompt.Controls.Add(textBox)
prompt.Controls.Add(selLabel)
prompt.Controls.Add(cmbx)
prompt.Controls.Add(confirmation)
prompt.AcceptButton = confirmation
prompt.StartPosition = FormStartPosition.CenterScreen
prompt.ShowDialog()
Return String.Format("{0};{1}", textBox.Text, cmbx.SelectedItem.ToString())
End Function
I also got the same exception:
I tried the following steps:
In Eclipse> Project > Clean. (The Exception remained)
I ran another project(The testng.xml ran successfully)
After running another project, I ran the project in which I was getting the Exception, and fortunately it worked for me, with no errors.
You're missing a GROUP BY clause:
SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.
If you are looking for an answer where you can redirect specific url/s to http then please update your htaccess like below
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
It worked for me :)
Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
How have I created a linkedlist like this. How does this work? This is all a linked list is. An item with a link to the next item in the list. As long as you keep a reference to the item at the beginning of the list, you can traverse the whole thing using each subsequent reference to the next value.
To append, all you need to do is find the end of the list, and make the next item the value you want appended, so if this has non-null next, you would have to call append on the next item until you find the end of the list.
this.next.Append(word);
Simplifying from pctroll's answer, similarly based on this blog post.
# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote
If you're doing computations:
isCancelled()
periodically.If you're doing a HTTP request:
HttpGet
or HttpPost
somewhere (eg. a public field).cancel
, call request.abort()
. This will cause IOException
be thrown inside your doInBackground
.In my case, I had a connector class which I used in various AsyncTasks. To keep it simple, I added a new abortAllRequests
method to that class and called this method directly after calling cancel
.
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
Unfortunately, crontabs have a very limited environment variables scope, thus you need to export them every time the corntab runs.
An easy approach would be the following example, suppose you've your env vars in a file called env, then:
* * * * * . ./env && /path/to_your/command
this part . ./env
will export them and then they're used within the same scope of your command
The first thing you should do is to determine whether you want to keep the local changes before you delete the commit message.
Use git log
to show current commit messages, then find the commit_id
before the commit that you want to delete, not the commit you want to delete.
git reset --soft commit_id
git reset --hard commit_id
That's the difference of soft and hard
I had the same issue, I cleaned and rebuilt the project and it worked.
Actually NULL filter is not being ignored. Thing is this is how joining two tables work.
I will try to walk down with the steps performed by database server to make it understand.
For example when you execute the query which you said is ignoring the NULL condition.
SELECT
*
FROM
shipments s
LEFT OUTER JOIN returns r
ON s.id = r.id
AND r.id is null
WHERE
s.day >= CURDATE() - INTERVAL 10 DAY
1st thing happened is all the rows from table SHIPMENTS get selected
on next step database server will start selecting one by one record from 2nd(RETURNS) table.
on third step the record from RETURNS table will be qualified against the join conditions you have provided in the query which in this case is (s.id = r.id and r.id is NULL)
note that this qualification applied on third step only decides if server should accept or reject the current record of RETURNS table to append with the selected row of SHIPMENT table. It can in no way effect the selection of record from SHIPMENT table.
And once server is done with joining two tables which contains all the rows of SHIPMENT table and selected rows of RETURNS table it applies the where clause on the intermediate result. so when you put (r.id is NULL) condition in where clause than all the records from the intermediate result with r.id = null gets filtered out.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
This page on MSDN lists standard DateTime format strings, uncluding strings using the 'Z'.
Update: you will need to make sure that the rest of the date string follows the correct pattern as well (you have not supplied an example of what you send it, so it's hard to say whether you did or not). For the UTC format to work it should look like this:
// yyyy'-'MM'-'dd HH':'mm':'ss'Z'
DateTime utcTime = DateTime.Parse("2009-05-07 08:17:25Z");
The performance is almost a 100% identical. You can check this out by opening the class in Reflector.net
This is the This indexer:
public TValue this[TKey key]
{
get
{
int index = this.FindEntry(key);
if (index >= 0)
{
return this.entries[index].value;
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
this.Insert(key, value, false);
}
}
And this is the Add method:
public void Add(TKey key, TValue value)
{
this.Insert(key, value, true);
}
I won't post the entire Insert method as it's rather long, however the method declaration is this:
private void Insert(TKey key, TValue value, bool add)
And further down in the function, this happens:
if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
if (add)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
Which checks if the key already exists, and if it does and the parameter add is true, it throws the exception.
So for all purposes and intents the performance is the same.
Like a few other mentions, it's all about whether you need the check, for attempts at adding the same key twice.
Sorry for the lengthy post, I hope it's okay.
First checkout to the branch which you want to rename:
git branch -m old_branch new_branch
git push -u origin new_branch
To remove an old branch from remote
:
git push origin :old_branch
You can add a class to each of your .row
divs to add some space in between them like so:
.spacer {
margin-top: 40px; /* define margin as you see fit */
}
You can then use it like so:
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
<div class="row spacer">
<div class="span4">...</div>
<div class="span4">...</div>
<div class="span4">...</div>
</div>
I found this link useful.
Here is the paragraph highlighting some of the pros/cons of each approach.
The most commonly seen design is to imitate the many Boolean-like flags that Oracle's data dictionary views use, selecting 'Y' for true and 'N' for false. However, to interact correctly with host environments, such as JDBC, OCCI, and other programming environments, it's better to select 0 for false and 1 for true so it can work correctly with the getBoolean and setBoolean functions.
Basically they advocate method number 2, for efficiency's sake, using
getBoolean()
etc.) with a check constraintTheir example:
create table tbool (bool char check (bool in (0,1)); insert into tbool values(0); insert into tbool values(1);`
$(document).ready(function() {_x000D_
var table = $('#example').DataTable( {_x000D_
scrollY: "400px",_x000D_
scrollX: true,_x000D_
scrollCollapse: true,_x000D_
paging: true,_x000D_
fixedColumns: {_x000D_
leftColumns: 3_x000D_
}_x000D_
} );_x000D_
} );
_x000D_
<head>_x000D_
<title>table</title>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">_x000D_
<link rel="stylesheet" href="https://cdn.datatables.net/fixedcolumns/3.2.4/css/fixedColumns.dataTables.min.css">_x000D_
<script type="text/javascript" src="http://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>_x000D_
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>_x000D_
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>_x000D_
<script type="text/javascript" src="https://cdn.datatables.net/fixedcolumns/3.2.4/js/dataTables.fixedColumns.min.js"></script>_x000D_
_x000D_
_x000D_
<style>_x000D_
th, td { white-space: nowrap; }_x000D_
div.dataTables_wrapper {_x000D_
width: 900px;_x000D_
margin: 0 auto;_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>
_x000D_
<table id="example" class="stripe row-border order-column" style="width:100%">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>First name</th>_x000D_
<th>Last name</th>_x000D_
<th>Position</th>_x000D_
<th>Office</th>_x000D_
<th>Age</th>_x000D_
<th>Start date</th>_x000D_
<th>Salary</th>_x000D_
<th>Extn.</th>_x000D_
<th>E-mail</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Tiger</td>_x000D_
<td>Nixon</td>_x000D_
<td>System Architect</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>61</td>_x000D_
<td>2011/04/25</td>_x000D_
<td>$320,800</td>_x000D_
<td>5421</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Garrett</td>_x000D_
<td>Winters</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>63</td>_x000D_
<td>2011/07/25</td>_x000D_
<td>$170,750</td>_x000D_
<td>8422</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Ashton</td>_x000D_
<td>Cox</td>_x000D_
<td>Junior Technical Author</td>_x000D_
<td>San Francisco</td>_x000D_
<td>66</td>_x000D_
<td>2009/01/12</td>_x000D_
<td>$86,000</td>_x000D_
<td>1562</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cedric</td>_x000D_
<td>Kelly</td>_x000D_
<td>Senior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>22</td>_x000D_
<td>2012/03/29</td>_x000D_
<td>$433,060</td>_x000D_
<td>6224</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Airi</td>_x000D_
<td>Satou</td>_x000D_
<td>Accountant</td>_x000D_
<td>Tokyo</td>_x000D_
<td>33</td>_x000D_
<td>2008/11/28</td>_x000D_
<td>$162,700</td>_x000D_
<td>5407</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Brielle</td>_x000D_
<td>Williamson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>2012/12/02</td>_x000D_
<td>$372,000</td>_x000D_
<td>4804</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Herrod</td>_x000D_
<td>Chandler</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>San Francisco</td>_x000D_
<td>59</td>_x000D_
<td>2012/08/06</td>_x000D_
<td>$137,500</td>_x000D_
<td>9608</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Rhona</td>_x000D_
<td>Davidson</td>_x000D_
<td>Integration Specialist</td>_x000D_
<td>Tokyo</td>_x000D_
<td>55</td>_x000D_
<td>2010/10/14</td>_x000D_
<td>$327,900</td>_x000D_
<td>6200</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Colleen</td>_x000D_
<td>Hurst</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>39</td>_x000D_
<td>2009/09/15</td>_x000D_
<td>$205,500</td>_x000D_
<td>2360</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sonya</td>_x000D_
<td>Frost</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>23</td>_x000D_
<td>2008/12/13</td>_x000D_
<td>$103,600</td>_x000D_
<td>1667</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jena</td>_x000D_
<td>Gaines</td>_x000D_
<td>Office Manager</td>_x000D_
<td>London</td>_x000D_
<td>30</td>_x000D_
<td>2008/12/19</td>_x000D_
<td>$90,560</td>_x000D_
<td>3814</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Sakura</td>_x000D_
<td>Yamamoto</td>_x000D_
<td>Support Engineer</td>_x000D_
<td>Tokyo</td>_x000D_
<td>37</td>_x000D_
<td>2009/08/19</td>_x000D_
<td>$139,575</td>_x000D_
<td>9383</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Thor</td>_x000D_
<td>Walton</td>_x000D_
<td>Developer</td>_x000D_
<td>New York</td>_x000D_
<td>61</td>_x000D_
<td>2013/08/11</td>_x000D_
<td>$98,540</td>_x000D_
<td>8327</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Finn</td>_x000D_
<td>Camacho</td>_x000D_
<td>Support Engineer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>47</td>_x000D_
<td>2009/07/07</td>_x000D_
<td>$87,500</td>_x000D_
<td>2927</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Serge</td>_x000D_
<td>Baldwin</td>_x000D_
<td>Data Coordinator</td>_x000D_
<td>Singapore</td>_x000D_
<td>64</td>_x000D_
<td>2012/04/09</td>_x000D_
<td>$138,575</td>_x000D_
<td>8352</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Zenaida</td>_x000D_
<td>Frank</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>New York</td>_x000D_
<td>63</td>_x000D_
<td>2010/01/04</td>_x000D_
<td>$125,250</td>_x000D_
<td>7439</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Zorita</td>_x000D_
<td>Serrano</td>_x000D_
<td>Software Engineer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>56</td>_x000D_
<td>2012/06/01</td>_x000D_
<td>$115,000</td>_x000D_
<td>4389</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jennifer</td>_x000D_
<td>Acosta</td>_x000D_
<td>Junior Javascript Developer</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>43</td>_x000D_
<td>2013/02/01</td>_x000D_
<td>$75,650</td>_x000D_
<td>3431</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cara</td>_x000D_
<td>Stevens</td>_x000D_
<td>Sales Assistant</td>_x000D_
<td>New York</td>_x000D_
<td>46</td>_x000D_
<td>2011/12/06</td>_x000D_
<td>$145,600</td>_x000D_
<td>3990</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Hermione</td>_x000D_
<td>Butler</td>_x000D_
<td>Regional Director</td>_x000D_
<td>London</td>_x000D_
<td>47</td>_x000D_
<td>2011/03/21</td>_x000D_
<td>$356,250</td>_x000D_
<td>1016</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Lael</td>_x000D_
<td>Greer</td>_x000D_
<td>Systems Administrator</td>_x000D_
<td>London</td>_x000D_
<td>21</td>_x000D_
<td>2009/02/27</td>_x000D_
<td>$103,500</td>_x000D_
<td>6733</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Jonas</td>_x000D_
<td>Alexander</td>_x000D_
<td>Developer</td>_x000D_
<td>San Francisco</td>_x000D_
<td>30</td>_x000D_
<td>2010/07/14</td>_x000D_
<td>$86,500</td>_x000D_
<td>8196</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Shad</td>_x000D_
<td>Decker</td>_x000D_
<td>Regional Director</td>_x000D_
<td>Edinburgh</td>_x000D_
<td>51</td>_x000D_
<td>2008/11/13</td>_x000D_
<td>$183,000</td>_x000D_
<td>6373</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Michael</td>_x000D_
<td>Bruce</td>_x000D_
<td>Javascript Developer</td>_x000D_
<td>Singapore</td>_x000D_
<td>29</td>_x000D_
<td>2011/06/27</td>_x000D_
<td>$183,000</td>_x000D_
<td>5384</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Donna</td>_x000D_
<td>Snider</td>_x000D_
<td>Customer Support</td>_x000D_
<td>New York</td>_x000D_
<td>27</td>_x000D_
<td>2011/01/25</td>_x000D_
<td>$112,000</td>_x000D_
<td>4226</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This can be easily done with the help of datatables. People who are new to data tables, please refer to https://datatables.net/ .Its a plugin and offers a lot of features.In the the code given, header is fixed,first 3 columns are fixed and several other features are also there.
I do this like this:
try {
YourClass yourClass = new YourClass();
Method method = YourClass.class.getMethod("yourMethodName", ParameterOfThisMethod.class);
method.invoke(yourClass, parameter);
} catch (Exception e) {
e.printStackTrace();
}
This should work. But I have same problems on an Android phone.
<input type="number" /> <input type="tel" />
I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.
But I havn't found a solution to solve that problem, if you really need to use jquerymobile.
UPDATE: I found out, that if the form-tag is stored out of the
<div data-role="page">
The number keypad isn't shown. This must be a bug...
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.
In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.
There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:
url: 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',
to this line:
url: '/path/to/phpscript.php',
and then in the php script (if you have permission to use the file_get_contents() function):
<?php
header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
?>
Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.
Edit: If you want to cache the result in php, here's the php file you would use:
<?php
$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
$contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
file_put_contents($cacheName, $contents);
}
$xml = simplexml_load_file($cacheName);
header('Content-type: application/xml');
echo $xml;
?>
Caching code take from here.
If your $result
variable is a string json like, you must use json_decode
function to parse it as an object or array:
$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);
Array
(
[Cancelled] =>
[MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
[Queued] =>
[SMSError] => 2
[SMSIncomingMessages] =>
[Sent] =>
[SentDateTime] => /Date(-62135578800000-0500)/
)
Now you can work with $json
variable as an array:
echo $json['MessageID'];
echo $json['SMSError'];
// other stuff
References:
Also you will specify route on action for set route
[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
//gets all customer logic
}
[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer
}
[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
//gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
//gets customer by its username
}
The genaral form to declare a new array in java is as follows:
type arrayName[] = new type[numberOfElements];
Where type is a primitive type or Object. numberOfElements
is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).
Lets initialize an array to store the salaries of all employees in a small company of 5 people:
int salaries[] = new int[5];
The type of the array (in this case int
) applies to all values in the array. You can not mix types in one array.
Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:
int salaries[] = {50000, 75340, 110500, 98270, 39400};
Or to do it at a later point like this:
salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;
More visual example of array creation:
To learn more about Arrays, check out the guide.
directory
is neither an existing file nor directory. As it turns out, the real name is directory.1
as revealed by ls -la $HOME/Desktop/
.
The complete working command is
cp -R $HOME/directory.1/file.bundle /library/application\ support/directory/
with the -R
parameter for recursive copy (compulsory for copying directories).
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
You can get the bounding box of any element by calling getBoundingClientRect
var rect = document.getElementById("myElement").getBoundingClientRect();
That will return an object with left, top, width and height fields.
You can access your files via SSL like this:
https://s3.amazonaws.com/bucket_name/images/logo.gif
If you use a custom domain for your bucket, you can use S3 and CloudFront together with your own SSL certificate (or generate a free one via Amazon Certificate Manager): http://aws.amazon.com/cloudfront/custom-ssl-domains/
Question#1 - These are the only way to handle view clicks.
Question#2 -
Option#1/Option#4 - There's not much difference between option#1 and option#4. The only difference I see is in one case activity is implementing the OnClickListener, whereas, in the other case, there'd be an anonymous implementation.
Option#2 - In this method an anonymous class will be generated. This method is a bit cumborsome, as, you'd need to do it multiple times, if you have multiple buttons. For Anonymous classes, you have to be careful for handling memory leaks.
Option#3 - Though, this is a easy way. Usually, Programmers try not to use any method until they write it, and hence this method is not widely used. You'd see mostly people use Option#4. Because it is cleaner in term of code.
It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo
class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.
For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:
[C#]
string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();
foreach (var directory in parentDirectory)
{
// Notice I've created a DirectoryInfo variable.
DirectoryInfo dirInfo = new DirectoryInfo(directory);
// And likewise a name variable for storing the name.
// If this is not added, only the first directory will
// be captured in the loop; the rest won't.
string name = dirInfo.Name;
// Finally we add the directory name to our defined List.
directories.Add(name);
}
[VB.NET]
Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()
For Each directory In parentDirectory
' Notice I've created a DirectoryInfo variable.
Dim dirInfo As New DirectoryInfo(directory)
' And likewise a name variable for storing the name.
' If this is not added, only the first directory will
' be captured in the loop; the rest won't.
Dim name As String = dirInfo.Name
' Finally we add the directory name to our defined List.
directories.Add(name)
Next directory
You can get it using the :selected
selector, like this:
$("#my_select").change(function() {
var id = $(this).children(":selected").attr("id");
});
First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.
Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing
and concurrent.futures
libraries both wraps up most of the details for you.
The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures
, 4 lines with multiprocessing
.)
If you're using 2.6-2.7 or 3.0-3.1, futures
isn't built in, but you can install it from PyPI (pip install futures
).
Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map
), so let's do that first:
def try_my_operation(item):
try:
api.my_operation(item)
except:
print('error with item')
Putting it all together:
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)
If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper
from the itertools
recipes, which you can copy and paste into your code, or get from the more-itertools
project on PyPI):
def try_multiple_operations(items):
for item in items:
try:
api.my_operation(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group)
for group in grouper(5, items)]
concurrent.futures.wait(futures)
Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.
So, how do you use threads instead of processes? Just change ProcessPoolExecutor
to ThreadPoolExecutor
.
If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.
Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?
Yes. In fact, there are two different ways to do it.
First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.
Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.
If you don't know which is appropriate for your program, usually it's the first.
I have found a solution. This worked for me:
import numpy as np
import matplotlib.pyplot as plt
points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()
To do this with multiple images you need to run though an .each()
function. This works but I'm not sure how efficient it is.
$('img').hide();
$('img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
win32com.client
is a part of pywin32
So, download pywin32 from here
>>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
>>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
>>> c1set = frozenset(c1)
Flatten variant:
>>> [n for lst in c2 for n in lst if n in c1set]
[13, 32, 7, 13, 28, 1, 6]
Nested variant:
>>> [[n for n in lst if n in c1set] for lst in c2]
[[13, 32], [7, 13, 28], [1, 6]]
If you have date in DateTime
variable then its a DateTime
object and doesn't contain any format. Formatted date are expressed as string
when you call DateTime.ToString
method and provide format in it.
Lets say you have two DateTime
variable, you can use the compare method for comparision,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Code snippet taken from msdn.
It sounds like you're looking for applicationHost.config
, which is located in C:\Windows\System32\inetsrv\config
.
Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config
and web.config
.
There is a dedicated npm
package for it. css-scrollbar-side
For the record, the spring.jpa.hibernate.ddl-auto
property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto
.
The values create
, create-drop
, validate
, and update
basically influence how the schema tool management will manipulate the database schema at startup.
For example, the update
operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.
The update
operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.
Typically in test case scenarios, you'll likely use create-drop
so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.
In development, it's often common to see developers use update
to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.
In production, it's often highly recommended you use none
or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.
The array declaration should be:
Car[] garage = new Car[100];
You can also just assign directly:
garage[1] = new Car("Blue");
Use strpos()
:
if (strpos($string2, 'http') === 0) {
// It starts with 'http'
}
Remember the three equals signs (===
). It will not work properly if you only use two. This is because strpos()
will return false
if the needle cannot be found in the haystack.
Why to invent the wheel?
There is a very popular NPM package, that let you do things like that easy.
var recursive = require("recursive-readdir");
recursive("some/path", function (err, files) {
// `files` is an array of file paths
console.log(files);
});
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
If you're escaping for HTML, there are only three that I can think of that would be really necessary:
html.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
Depending on your use case, you might also need to do things like "
to "
. If the list got big enough, I'd just use an array:
var escaped = html;
var findReplace = [[/&/g, "&"], [/</g, "<"], [/>/g, ">"], [/"/g, """]]
for(var item in findReplace)
escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);
encodeURIComponent()
will only escape it for URLs, not for HTML.
Yes, always will be slower create an object by reflection because the JVM cannot optimize the code on compilation time. See the Sun/Java Reflection tutorials for more details.
See this simple test:
public class TestSpeed {
public static void main(String[] args) {
long startTime = System.nanoTime();
Object instance = new TestSpeed();
long endTime = System.nanoTime();
System.out.println(endTime - startTime + "ns");
startTime = System.nanoTime();
try {
Object reflectionInstance = Class.forName("TestSpeed").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
endTime = System.nanoTime();
System.out.println(endTime - startTime + "ns");
}
}
emplace_back
conforming implementation will forward arguments to the vector<Object>::value_type
constructor when added to the vector. I recall Visual Studio didn't support variadic templates, but with variadic templates will be supported in Visual Studio 2013 RC, so I guess a conforming signature will be added.
With emplace_back
, if you forward the arguments directly to vector<Object>::value_type
constructor, you don't need a type to be movable or copyable for emplace_back
function, strictly speaking. In the vector<NonCopyableNonMovableObject>
case, this is not useful, since vector<Object>::value_type
needs a copyable or movable type to grow.
But note that this could be useful for std::map<Key, NonCopyableNonMovableObject>
, since once you allocate an entry in the map, it doesn't need to be moved or copied ever anymore, unlike with vector
, meaning that you can use std::map
effectively with a mapped type that is neither copyable nor movable.
On the Mac version 8.0.1 has this setting here:
PhpStorm > Preferences > Editor (this is in the second section on the left - i.e. IDE Settings NOT Project Settings) > Appearance > Show line numbers
add below code to activity_main.xml file:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="@string/button" />
and just add the below method to the MainActivity.java file:
public void buttonClick(View view){
Intent i = new Intent(getApplicationContext()SendPhotos.class);
startActivity(i);
}
If you have downloaded Github Desktop Client 1.0.9
then the path for git.exe
will be
C:\Users\Username\AppData\Local\GitHubDesktop\app-1.0.9\resources\app\git\cmd\git.exe
This will probably get downvoted to oblivion, but here is how I used 1.1.5's ternary operators to switch classes depending on whether a row in a table is the first, middle or last -- except if there is only one row in the table:
<span class="attribute-row" ng-class="(restaurant.Attributes.length === 1) || ($first ? 'attribute-first-row': false || $middle ? 'attribute-middle-row': false || $last ? 'attribute-last-row': false)">
</span>
http://www.program-transformation.org/Transform/VisualBasicDecompilers
This link provides a lot of resources for VB6 Decompiling, but it seems like it will depend greatly on what you DO have (do you still have the pre-link Object code [EDIT: er... p-code I mean], or just the EXE?) Either way, it looks like there's something, take a look in there.
Using
return RedirectPermanent(myUrl)
worked for me
MariaDB has lifted this starting from 10.3.x (both for DELETE
and UPDATE
):
UPDATE - Statements With the Same Source and Target
From MariaDB 10.3.2, UPDATE statements may have the same source and target.
Until MariaDB 10.3.1, the following UPDATE statement would not work:
UPDATE t1 SET c1=c1+1 WHERE c2=(SELECT MAX(c2) FROM t1); ERROR 1093 (HY000): Table 't1' is specified twice, both as a target for 'UPDATE' and as a separate source for data
From MariaDB 10.3.2, the statement executes successfully:
UPDATE t1 SET c1=c1+1 WHERE c2=(SELECT MAX(c2) FROM t1);
DELETE - Same Source and Target Table
Until MariaDB 10.3.1, deleting from a table with the same source and target was not possible. From MariaDB 10.3.1, this is now possible. For example:
DELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE b.c2=0);
If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx
... then this might work:
.mdf
and .ldf
files in your project directoryJust like the &
and &&
operator, the double Operator is a "short-circuit" operator.
For example:
if(condition1 || condition2 || condition3)
If condition1 is true, condition 2 and 3 will NOT be checked.
if(condition1 | condition2 | condition3)
This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them.
There is one big caveat, NullReferences or similar problems. For example:
if(class != null && class.someVar < 20)
If class is null, the if-statement will stop after class != null
is false. If you only use &, it will try to check class.someVar
and you get a nice NullReferenceException
. With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind.
No one ever uses the single &
or |
operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The &
operator does "run these 3 functions, and if one of them returns false, execute the else block", while the |
does "only run the else block if none return false" - can be useful, but as said, often it's a design smell.
There is a Second use of the |
and &
operator though: Bitwise Operations.
UIColor's RGB components are scaled between 0 and 1, not up to 255.
Try
categoryTitle.textColor = [UIColor colorWithRed:(188/255.f) green:... blue:... alpha:1.0];
In Swift:
categoryTitle.textColor = UIColor(red: 188/255.0, green: ..., blue: ..., alpha: 1)
There are two ways to achieve what you want. Unfortunately, neither can be done using a view.
You can either create a table valued user defined function that takes the parameter you want and returns a query result
Or you can do pretty much the same thing but create a stored procedure instead of a user defined function.
For example:
the stored procedure would look like
CREATE PROCEDURE s_emp
(
@enoNumber INT
)
AS
SELECT
*
FROM
emp
WHERE
emp_id=@enoNumber
Or the user defined function would look like
CREATE FUNCTION u_emp
(
@enoNumber INT
)
RETURNS TABLE
AS
RETURN
(
SELECT
*
FROM
emp
WHERE
emp_id=@enoNumber
)
You can export any SQL query into JSON directly from PHPMyAdmin
You Create Custom ListView Which is non Scrollable
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
In Your Layout Resources File
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!-- com.Example Changed with your Package name -->
<com.Example.NonScrollListView
android:id="@+id/lv_nonscroll_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.Example.NonScrollListView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/lv_nonscroll_list" >
<!-- Your another layout in scroll view -->
</RelativeLayout>
</RelativeLayout>
In Java File
Create a object of your customListview instead of ListView like : NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_nonscroll_list);
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case RESET_STORE: {
state = initialState
}
break
}
return state
}
You can also fire an action which is handled by all or some reducers, that you want to reset to initial store. One action can trigger a reset to your whole state, or just a piece of it that seems fit to you. I believe this is the simplest and most controllable way of doing this.
The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.
Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.
It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.
For my case the problem was in fact that i broke machine.config and looks like VS couldn't have a connection I've added the following lines to my machine.config
<!--
<system.net>
<defaultProxy>
<proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
</defaultProxy>
</system.net>
<!--
-->
After replacing the previous section to:
<!--
<system.net>
<defaultProxy>
<proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
</defaultProxy>
</system.net>
-->
VS started to work.
Runscope is a cloud based service that can monitor Web APIs using a set of tests. Tests can be , scheduled and/or run via parameterized web hooks. Tests can also be executed from data centers around the world to ensure response times are acceptable to global client base.
The free tier of Runscope supports up to 10K requests per month.
Disclaimer: I am a developer advocate for Runscope.
A pre-commit hook is something that runs on the server, so this probably has nothing to do with your local setup. It could be that you changed something in a settings panel on myversioncontrol.com that is implemented using a pre-commit hook or the myversioncontrol people made an error and added a non-functioning hook.
Fairly new to using PowerShell, think I might be able to help. Could you try this?
I believe you're not getting the correct parameters to your script block:
param([string]$one, [string]$two)
$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {Get-LocalUsers -parentNodeXML $args[0] -migratorUser $args[1] } -ArgumentList $xmlPRE, $migratorCreds
To deserialize the response need to use HashMap
:
String resp = ...//String output from your source
Gson gson = new GsonBuilder().create();
gson.fromJson(resp,TheResponse.class);
class TheResponse{
HashMap<String,Song> songs;
}
class Song{
String id;
String pos;
}
<script>
$(document).ready(function(){
$('#colorselector').on('change', function() {
if ( this.value == 'red')
{
$("#divid").show();
}
else
{
$("#divid").hide();
}
});
});
</script>
Do like this for every value Also change the values... as per your parameters
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
This work with almsost all shell.
ncore=0
while read line ;do
[ "$line" ] && [ -z "${line%processor*}" ] && ncore=$((ncore+1))
done </proc/cpuinfo
echo $ncore
4
In order to stay compatible with shell, dash, busybox and others, I've used ncore=$((ncore+1))
instead of ((ncore++))
.
ncore=0
while read -a line ;do
[ "$line" = "processor" ] && ((ncore++))
done </proc/cpuinfo
echo $ncore
4
How do I select multiple columns by labels in pandas?
Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:
loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
A B C E G H I
0 -1.666330 0.321260 -1.768185 -0.034774 0.023294 0.533451 -0.241990
1 0.911498 3.408758 0.419618 -0.462590 0.739092 1.103940 0.116119
2 1.243001 -0.867370 1.058194 0.314196 0.887469 0.471137 -1.361059
3 -0.525165 0.676371 0.325831 -1.152202 0.606079 1.002880 2.032663
4 0.706609 -0.424726 0.308808 1.994626 0.626522 -0.033057 1.725315
5 0.879802 -1.961398 0.131694 -0.931951 -0.242822 -1.056038 0.550346
6 0.199072 0.969283 0.347008 -2.611489 0.282920 -0.334618 0.243583
7 1.234059 1.000687 0.863572 0.412544 0.569687 -0.684413 -0.357968
8 -0.299185 0.566009 -0.859453 -0.564557 -0.562524 0.233489 -0.039145
9 0.937637 -2.171174 -1.940916 -1.553634 0.619965 -0.664284 -0.151388
Note that the +1
is added because when using iloc
the rightmost index is exclusive.
filter
is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.
The "location-based" solution with loc
is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.
Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.
I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.
This works well for AIX. I am searching for lines containing JOINED<\t>ACTIVE
voradmin cluster status | grep JOINED$'\t'ACTIVE
vorudb201 1 MEMBER(g) JOINED ACTIVE
*vorucaf01 2 SECONDARY JOINED ACTIVE
You can use following code
DirectoryInfo di = Directory.CreateDirectory(path);
Here is an actual Java implementation based on the Groovy answer posted earlier. (I know there are already Groovy and Kotlin implementations posted, but for someone like me who's only done Java, it's a real hassle to figure out how to convert between other languages and Java).
(Results match with other people's graphs)
Algorithm implementation
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
public class SignalDetector {
public HashMap<String, List> analyzeDataForSignals(List<Double> data, int lag, Double threshold, Double influence) {
// init stats instance
SummaryStatistics stats = new SummaryStatistics();
// the results (peaks, 1 or -1) of our algorithm
List<Integer> signals = new ArrayList<Integer>(Collections.nCopies(data.size(), 0));
// filter out the signals (peaks) from our original list (using influence arg)
List<Double> filteredData = new ArrayList<Double>(data);
// the current average of the rolling window
List<Double> avgFilter = new ArrayList<Double>(Collections.nCopies(data.size(), 0.0d));
// the current standard deviation of the rolling window
List<Double> stdFilter = new ArrayList<Double>(Collections.nCopies(data.size(), 0.0d));
// init avgFilter and stdFilter
for (int i = 0; i < lag; i++) {
stats.addValue(data.get(i));
}
avgFilter.set(lag - 1, stats.getMean());
stdFilter.set(lag - 1, Math.sqrt(stats.getPopulationVariance())); // getStandardDeviation() uses sample variance
stats.clear();
// loop input starting at end of rolling window
for (int i = lag; i < data.size(); i++) {
// if the distance between the current value and average is enough standard deviations (threshold) away
if (Math.abs((data.get(i) - avgFilter.get(i - 1))) > threshold * stdFilter.get(i - 1)) {
// this is a signal (i.e. peak), determine if it is a positive or negative signal
if (data.get(i) > avgFilter.get(i - 1)) {
signals.set(i, 1);
} else {
signals.set(i, -1);
}
// filter this signal out using influence
filteredData.set(i, (influence * data.get(i)) + ((1 - influence) * filteredData.get(i - 1)));
} else {
// ensure this signal remains a zero
signals.set(i, 0);
// ensure this value is not filtered
filteredData.set(i, data.get(i));
}
// update rolling average and deviation
for (int j = i - lag; j < i; j++) {
stats.addValue(filteredData.get(j));
}
avgFilter.set(i, stats.getMean());
stdFilter.set(i, Math.sqrt(stats.getPopulationVariance()));
stats.clear();
}
HashMap<String, List> returnMap = new HashMap<String, List>();
returnMap.put("signals", signals);
returnMap.put("filteredData", filteredData);
returnMap.put("avgFilter", avgFilter);
returnMap.put("stdFilter", stdFilter);
return returnMap;
} // end
}
Main method
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
DecimalFormat df = new DecimalFormat("#0.000");
ArrayList<Double> data = new ArrayList<Double>(Arrays.asList(1d, 1d, 1.1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 0.9d, 1d,
1.1d, 1d, 1d, 0.9d, 1d, 1d, 1.1d, 1d, 1d, 1d, 1d, 1.1d, 0.9d, 1d, 1.1d, 1d, 1d, 0.9d, 1d, 1.1d, 1d, 1d,
1.1d, 1d, 0.8d, 0.9d, 1d, 1.2d, 0.9d, 1d, 1d, 1.1d, 1.2d, 1d, 1.5d, 1d, 3d, 2d, 5d, 3d, 2d, 1d, 1d, 1d,
0.9d, 1d, 1d, 3d, 2.6d, 4d, 3d, 3.2d, 2d, 1d, 1d, 0.8d, 4d, 4d, 2d, 2.5d, 1d, 1d, 1d));
SignalDetector signalDetector = new SignalDetector();
int lag = 30;
double threshold = 5;
double influence = 0;
HashMap<String, List> resultsMap = signalDetector.analyzeDataForSignals(data, lag, threshold, influence);
// print algorithm params
System.out.println("lag: " + lag + "\t\tthreshold: " + threshold + "\t\tinfluence: " + influence);
System.out.println("Data size: " + data.size());
System.out.println("Signals size: " + resultsMap.get("signals").size());
// print data
System.out.print("Data:\t\t");
for (double d : data) {
System.out.print(df.format(d) + "\t");
}
System.out.println();
// print signals
System.out.print("Signals:\t");
List<Integer> signalsList = resultsMap.get("signals");
for (int i : signalsList) {
System.out.print(df.format(i) + "\t");
}
System.out.println();
// print filtered data
System.out.print("Filtered Data:\t");
List<Double> filteredDataList = resultsMap.get("filteredData");
for (double d : filteredDataList) {
System.out.print(df.format(d) + "\t");
}
System.out.println();
// print running average
System.out.print("Avg Filter:\t");
List<Double> avgFilterList = resultsMap.get("avgFilter");
for (double d : avgFilterList) {
System.out.print(df.format(d) + "\t");
}
System.out.println();
// print running std
System.out.print("Std filter:\t");
List<Double> stdFilterList = resultsMap.get("stdFilter");
for (double d : stdFilterList) {
System.out.print(df.format(d) + "\t");
}
System.out.println();
System.out.println();
for (int i = 0; i < signalsList.size(); i++) {
if (signalsList.get(i) != 0) {
System.out.println("Point " + i + " gave signal " + signalsList.get(i));
}
}
}
}
Results
lag: 30 threshold: 5.0 influence: 0.0
Data size: 74
Signals size: 74
Data: 1.000 1.000 1.100 1.000 0.900 1.000 1.000 1.100 1.000 0.900 1.000 1.100 1.000 1.000 0.900 1.000 1.000 1.100 1.000 1.000 1.000 1.000 1.100 0.900 1.000 1.100 1.000 1.000 0.900 1.000 1.100 1.000 1.000 1.100 1.000 0.800 0.900 1.000 1.200 0.900 1.000 1.000 1.100 1.200 1.000 1.500 1.000 3.000 2.000 5.000 3.000 2.000 1.000 1.000 1.000 0.900 1.000 1.000 3.000 2.600 4.000 3.000 3.200 2.000 1.000 1.000 0.800 4.000 4.000 2.000 2.500 1.000 1.000 1.000
Signals: 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 0.000 1.000 1.000 1.000 1.000 1.000 0.000 0.000 0.000 0.000 0.000 0.000 1.000 1.000 1.000 1.000 1.000 1.000 0.000 0.000 0.000 1.000 1.000 1.000 1.000 0.000 0.000 0.000
Filtered Data: 1.000 1.000 1.100 1.000 0.900 1.000 1.000 1.100 1.000 0.900 1.000 1.100 1.000 1.000 0.900 1.000 1.000 1.100 1.000 1.000 1.000 1.000 1.100 0.900 1.000 1.100 1.000 1.000 0.900 1.000 1.100 1.000 1.000 1.100 1.000 0.800 0.900 1.000 1.200 0.900 1.000 1.000 1.100 1.200 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 0.900 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 1.000 0.800 0.800 0.800 0.800 0.800 1.000 1.000 1.000
Avg Filter: 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 1.003 1.003 1.007 1.007 1.003 1.007 1.010 1.003 1.000 0.997 1.003 1.003 1.003 1.000 1.003 1.010 1.013 1.013 1.013 1.010 1.010 1.010 1.010 1.010 1.007 1.010 1.010 1.003 1.003 1.003 1.007 1.007 1.003 1.003 1.003 1.000 1.000 1.007 1.003 0.997 0.983 0.980 0.973 0.973 0.970
Std filter: 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.060 0.060 0.063 0.063 0.060 0.063 0.060 0.071 0.073 0.071 0.080 0.080 0.080 0.077 0.080 0.087 0.085 0.085 0.085 0.083 0.083 0.083 0.083 0.083 0.081 0.079 0.079 0.080 0.080 0.080 0.077 0.077 0.075 0.075 0.075 0.073 0.073 0.063 0.071 0.080 0.078 0.083 0.089 0.089 0.086
Point 45 gave signal 1
Point 47 gave signal 1
Point 48 gave signal 1
Point 49 gave signal 1
Point 50 gave signal 1
Point 51 gave signal 1
Point 58 gave signal 1
Point 59 gave signal 1
Point 60 gave signal 1
Point 61 gave signal 1
Point 62 gave signal 1
Point 63 gave signal 1
Point 67 gave signal 1
Point 68 gave signal 1
Point 69 gave signal 1
Point 70 gave signal 1
I use java 1.8 with com.fasterxml.jackson.databind.ObjectMapper
ObjectMapper mapper = new ObjectMapper();
Integer value = mapper.readValue(new URL("your url here"), Integer.class);
Integer.class can be also a complex type. Just for example used.
Any easy way to cover ALL file inputs is to just style your input[type=button] and drop this in globally to turn file inputs into buttons:
$(document).ready(function() {
$("input[type=file]").each(function () {
var thisInput$ = $(this);
var newElement = $("<input type='button' value='Choose File' />");
newElement.click(function() {
thisInput$.click();
});
thisInput$.after(newElement);
thisInput$.hide();
});
});
Here's some sample button CSS that I got from http://cssdeck.com/labs/beautiful-flat-buttons:
input[type=button] {
position: relative;
vertical-align: top;
width: 100%;
height: 60px;
padding: 0;
font-size: 22px;
color:white;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
background: #454545;
border: 0;
border-bottom: 2px solid #2f2e2e;
cursor: pointer;
-webkit-box-shadow: inset 0 -2px #2f2e2e;
box-shadow: inset 0 -2px #2f2e2e;
}
input[type=button]:active {
top: 1px;
outline: none;
-webkit-box-shadow: none;
box-shadow: none;
}
Installing Drivers for Arduino in Windows 8 / 7.
( I tried it for Uno r3, but i believe it will work for all Arduino Boards )
Plugin your Arduino Board
Go to Control Panel ---> System and Security ---> System ---> On the left pane Device Manger
Expand Other Devices.
Under Other Devices you will notice a icon with a small yellow error graphic. (Unplug all your other devices attached to any Serial Port)
Right Click on that device ---> Update Driver Software
Select Browse my computer for Driver Software
Click on Browse ---> Browse for the folder of Arduino Environment which you have downloaded from Arduino website. If not downloaded then http://arduino.cc/en/Main/Software
After Browsing mark include subfolder.
Click next ---> Your driver will be installed.
Collapse Other Devices ---> Expand Port ( its in device manager only under other devices )
You will see Arduino Written ---> Look for its COM PORT (close device manager)
Go to Arduino Environment ---> Tools ---> Serial Port ---> Select the COM PORT as mentioned in PORT in device manager. (If you are using any other Arduino Board instead of UNO then select the same in boards )
Upload your killer programmes and see them work . . .
I hope this helps. . .
Welcome
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Here is the solution I used for Report Server 2008 R2
It should work regardless of what the Report Server will output for use for in its "id" attribute of the table. I don't think you can always assume it will be "ctl31_fixedTable"
I used a mix of the suggestion above and some ways to dynamically load jquery libraries into a page from javascript file found here
On the server go to the directory: C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js
Copy the jquery library jquery-1.6.2.min.js into the directory
Create a backup copy of the file ReportingServices.js Edit the file. And append this to the bottom of it:
var jQueryScriptOutputted = false;
function initJQuery() {
//if the jQuery object isn't available
if (typeof(jQuery) == 'undefined') {
if (! jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;
//output the script
document.write("<scr" + "ipt type=\"text/javascript\" src=\"../js/jquery-1.6.2.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
} else {
$(function() {
// Bug-fix on Chrome and Safari etc (webkit)
if ($.browser.webkit) {
// Start timer to make sure overflow is set to visible
setInterval(function () {
var div = $('table[id*=_fixedTable] > tbody > tr:last > td:last > div')
div.css('overflow', 'visible');
}, 1000);
}
});
}
}
initJQuery();
I suggest the following:
import ast
def is_int(s):
return isinstance(ast.literal_eval(s), int)
From the docs:
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
I should note that this will raise a ValueError
exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:
from ast import literal_eval
from contextlib import suppress
def is_int(s):
with suppress(ValueError):
return isinstance(literal_eval(s), int)
return False
¯\_(?)_/¯
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
In short:
<textarea>
should be closed immediately on the same line where it started.
General Practice: this will add-up line-breaks and spaces used for indentation in the code.
<textarea id="sitelink" name="sitelink">
</textarea>
Correct Practice
<textarea id="sitelink" name="sitelink"></textarea>
Write your own:
template<class T>
bool checkElementIsInSet(const T& elem, const std::set<T>& container)
{
return container.find(elem) != container.end();
}
Your major problem is not the stuff to the right of the decimal, it is the stuff to the left. The two values in your type declaration are precision and scale.
From MSDN: "Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2."
If you specify (10, 4), that means you can only store 6 digits to the left of the decimal, or a max number of 999999.9999. Anything bigger than that will cause an overflow.
SELECT set_config('log_statement', 'all', true);
With a corresponding user right may use the query above after connect. This will affect logging until session ends.
Have you run through Vim's built-in tutorial? If not, drop to the command-line and type vimtutor
. It's a great way to learn the initial commands.
Vim has an incredible amount of flexibility and power and, if you're like most vim users, you'll learn a lot of new commands and forget old ones, then relearn them. The built-in help is good and worthy of periodic browsing to learn new stuff.
There are several good FAQs and cheatsheets for vim on the internet. I'd recommend searching for vim + faq
and vim + cheatsheet
. Cheat-Sheets.org#vim is a good source, as is Vim Tips wiki.
Adding you a quick example using git plugin GitSCM:
checkout([
$class: 'GitSCM',
branches: [[name: '*/master']],
doGenerateSubmoduleConfigurations: false,
extensions: [[$class: 'CleanCheckout']],
submoduleCfg: [],
userRemoteConfigs: [[credentialsId: '<gitCredentials>', url: '<gitRepoURL>']]
])
in your pipeline
stage('checkout'){
steps{
script{
checkout
}
}
}
The accepted answer doesn't handle the from X import Y case. This code handles it and the standard import case as well:
def importOrReload(module_name, *names):
import sys
if module_name in sys.modules:
reload(sys.modules[module_name])
else:
__import__(module_name, fromlist=names)
for name in names:
globals()[name] = getattr(sys.modules[module_name], name)
# use instead of: from dfly_parser import parseMessages
importOrReload("dfly_parser", "parseMessages")
In the reloading case, we reassign the top level names to the values stored in the newly reloaded module, which updates them.
You can also try:
document.getElementById('theID').value = 'new value';
to make it work in IE-9 use below .it works for me
JQuery need to include:
jQuery(function() {
jQuery.support.placeholder = false;
webkit_type = document.createElement('input');
if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':text, textarea, :password').focus(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) && ($(this).attr('placeholder') != '') && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if (($(this).attr('placeholder')) && ($(this).attr('placeholder').length > 0) && ($(this).attr('placeholder') != '') && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$(':text, textarea, :password').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
CSS Style need to include:
.hasPlaceholder {color: #aaa;}