If you are a linux user Update node to a later version by running
sudo apt update
sudo apt install build-essential checkinstall libssl-dev
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.35.1/install.sh | bash
nvm --version
nvm ls
nvm ls-remote
nvm install [version.number]
this should solve your problem
I faced the similar issue.
Deselect the check box ("In wizard deselect the checkbox stating "First row has columns names") and before running the wizard make sure you have opened your excel sheet.
Then run the wizard by deselecting the checkbox.
This resolved my issue.
Hashes can not be decrypted check this out.
If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).
But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php
For Blowfish by crypt()
function -
crypt('String', '$2a$07$twentytwocharactersalt$');
password_hash
will be introduced in PHP 5.5.
$options = [
'cost' => 7,
'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.
Use \overset{above}{main}
in math mode. In your case, \overset{a}{\#}
.
According to the api docs, doing:
dataFrame1.except(dataFrame2)
will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.
Turns out the problem was in the permission. I fix it with the following command
sudo chown -R $USER /var/www
Please make sure with the $USER
variable. I tested and worked on Ubuntu Distro
If using a StackTraceElement, use:
String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
System.out.println(simpleClassName);
name()
is a "built-in" method of enum
. It is final and you cannot change its implementation. It returns the name of enum constant as it is written, e.g. in upper case, without spaces etc.
Compare MOBILE_PHONE_NUMBER
and Mobile phone number
. Which version is more readable? I believe the second one. This is the difference: name()
always returns MOBILE_PHONE_NUMBER
, toString()
may be overriden to return Mobile phone number
.
Arbitrarily choosing to keep the minimum PIC_ID. Also, avoid using the implicit join syntax.
SELECT U.NAME, MIN(P.PIC_ID)
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
GROUP BY U.NAME;
LocalDateTime.parse(
"2012-07-10 14:58:00.000000".replace( " " , "T" )
)
You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.
Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).
You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date
) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.
Use an appropriate data type instead. Specifically, java.time.LocalDateTime
.
Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM
and mm
have different effects.
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.
Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T
to comply fully.
The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
and I need the resultant date object to be of the same format.
No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.
Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime
objects which lacks those concepts.
String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
To generate a String representing the value of your LocalDateTime
:
toString
to get a String in standard ISO 8601 format.DateTimeFormatter
for producing strings in either custom formats or automatically-localized formats. Search Stack Overflow for more info as these topics have been covered many many times already.
ZonedDateTime
A LocalDateTime
does not represent an exact point on the timeline.
To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Rclone is what you are looking for. Rclone ("rsync for cloud storage") is a command line program to sync files and directories to and from different cloud storage providers including local filesystems. Rclone was previously known as Swiftsync and has been available since 2013.
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.
Create a File
object, passing the directory path to the constructor. Use the listFiles()
to retrieve an array of File
objects for each file in the directory, and then call the getName()
method to get the filename.
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
The solution is given below,
root@123abc:/root# <-- get the container ID
cp thefile.txt /var/lib/docker/devicemapper/mnt/123abc<bunch-o-hex>/rootfs/root
The file shall be directly copied to the location where the container sits on the filesystem.
I was trying to connect to mysql from the python code that was executed using spark-submit
.
I was using HDP sandbox that was using Ambari. Tried lot of options such as --jars
, --driver-class-path
, etc, but none worked.
Copy the jar in /usr/local/miniconda/lib/python2.7/site-packages/pyspark/jars/
As of now I'm not sure if it's a solution or a quick hack, but since I'm working on POC so it kind of works for me.
I have a full explanation already posted here
Basically, General guidelines for designing images are:
ldpi is 0.75x dimensions of mdpi
hdpi is 1.5x dimensions of mdpi
xhdpi is 2x dimensinons of mdpi
Usually, I design mdpi images for a 320x480 screen and then multiply the dimensions as per the above rules to get images for other resolutions.
Please refer to the full explanation for a more detailed answer.
As an Anaconda user, I wanted to find one or two appropriate commands to solve the problem. Fortunately, this answer helped. For conda 4.5.11 (use conda -V
to check Anaconda version) I have performed next steps:
# Python version does not matter, most likely, check yourself
conda create -n myenv python=3.6
conda activate myenv
conda install -c menpo opencv
That will install OpenCV 2.4.11. Anaconda's another command conda install -c menpo opencv3
will install OpenCV3, but Python has to be downgraded to 2.7. To install OpenCV3 with Python3 use next (due to the first link):
conda create -n myenv python
pip install opencv-python==3.4.2.16
pip install opencv-contrib-python==3.4.2.16
Check the SIFT:
conda activate myenv
python
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>
ORA-06512 is part of the error stack. It gives us the line number where the exception occurred, but not the cause of the exception. That is usually indicated in the rest of the stack (which you have still not posted).
In a comment you said
"still, the error comes when pNum is not between 12 and 14; when pNum is between 12 and 14 it does not fail"
Well, your code does this:
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
That is, it raises an exception when pNum is not between 12 and 14. So does the rest of the error stack include this line?
ORA-06510: PL/SQL: unhandled user-defined exception
If so, all you need to do is add an exception block to handle the error. Perhaps:
PROCEDURE PX(pNum INT,pIdM INT,pCv VARCHAR2,pSup FLOAT)
AS
vSOME_EX EXCEPTION;
BEGIN
IF ((pNum < 12) OR (pNum > 14)) THEN
RAISE vSOME_EX;
ELSE
EXECUTE IMMEDIATE 'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('||pCv||', '||pSup||', '||pIdM||')';
END IF;
exception
when vsome_ex then
raise_application_error(-20000
, 'This is not a valid table: M'||pNum||'GR');
END PX;
The documentation covers handling PL/SQL exceptions in depth.
On Mac OS X installing nginx with brew makes the default directory:
/usr/local/var/www
So:
root html
means
root /usr/local/var/www/html
There is no html directory so it would have to be created manually.
This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github
UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js
Have a look at the UUID class bundled with Java 5 and later.
For example:
If you want to use a composer.json
from GitHub you would look at this example (under the VCS section).
The package section is for packages that do not have the composer.json
. However, you didn't follow that example as well or it would also have worked. Do read what it says about package repositories:
Basically, you define the same information that is included in the composer repository's
packages.json
, but only for a single package. Again, the minimum required fields are name, version, and either of dist or source.
PostgreSQL is integrated in Server.app available through the App Store in Mac OS X v10.8 (Mountain Lion). That means that it is already configured, and you only need to launch it, and then create users and databases.
Tip: Do not start with defining $PGDATA and so on. Take file locations as is.
You would have this file: /Library/Server/PostgreSQL/Config/org.postgresql.postgres.plist
To start:
sudo serveradmin start postgres
Process started with arguments:
/Applications/Server.app/Contents/ServerRoot/usr/bin/postgres_real -D /Library/Server/PostgreSQL/Data -c listen_addresses=127.0.0.1,::1 -c log_connections=on -c log_directory=/Library/Logs/PostgreSQL -c log_filename=PostgreSQL.log -c log_line_prefix=%t -c log_lock_waits=on -c log_statement=ddl -c logging_collector=on -c unix_socket_directory=/private/var/pgsql_socket -c unix_socket_group=_postgres -c unix_socket_permissions=0770
You can sudo:
sudo -u _postgres psql template1
Or connect:
psql -h localhost -U _postgres postgres
You can find the data directory, version, running status and so forth with
sudo serveradmin fullstatus postgres
ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...
That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.
If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat
to parse these kinds of strings.
Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:
#include <stdio.h>
#include <string.h>
void reverse_string(char *str)
{
/* skip null */
if (str == 0)
{
return;
}
/* skip empty string */
if (*str == 0)
{
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
/* reverse */
while (end > start)
{
/* swap */
temp = *start;
*start = *end;
*end = temp;
/* move */
++start;
--end;
}
}
int main(void)
{
char s1[] = "Reverse me!";
char s2[] = "abc";
char s3[] = "ab";
char s4[] = "a";
char s5[] = "";
reverse_string(0);
reverse_string(s1);
reverse_string(s2);
reverse_string(s3);
reverse_string(s4);
reverse_string(s5);
printf("%s\n", s1);
printf("%s\n", s2);
printf("%s\n", s3);
printf("%s\n", s4);
printf("%s\n", s5);
return 0;
}
Edited so that end will not point to a possibly bad memory location when strlen is 0.
This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).
Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d
(and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.
You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb
.
Here's the breakdown of the fields:
address
(after the at
) - the location in memory the code is trying to access (it's likely that 10
and 11
are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0
)ip
- instruction pointer, ie. where the code which is trying to do this livessp
- stack pointererror
- An error code for page faults; see below for what this means on x86.
/*
* Page fault error code bits:
*
* bit 0 == 0: no page found 1: protection fault
* bit 1 == 0: read access 1: write access
* bit 2 == 0: kernel-mode access 1: user-mode access
* bit 3 == 1: use of reserved bit detected
* bit 4 == 1: fault was an instruction fetch
*/
CAUTION: This method completely removes MySQL data!
I have same problem in Ubuntu 12.10 , mysql 5.5
I have tested lots of answer related to my issue but none of theme work
at last I had to reinstall remove my mysql server completely and then I install again Mysql server
but you should be aware that you should delete all directory which related to Mysql I use this link to remove mysql completely
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /var/run/mysqld
and then you install again LAMP by tasksel
https://serverfault.com/questions/254629/unable-to-install-mysql-server-in-ubuntu/296928#296928
You can run the query as:
select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'
like others pointed out, if your dates are hardcoded.
On the other hand, if the date is in another table, you can add a day and subtract a second (if the dates are saved without the second/time), like:
select * from person JOIN some_table ... where dob between some_table.initial_date and (some_table.final_date + INTERVAL 1 DAY - INTERVAL 1 SECOND)
Avoid doing casts on the dob
fiels (like in the accepted answer), because that can cause huge performance problems (like not being able to use an index in the dob
field, assuming there is one). The execution plan may change from using index condition
to using where
if you make something like DATE(dob)
or CAST(dob AS DATE)
, so be careful!
If you don't want to use external services (IP websites, etc.) You can use the UPnP Protocol.
Do to that we use a simple UPnP client library (https://github.com/flyte/upnpclient)
Install:
pip install upnpclient
Simple Code:
import upnpclient
devices = upnpclient.discover()
if(len(devices) > 0):
externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
print(externalIP)
else:
print('No Connected network interface detected')
Full Code (to get more information as mentioned in the github readme)
In [1]: import upnpclient
In [2]: devices = upnpclient.discover()
In [3]: devices
Out[3]:
[<Device 'OpenWRT router'>,
<Device 'Harmony Hub'>,
<Device 'walternate: root'>]
In [4]: d = devices[0]
In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]:
{'NewConnectionStatus': 'Connected',
'NewLastConnectionError': 'ERROR_NONE',
'NewUptime': 14851479}
In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}
In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}
What about putting it into cron.hourly
, waiting until the next run of hourly cron jobs, then removing it? That would run it once within an hour, and in the cron environment. You can also run ./your_script
, but that won't have the same environment as under cron.
Just rename the .war
into .jar
and unzip it using Winrar
(or any other archive manager).
c is the new dictionary, and a is your original dictionary, {'z','w'} are the keys you want to remove from a
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
Also check: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01.html
:datetime (8 bytes)
:timestamp (4 bytes)
@IBOutlet weak var constraintTxtV: NSLayoutConstraint!
func TextViewDynamicallyIncreaseSize() {
let contentSize = self.txtVDetails.sizeThatFits(self.txtVDetails.bounds.size)
let higntcons = contentSize.height
constraintTxtV.constant = higntcons
}
A simple way to see the difference between a hard link and a symbolic link is through a simple example. A hard link to a file will point to the place where the file is stored, or the inode of that file. A symbolic link will point to the actual file itself.
So if we have a file called "a" and create a hard link "b" and a symbolic link "c" which all refer to file "a" :
echo "111" > a
ln a b
ln -s a c
The output of "a", "b", and "c" will be :
cat a --> 111
cat b --> 111
cat c --> 111
Now let's remove file "a" and see what happens to the output of "a", "b", and "c":
rm a
cat a --> No such file or directory
cat b --> 111
cat c --> No such file or directory
So what happened?
Because file "c" points to file "a" itself, if file "a" is deleted then file "c" will have nothing to point to, in fact it is also deleted.
However, file "b" points to the place of storage, or the inode, of file "a". So if file "a" is deleted then it will no longer point to the inode, but because file "b" does, the inode will continue to store whatever contents belonged to "a" until no more hard links point to it anymore.
Easiest way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:
1- go to C:\Users[user].android\avd[your virtual device folder] open "config.ini" with text editor like notepad
2- change
"PlayStore.enabled=false" to "PlayStore.enabled=true"
3- change
mage.sysdir.1 = system-images\android-30\google_apis\x86\
to
image.sysdir.1 = system-images\android-30\google_apis_playstore\x86\
The answer to your question is ultimately, it depends. The links in that navigation are added via different layout XML files. Here's the code that first defines the block in layout/customer.xml
. Notice that it also defines some links to add to the menu:
<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
<action method="addLink" translate="label" module="customer"><name>account</name><path>customer/account/</path><label>Account Dashboard</label></action>
<action method="addLink" translate="label" module="customer"><name>account_edit</name><path>customer/account/edit/</path><label>Account Information</label></action>
<action method="addLink" translate="label" module="customer"><name>address_book</name><path>customer/address/</path><label>Address Book</label></action>
</block>
Other menu items are defined in other layout files. For example, the Reviews module uses layout/review.xml
to define its layout, and contains the following:
<customer_account>
<!-- Mage_Review -->
<reference name="customer_account_navigation">
<action method="addLink" translate="label" module="review"><name>reviews</name><path>review/customer</path><label>My Product Reviews</label></action>
</reference>
</customer_account>
To remove this link, just comment out or remove the <action method=...>
tag and the menu item will disappear. If you want to find all menu items at once, use your favorite file search and find any instances of name="customer_account_navigation"
, which is the handle that Magento uses for that navigation block.
I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.
var e = $("<ul><li><div class='bar'>bla</div></li></ul>");
$('li', e).attr('id','a1234'); // set the attribute
$('body').append(e); // put it into the DOM
Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.
The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.
You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.
Example: http://jsbin.com/iceqo
By the way, you may also be interested in microtemplating.
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
I use CodeIgniter. One server OK ... this one probably older ... Anyway using
$this->db->reconnect();
Fixed it.
Well, this is 2017 so you now have Network Information API (albeit with a limited support across browsers as of now) to get some sort of estimate downlink speed information:
navigator.connection.downlink
This is effective bandwidth estimate in Mbits per sec. The browser makes this estimate from recently observed application layer throughput across recently active connections. Needless to say, the biggest advantage of this approach is that you need not download any content just for bandwidth/ speed calculation.
You can look at this and a couple of other related attributes here
Due to it's limited support and different implementations across browsers (as of Nov 2017), would strongly recommend read this in detail
For internal gridlines, use the tag: td For external gridlines, use the tag: table
Update:
I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).
So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.
I wrote a guideline how to install it:
Note:
It is also possible to drag and drop the plugin.dll
file directly in plugin folder.
64bit:%programfiles%\Notepad++\plugins
32bit:%programfiles(x86)%\Notepad++\plugins
Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.
Disclaimer: the link of this guideline refer to my personal web site.
fedorqui has a working solution but there is another way to do the same thing.
Chock if a variable is set
#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
echo 'No, I am not!';
fi
Or to verify that a variable is empty
#!/bin/bash
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
echo 'Yes I am!';
fi
tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Correct me if I am wrong. By doing
[button setSelected:YES];
you are clearly changing the state of the buttons as selected. So naturally by the code you have provided the image will that for the selected state in your case checked.png
If you have the disk space, you could use SELECT INTO and create a new table. It's minimally logged, so it would go much faster
select t.*, int_field = CAST(-1 as int)
into mytable_new
from mytable t
-- create your indexes and constraints
GO
exec sp_rename mytable, mytable_old
exec sp_rename mytable_new, mytable
drop table mytable_old
This seems to be added recently:
https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.
You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.
try the below code
execute immediate 'truncate table tablename' ;
If Age and Palt are columns in the same Table, you can count(*) all tasks and sum only late ones like this:
select ks,
count(*) tasks,
sum(case when Age > Palt then 1 end) late
from Table
group by ks
var title = 'fdfdsg dsgdfh dgdh dsgdh tyu hjuk yjuk uyk hjg fhjg hjj tytutdfsf sdgsdg dsfsdgvf dfgfdhdn dfgilkj,n, jhk jsu wheiu sjldsf dfdsf hfdkdjf dfhdfkd hsfd ,dsfk dfjdf ,yier djsgyi kds';
var shortText = $.trim(title).substring(1000, 150).split(" ").slice(0, -1).join(" ") + "...More >>";
You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.
You can use the window.innerWidth and window.innerHeight properties.
Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:
branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2
For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.
To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:
git co A
git co SHA-of-A2
git co -b AA
Then we created a branch BB from commit B3:
git co B
git co SHA-of-B3
git co -b BB
At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.
It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.
Depending on what you actually want to achieve, you should take a look at Android Handlers:
http://developer.android.com/reference/android/os/Handler.html
If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).
Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.
A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.
The best is to just set form action
to your PHP script; if you need to do anything before submission you can just add to onsubmit
Edit turned out you didn't need any extra function, just a small change here:
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateName(theForm.name);
reason += validatePhone(theForm.phone);
reason += validateEmail(theForm.emaile);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
} else {
simpleCart.checkout();
}
return false;
}
Then in your form:
<form action="#" onsubmit="return validateFormOnSubmit(this);">
Just adding so you don't have to click-through:
curl --user name:password http://www.example.com
or if you're trying to do send authentication for OAuth 2:
curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com
Dictionary is a key value pair. Catch Key by
dic["cat"]
and assign its value like
dic["cat"] = 5
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
happend to me and was sent to this page, not sure if I had the same scenario, but mine was me trying to "re-merge" that "test" branch.
So I previously merged it but I intentionally exclude some specific changes during that merge, so it clearly has some diff between branches. I was then trying to re-merge it because I realize/forget that I should have and wanted to add a particular change/file that I have previously excluded and I was hoping if I do a merge again would show all changes that I excluded before, but I was wrong and I get the "Already up-to-date" message instead.
Upon reading @Bombe's comment/answer, he is right, and git I think behaves that way, so what I did was to make hard backup of the files on test branch, then checkout the master branch and manually paste the files in it and commit it as if it was new changes.
am not sure if this is the right way or could help others having this same issue, but it did provide solution to my particular case.
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.
You may actually go with ViewChild API
...
parent.ts
<button (click)="clicked()">click</button>
export class App {
@ViewChild(Child) vc:Child;
constructor() {
this.name = 'Angular2'
}
func(e) {
console.log(e)
}
clicked(){
this.vc.getName();
}
}
child.ts
export class Child implements OnInit{
onInitialized = new EventEmitter<Child>();
...
...
getName()
{
console.log('called by vc')
console.log(this.name);
}
}
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
Depending on you flavor of SQL, you can also imply the else statement in your aggregate counts.
For example, here's a simple table Grades
:
| Letters |
|---------|
| A |
| A |
| B |
| C |
We can test out each Aggregate counter syntax like this (Interactive Demo in SQL Fiddle):
SELECT
COUNT(CASE WHEN Letter = 'A' THEN 1 END) AS [Count - End],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Count - Else Null],
COUNT(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Count - Else Zero],
SUM(CASE WHEN Letter = 'A' THEN 1 END) AS [Sum - End],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE NULL END) AS [Sum - Else Null],
SUM(CASE WHEN Letter = 'A' THEN 1 ELSE 0 END) AS [Sum - Else Zero]
FROM Grades
And here are the results (unpivoted for readability):
| Description | Counts |
|-------------------|--------|
| Count - End | 2 |
| Count - Else Null | 2 |
| Count - Else Zero | 4 | *Note: Will include count of zero values
| Sum - End | 2 |
| Sum - Else Null | 2 |
| Sum - Else Zero | 2 |
Which lines up with the docs for Aggregate Functions in SQL
Docs for COUNT
:
COUNT(*)
- returns the number of items in a group. This includes NULL values and duplicates.
COUNT(ALL expression)
- evaluates expression for each row in a group, and returns the number of nonnull values.
COUNT(DISTINCT expression)
- evaluates expression for each row in a group, and returns the number of unique, nonnull values.
Docs for SUM
:
ALL
- Applies the aggregate function to all values. ALL is the default.
DISTINCT
- Specifies that SUM return the sum of unique values.
For me when I run git clone, Git will store the cloned package in the directory that I am running the command from.
- I use windows.
for example :
C:\Users\user>git clone https://github.com/broosaction/aria
will create a folder:
C:\Users\user\aria
You are trying to index into a scalar (non-iterable) value:
[y[1] for y in y_test]
# ^ this is the problem
When you call [y for y in test]
you are iterating over the values already, so you get a single value in y
.
Your code is the same as trying to do the following:
y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail
I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test]
.
If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:
[results.append(..., y) for y in y_test]
Or just use a for loop:
for y in y_test:
results.append(..., y)
The correct way to do this is to use readLine
, from the Swift Standard Library.
Example:
let response = readLine()
Will give you an Optional value containing the entered text.
NOTICE: "a" comes AFTER "Z":
$ touch A.txt aa.txt Z.txt
$ ls
A.txt Z.txt aa.txt
map
is the most logical solution for this problem.
let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]
However, if there is a chance that the array is sparse, you'll need to use for
or, even better, for .. of
.
See:
I fixed this problem.The device system version is older then the sdk minSdkVersion? I just modified the minSdkVersion from android_L to 19 to target my nexus 4.4.4.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.2'
}
}
apply plugin: 'com.android.application'
repositories {
jcenter()
}
android {
**compileSdkVersion 'android-L'** modified to 19
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.antwei.uiframework.ui"
minSdkVersion 14
targetSdkVersion 'L'
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
**compile 'com.android.support:support-v4:21.+'** modified to compile 'com.android.support:support-v4:20.0.0'
}
how to modified the value by ide. select file->Project Structure -> Facets -> android-gradle and then modified the compile Sdk Version from android_L to 19
sorry I don't have enough reputation to add pictures
subprocess.check_output() returns bytes.
so you need to convert '\n' to bytes as well:
f.write (plaintext + b'\n')
hope this helps
You could do the following
declare @role varchar(100) = 'Alpha'
select * from xmltable where convert(varchar(max),xmlfield) like '%<role>'+@role+'</role>%'
Obviously this is a bit of a hack and I wouldn't recommend it for any formal solutions. However I find this technique very useful when doing adhoc queries on XML columns in SQL Server Management Studio for SQL Server 2012.
try this way .eregi("[^A-Za-z0-9.]", $value)
The reason for the exception is the re-creation of the FragmentActivity
during the runtime of the AsyncTask
and the access to the previous, destroyed FragmentActivity
in onPostExecute()
afterwards.
The problem is to get a valid reference to the new FragmentActivity
. There is no method for this neither getActivity()
nor findById()
or something similar. This forum is full of threads according this issue (e.g. search for "Activity context in onPostExecute"
). Some of them are describing workarounds (until now I didn't find a good one).
Maybe it would be a better solution to use a Service for my purpose.
USE THIS:
apt-get update && apt-get install -y vim
Explanation of the above command
Got a similar error from CircleCi's error log.
"ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.3.0 but 3.3.3333 was found instead."
Just so you know this did not affect the Angular application, but the CircleCi error was becoming annoying. I am running Angular 7.1
I ran: $ npm i [email protected] --save-dev --save-exact to update the package-lock.json file.
Then I ran: $ npm i
After that I ran: $ npm audit fix
"This CircleCi error message" went away. So it works
First, change your inner code for another loop (for
and while
) so you can repeat the same code for different values.
More specific for your problem, if you want to know if a given n
is prime, you need to divide it for all values between 2 and sqrt(n). If any of the modules is 0, it is not prime.
If you want to find all primes, you can speed it and check n
only by dividing by the previously found primes. Another way of speeding the process is the fact that, apart from 2 and 3, all the primes are 6*k
plus or less 1.
There is a CSS unit called viewport height / viewport width.
Example
.mainbody{height: 100vh;}
similarly html,body{width: 100vw;}
or 90vh = 90% of the viewport height.
**IE9+ and most modern browsers.
Simple answer to this; I was trying to figure out the same thing, and it just hit me.
GitHub IS a program installed on your computer, and when it runs, it WILL use threads and RAM. So that makes it a process. All you have to do is open Task Manager, click the Processes tab, find 'Github.exe', right click, Open File Location. Voila! Mine is in some App folder in Local, about 4 layers deep.
For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.
At least then it's only in once place if you need to later refactor.
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:
launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"
To directly answer your question, you can add launchctl line in your ~/.bash_profile
As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.
You need to CAST
the ParentId
as an nvarchar
, so that the output is always the same data type.
SELECT Id 'PatientId',
ISNULL(CAST(ParentId as nvarchar(100)),'') 'ParentId'
FROM Patients
Route:
<Route state={this.state} exact path="/customers/:id" render={(props) => <PageCustomer {...props} state={this.state} />} />
And then can access params in your PageCustomer component like this: this.props.match.params.id
.
For example an api call in PageCustomer component:
axios({
method: 'get',
url: '/api/customers/' + this.props.match.params.id,
data: {},
headers: {'X-Requested-With': 'XMLHttpRequest'}
})
a.sum(0)
should solve the problem. It is a 2d np.array
and you will get the sum of all column. axis=0
is the dimension that points downwards and axis=1
the one that points to the right.
parseInt will throw NumberFormatException if it cannot parse the integer. So doing this will answer your question
try{
Integer.parseInt(....)
}catch(NumberFormatException e){
//couldn't parse
}
def gcdIter(a, b):
gcd= min (a,b)
for i in range(0,min(a,b)):
if (a%gcd==0 and b%gcd==0):
return gcd
break
gcd-=1
The thing is that two double may not be exactly equal due to precision issues inherent to floating point numbers. With this delta value you can control the evaluation of equality based on a error factor.
Also some floating-point values can have special values like NAN and -Infinity/+Infinity which can influence results.
If you really intend to compare that two doubles are exactly equal it is best compare them as an long representation
Assert.assertEquals(Double.doubleToLongBits(expected), Double.doubleToLongBits(result));
Or
Assert.assertEquals(0, Double.compareTo(expected, result));
Which can take these nuances into account.
I have not delved into the Assert method in question, but I can only assume the previous was deprecated for this kind of issues and the new one does take them into account.
You should not expose this info. in public, specially api keys. It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
My understanding is that those two examples are effectively equivalent. The only difference is that in the first, you can reuse the compiled regular expression elsewhere without causing it to be compiled again.
Here's a reference for you: http://diveintopython3.ep.io/refactoring.html
Calling the compiled pattern object's search function with the string 'M' accomplishes the same thing as calling re.search with both the regular expression and the string 'M'. Only much, much faster. (In fact, the re.search function simply compiles the regular expression and calls the resulting pattern object's search method for you.)
Inspired by Matt Gregory's answer here is a bit more complicated iterator that will return a,b,...,z,aa,ab,...,zz,aaa,aab,...,zzy,zzz
class AlphaCounter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def __next__(self): # Python 3: def __next__(self)
alpha = ' abcdefghijklmnopqrstuvwxyz'
n_current = sum([(alpha.find(self.current[x])* 26**(len(self.current)-x-1)) for x in range(len(self.current))])
n_high = sum([(alpha.find(self.high[x])* 26**(len(self.high)-x-1)) for x in range(len(self.high))])
if n_current > n_high:
raise StopIteration
else:
increment = True
ret = ''
for x in self.current[::-1]:
if 'z' == x:
if increment:
ret += 'a'
else:
ret += 'z'
else:
if increment:
ret += alpha[alpha.find(x)+1]
increment = False
else:
ret += x
if increment:
ret += 'a'
tmp = self.current
self.current = ret[::-1]
return tmp
for c in AlphaCounter('a', 'zzz'):
print(c)
INFLATE THE LAYOUT !! (which contains the id)
In my case findViewById() returned null, because the layout in which the element was written, was not inflated...
Eg. fragment_layout.xml
<ListView
android:id="@+id/listview">
findViewById(R.id.listview) returned null, because I had not done inflater.inflate(R.layout.fragment_layout, ..., ...); before it.
Hope this answer helps some of y'all.
One difference observed (Python27):
os.environ
raises an exception if the environmental variable does not exist.
os.getenv
does not raise an exception, but returns None
Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use ThreadLocalRandom.current().nextLong(n)
(for 0 = x < n) and ThreadLocalRandom.current().nextLong(m, n)
(for m = x < n). See @Alex's answer for detail.
If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g. org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
, see @mawaldne's answer), or implement your own nextLong(n)
.
According to https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html nextInt
is implemented as
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
So we may modify this to perform nextLong
:
long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits-val+(n-1) < 0L);
return val;
}
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
Try This
$(this).closest('.ui-dialog-content').dialog('close');
It will close the dialog inside it.
Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:
else if (e.getKeyCode()==38)
{
//Up arrow key code
}
else if (e.getKeyCode()==40)
{
//down arrow key code
}
Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:
Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click()
, submit()
et al:
on some event; assign or set the value of the input:
$('#inputid').val($('#idB').text());
where:
<input id = "inputid" type = "hidden" />
<div id = "idB">This text will be passed to the input</div>
Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.
Beware the differences betwen .html()
and .text()
when dealing with html forms.
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Best solution is randint
, but this function produce integer numbers.
You can use rand
with rounding function
r = round(a + (b-a).*rand(m,n));
This produces Real random number between a and b , size of output matrix is m*n
A much more secure answer that I'm surprised is not mentioned here yet:
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );
For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING
.
I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:
$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.
One other scenario which I encountered.
String imageName ="Hello" and then when it is passed into getIdentifier function as first argument, it will pass the name with string null termination and will always return zero. Pass this imageName.substring(0, imageName.length()-1)
This fiddle has both each
and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.
Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.
Eg1: The below example is directly calling json key (data) inside small_data variable.
In html use the below code:
<div id="small-content-placeholder"></div>
The below can be placed in header or body of html:
<script id="small-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#data}}
<tr>
<td>{{username}}
</td>
<td>{{email}}</td>
</tr>
{{/data}}
</tbody>
</table>
</script>
The below one is on document ready:
var small_source = $("#small-template").html();
var small_template = Handlebars.compile(small_source);
The below is the json:
var small_data = {
data: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
]
};
Finally attach the json to content holder:
$("#small-content-placeholder").html(small_template(small_data));
Eg2: Iteration using each.
Consider the below json.
var big_data = [
{
name: "users1",
details: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
},
{
name: "users2",
details: [
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
}
];
While passing the json to content holder just name it in this way:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
And the template looks like :
<script id="big-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#each big_data}}
<tr>
<td>{{name}}
<ul>
{{#details}}
<li>{{username}}</li>
<li>{{email}}</li>
{{/details}}
</ul>
</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:
final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
// No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}
You still need to consider the case of a reverse-proxy:
Could use constants for the ports but not sure if there is a reliable source for them, default ports:
Most developers will know about port 80 and 443 anyways, so constants are not that helpful.
Also see this similar post.
It is easy you need to echo the value you need to return and then capture it like below
demofunc(){
local variable="hellow"
echo $variable
}
val=$(demofunc)
echo $val
use this code for set value in input tag by another id.
$(".formdata").val(document.getElementById("fsd").innerHTML);
or use this code for set value in input tag using classname="formdata"
$(".formdata").val("hello");
By default you use UNICODE so I suggest using faulty's method
int bar = int.Parse(foo.ToString());
Even though the numeric values under are the same for digits and basic Latin chars.
This issue is quite possibly due to exceeding the 65K methods dex limit imposed by Android. This problem can be solved either by cleaning the project, and removing some unused libraries and methods from dependencies in build.gradle, OR by adding multidex support.
So, If you have to keep libraries and methods, then you can enable multi dex support by declaring it in the gradle config.
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
You can read more about multidex support and developing apps with more than 65K methods here.
On some CPUs, there is a dedicated set of registers for the stack. When a call instruction is executed, one register is loaded with the program counter at the same time as a second register is loaded with the contents of the first, a third register is be loaded with the second, and a fourth with the third, etc. When a return instruction is executed, the program counter is latched with the contents of the first stack register and the same time as that register is latched from the second; that second register is loaded from a third, etc. Note that such hardware stacks tend to be rather small (many the smaller PIC series micros, for example, have a two-level stack).
While a hardware stack does have some advantages (push and pop don't add any time to a call/return, for example) having registers which can be loaded with two sources adds cost. If the stack gets very big, it will be cheaper to replace the push-pull registers with an addressable memory. Even if a small dedicated memory is used for this, it's cheaper to have 32 addressable registers and a 5-bit pointer register with increment/decrement logic, than it is to have 32 registers each with two inputs. If an application might need more stack than would easily fit on the CPU, it's possible to use a stack pointer along with logic to store/fetch stack data from main RAM.
Try using the above options But this one worked for me. my JAVA_HOME looked like this C:\Program Files\Java\jdk1.7.0_21;F:\Software\apache-ant-1.9.4-bin\apache-ant-1.9.4\bin Only keeping the JAVA path in the JAVA_HOME Remove any additional path if you had given C:\Program Files\Java\jdk1.7.0_21
Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx
EDIT:
You need to put the protocol prefix in front the address, i.e. in your case "ftp://"
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
You can use PHP, JSP, ASP or any other server side script to connect with mysql database and and return JSON data that you can parse it to in your android app this link how to do it
Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...
$("#formID").serialize()
It creates a string for you with all of the values automatically.
As for looping through objects, you can also do this.
$.each($("input, select, textarea"), function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.val();
});
Try introspective sort. http://en.wikipedia.org/wiki/Introsort
It's quicksort based, but it avoids the worst case behaviour that quicksort has for nearly sorted lists.
The trick is that this sort-algorithm detects the cases where quicksort goes into worst-case mode and switches to heap or merge sort. Nearly sorted partitions are detected by some non naiive partition method and small partitions are handled using insertion sort.
You get the best of all major sorting algorithms for the cost of a more code and complexity. And you can be sure you'll never run into worst case behaviour no matter how your data looks like.
If you're a C++ programmer check your std::sort algorithm. It may already use introspective sort internally.
You can indeed run multiple animations simultaneously, but your example has two problems. First, the syntax you use only specifies one animation. The second style rule hides the first. You can specify two animations using syntax like this:
-webkit-animation-name: spin, scale
-webkit-animation-duration: 2s, 4s
as in this fiddle (where I replaced "scale" with "fade" due to the other problem explained below... Bear with me.): http://jsfiddle.net/rwaldin/fwk5bqt6/
Second, both of your animations alter the same CSS property (transform) of the same DOM element. I don't believe you can do that. You can specify two animations on different elements, the image and a container element perhaps. Just apply one of the animations to the container, as in this fiddle: http://jsfiddle.net/rwaldin/fwk5bqt6/2/
Simply add a zero width space character inside a pseudo element
.class:after {
content: '\200b';
}
Static methods use the class as the object for locking, which is Utils.class for your example. So yes, it is OK.
Here's an option if you need to escape multiple %'s in a string with some already escaped.
(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])
To sanitise the message before passing it to String.format, you can use the following
Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);
StringBuffer buf = new StringBuffer();
while (m1.find())
m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));
// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();
This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.
It will leave any already escaped characters alone (e.g. %%, %%%% etc.)
Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...
That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.
Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.
This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.
In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like
var devTask = {
task_id: 120,
store_id: 2118,
task_name: 'generalLedger'
};
or
generalLedgerTask = new GeneralLedgerTask( devTask );
And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.
I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.
As stated in one of the comments, this works for Mac (probably for Windows/Linux too):
I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST
The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name
host.docker.internal
which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.You can also reach the gateway using
gateway.docker.internal
.
Quoted from https://docs.docker.com/docker-for-mac/networking/
This worked for me without using --net=host
.
For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.
To answer the @ascobol
's question using @bobince
's suggestion from the comments:
for i in range(5000):
for j in range(3000):
if should_terminate_the_loop:
break
else:
continue # no break encountered
break
The indent for the else
block is correct. The code uses obscure else
after a loop Python syntax. See Why does python use 'else' after for and while loops?
I like this syntax and indendation:
string = 'my long string...\n'
+ 'continue here\n'
+ 'and here.';
(but actually can't be considered as multiline string)
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
1.Create a custom pipe to get keys.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'keys'
})
export class KeysPipe implements PipeTransform {
transform(value: any, args?: any): any {
return Object.keys(value);
}
}
- In angular template file, you can use *ngFor and iterate over your object object
<div class ="test" *ngFor="let key of Obj | keys">
{{key}}
{{Obj[key].property}
<div>
This is probably not suitable for production because it will open the keyboard. Note that the boolean returned by similar functions is not specified in the API and are therefore unreliable. Refer to the documentation here...
public boolean showSoftInput (View view,
int flags,
ResultReceiver resultReceiver)
Note that this method takes a ResultReceiver. It can get the results: RESULT_UNCHANGED_SHOWN, RESULT_UNCHANGED_HIDDEN, RESULT_SHOWN, or RESULT_HIDDEN. If you get RESULT_UNCHANGED_SHOWN, the keyboard was visible. If you need it to stay closed if it was closed, you will need to close it.
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
What is wrong with List<T>.Sort()
?
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.sort#overloads
You can actually use localhost:8000
to connect to your machine's localhost by running below command each time when you run your emulator (tested on Mac only):
adb reverse tcp:8000 tcp:8000
Just put it to Android Studio terminal.
It basically sets up a reverse proxy in which a http server running on your phone accepts connections on a port and wires them to your computer or vice versa.
If you know the exact axis you want, then
pylab.ylim([0,1000])
works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft
as in the question, then add this after your plot command:
length = (len(fft))
pylab.ylim([0,length])
It is 2019 and many of the answers here would work, depending on what you want to do. If you want to pass in some internal state not visible in URL (params, query) you can use state
since 7.2 (as I have learned just today :) ).
From the blog (credits Tomasz Kula) - you navigate to route....
...from ts: this.router.navigateByUrl('/details', { state: { hello: 'world' } });
...from HTML template: <a routerLink="/details" [state]="{ hello: 'world' }">Go</a>
And to pick it up in the target component:
constructor(public activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.state$ = this.activatedRoute.paramMap
.pipe(map(() => window.history.state))
}
Late, but hope this helps someone with recent Angular.
How about doing this by creating a function in javascript as shown below:
function msToTime(duration) {_x000D_
var milliseconds = parseInt((duration % 1000) / 100),_x000D_
seconds = Math.floor((duration / 1000) % 60),_x000D_
minutes = Math.floor((duration / (1000 * 60)) % 60),_x000D_
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);_x000D_
_x000D_
hours = (hours < 10) ? "0" + hours : hours;_x000D_
minutes = (minutes < 10) ? "0" + minutes : minutes;_x000D_
seconds = (seconds < 10) ? "0" + seconds : seconds;_x000D_
_x000D_
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;_x000D_
}_x000D_
console.log(msToTime(300000))
_x000D_
(a–b)/c*(d + e – f / g)
step 1: (a-b)/c*(d+e- /fg))
step 2: (a-b)/c*(+de - /fg)
step 3: (a-b)/c * -+de/fg
Step 4: -ab/c * -+de/fg
step 5: /-abc * -+de/fg
step 6: */-abc-+de/fg
This is prefix notation.
For those that run into this and end up on this answer, as I did, where they got this error during uninstall orupgrade and Ubuntu keeps failing to uninstall the previous because the service doesn't exist this one line will get you past that and allow the uninstall or upgrade to continue.
sudo touch /lib/systemd/system/mongod.service
The "Python Packaging Authority" has a sampleproject:
https://github.com/pypa/sampleproject
It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.
I know I'm late to the party, but I needed something similar that the above answers didn't help.
I was using Angular's $watch function to detect changes in a variable. Not only did I need to know whether a property had changed on the variable, but I also wanted to make sure that the property that changed was not a temporary, calculated field. In other words, I wanted to ignore certain properties.
Here's the code: https://jsfiddle.net/rv01x6jo/
Here's how to use it:
// To only return the difference
var difference = diff(newValue, oldValue);
// To exclude certain properties
var difference = diff(newValue, oldValue, [newValue.prop1, newValue.prop2, newValue.prop3]);
Hope this helps someone.
First Declare Permission in Android Manifest:-
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MainActivityForDownloadImages.java
public class MainActivityForDownloadImages extends AppCompatActivity {
// String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
String urls = "https://images5.alphacoders.com/609/609173.jpg";
Button button;
public final Context context = this;
ProgressDialog progressDialog ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_for_download_images);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
progressDialog = new ProgressDialog(context);
button = findViewById(R.id.downloadImagebtn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// initialize the progress dialog like in the first example
// this is how you fire the downloader
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra("url", urls);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
}
}
}
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
progressDialog.setProgress(progress);
progressDialog.setMessage("Images Is Downloading");
progressDialog.show();
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
}
DownloadService.java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
inerDire.createNewFile();
FileOutputStream output = new FileOutputStream(inerDire);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
array_splice($array, array_search(array_value, $array), 1);
If your browser supports CSS3, try using the CSS element Calc()
height: calc(100% - 65px);
you might also want to adding browser compatibility options:
height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */
also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622
I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.
First, get hostname and port number by typing a command lsnrctl status
on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521
Second, enter the below command with your hostname and port number:
sqlplus username/password@HostName:Port Number/PluggableDatabaseName.
For example:
sqlplus hr/[email protected]:1521/ORCLPDB.
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete
Presumably you mean heap from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).
A very simple explanation is that the heap is the portion of memory where dynamically allocated memory resides (i.e. memory allocated via malloc
). Memory allocated from the heap will remain allocated until one of the following occurs:
free
'dIf all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a memory leak. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.
Contrast this with stack memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).
You can find more information about the heap in this article.
Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray
at a certain index, you would do it using the method:
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
This method is called insertObject:atIndex:
and it is clear that an object is being inserted at a specified index.
In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray
called array
would be called as follows:
NSString *obj = @"Hello, World!";
int index = 5;
[array insertObject:obj atIndex:index];
This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.
Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber
class; this has several object creation methods, including:
+ (id)numberWithBool:(BOOL)value;
+ (id)numberWithFloat:(float)value;
+ (id)numberWithDouble:(double)value;
In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.
In this code, jsondata is our array and in function return we are checking the 'version' present in the jsondata.
var as = $filter('filter')(jsondata, function (n,jsondata){
return n.filter.version==='V.0.3'
});
console.log("name is " + as[0].name+as[0]);
It is possible with PowerShell 4.
Get-Service *spool* | select name,starttype | ft -AutoSize
diff(1) is not the answer, but comm(1) is.
NAME
comm - compare two sorted files line by line
SYNOPSIS
comm [OPTION]... FILE1 FILE2
...
-1 suppress lines unique to FILE1
-2 suppress lines unique to FILE2
-3 suppress lines that appear in both files
So
comm -2 -3 file1 file2 > file3
The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...
comm -2 -3 <(sort file1) <(sort file2) > file3
provided that your shell supports process substitution (bash does).
I need to do 2 things to connect with instance name
1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)
Restart sql and done
Since my tomcat instances are named as tomcat_ . For example. tomcat_8086, I use
#
ps aux | grep tomcat
Other method is using nc utility
nc -l 8086
(port number )Or
ps aux | grep java
If you're geting [object object]
then use JSON.stringify
fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');
It worked for me.
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
This should do it:
var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);
For the caller, just use caller.toString()
.
It might be help someone. Similar example.
This is our Codable
class to bind data. You can easily create this class using SwiftyJsonAccelerator
class ModelPushNotificationFilesFile: Codable {
enum CodingKeys: String, CodingKey {
case url
case id
case fileExtension = "file_extension"
case name
}
var url: String?
var id: Int?
var fileExtension: String?
var name: String?
init (url: String?, id: Int?, fileExtension: String?, name: String?) {
self.url = url
self.id = id
self.fileExtension = fileExtension
self.name = name
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
url = try container.decodeIfPresent(String.self, forKey: .url)
id = try container.decodeIfPresent(Int.self, forKey: .id)
fileExtension = try container.decodeIfPresent(String.self, forKey: .fileExtension)
name = try container.decodeIfPresent(String.self, forKey: .name)
}
}
This is Json String
let jsonString = "[{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/tulips.png\"},
{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/arctichare.png\"},
{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/serrano.png\"},
{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/peppers.png\"},
{\"name\":\"\",\"file_extension\":\"\",\"id\":10684,\"url\":\"https:\\/\\/homepages.cae.wisc.edu\\/~ece533\\/images\\/pool.png\"}]"
Here we convert to swift object.
let jsonData = Data(jsonString.utf8)
let decoder = JSONDecoder()
do {
let fileArray = try decoder.decode([ModelPushNotificationFilesFile].self, from: jsonData)
print(fileArray)
print(fileArray[0].url)
} catch {
print(error.localizedDescription)
}
Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:
func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax
let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
return CLLocation(latitude: lat, longitude: lng)
}
In this function to convert distance I use following formulas:
latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))
Another css that can make the margin problem is that you have direction:someValue
in your css, so just remove it by setting it to initial.
For example:
body {
direction:rtl;
}
@media (max-width: 480px) {
body {
direction:initial;
}
}
You can get other constructors with getConstructor(...).
Change modalPresentationStyle
before presenting
vc.modalPresentationStyle = UIModalPresentationFullScreen;
Watch out for other paths ending in \ too. I had this:
...bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs\
and changed it to this:
bin;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\nodejs
removing the final \, but it still didn't work. The previous path, for the Web Platform Installer, had a trailing \ too. Removing that fixed the problem.
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)
SCSS styles
@font-face {
font-family: 'pass';
font-style: normal;
font-weight: 400;
src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}
input.password {
font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
font-size: 18px;
&::-webkit-input-placeholder {
transform: scale(0.77);
transform-origin: 0 50%;
}
&::-moz-placeholder {
font-size: 14px;
opacity: 1;
}
&:-ms-input-placeholder {
font-size: 14px;
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
After that, I got identical display input[password]
In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.
Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.
You can use it without casting such as:
select sum(`stuff`) as mySum from test;
Or cast it to decimal:
select sum(cast(`stuff` as decimal(4,2))) as mySum from test;
EDIT
For SQL Server, you can use:
select sum(cast(stuff as decimal(5,2))) as mySum from test;
To just get everything done goto Window>Preferences>General and goto theme menu and change it... Then re-start to apply...
I created my own function converting numbers to their corresponding month.
def month_name (number):
if number == 1:
return "January"
elif number == 2:
return "February"
elif number == 3:
return "March"
elif number == 4:
return "April"
elif number == 5:
return "May"
elif number == 6:
return "June"
elif number == 7:
return "July"
elif number == 8:
return "August"
elif number == 9:
return "September"
elif number == 10:
return "October"
elif number == 11:
return "November"
elif number == 12:
return "December"
Then I can call the function. For example:
print (month_name (12))
Outputs:
>>> December
Sessions - what Chris Thompson said.
Instantiation - a servlet is instantiated when the container receives the first request mapped to the servlet (unless the servlet is configured to load on startup with the <load-on-startup>
element in web.xml
). The same instance is used to serve subsequent requests.
Try something like
find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)
and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
Numpty here used SQL authentication
instead of Windows (correct)
when adding the login to SQL Server, which also gives you this error if you are using Windows auth.
you can create and initialize array of any object like this.
hero:Hero[]=[];
Concat date of one column with a time of another column in MySQL.
SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
Firefox doesn't support outerHTML, so you need to define a function to help support it:
function outerHTML(node) {
return node.outerHTML || (
function(n) {
var div = document.createElement('div');
div.appendChild( n.cloneNode(true) );
var h = div.innerHTML;
div = null;
return h;
}
)(node);
}
Then, you can use outerHTML:
var x = outerHTML($('#container').get(0));
$('#save').val(x);
I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.
For example:
[
3 => 'a',
2 => 'b',
1 => 'c',
0 => 'd'
]
Will return:
{
0: 'd',
1: 'c',
2: 'b',
3: 'a'
}
So the solution in this case, is to use array_reverse
before encoding it to json
If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.
@Service
public class MyService {
@Autowired
private TransactionTemplate transactionTemplate;
private void process(){
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
processInTransaction();
}
});
}
private void processInTransaction(){
//...
}
}
I know this question has already been answered, but thought I might add that I found the problem to be folder permissions on my android-sdk
directory.
I tested it out by granting Full Control to Everyone (dodgy, I know...), and the problem went away. I am not sure yet what the specific mix of permissions might be that it was looking for, but I assume some or other service in Eclipse didn't have execute permissions on adb.exe. That said, I'm a complete noob to this - just wanted to put it out there in case someone else had some insights into this.
I am running Windows 7, 64-bit, 4.2.0 Eclipse, and 20.0.0v201206242043 ADT.
Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to
include_path='.:/usr/share/php:/usr/share/pear'
or append the
'.:/usr/share/php:/usr/share/pear'
to the current value of include_path.
It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir
Nurik's answer was very helpful, but I couldn't get it to work until I found this. In short, if you're using the compatibility library (eg SupportFragmentManager instead of FragmentManager), the syntax of the XML animation files will be different.
Give your radiobutton a custom style:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@drawable/custom_btn_radio</item>
</style>
custom_btn_radio.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" />
<item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
Replace the drawables with your own.
For a bit of facts here is the relevant text from the specifications
Pointers to objects of the same type can be compared for equality with the 'intuitive' expected results:
From § 5.10 of the C++11 standard:
Pointers of the same type (after pointer conversions) can be compared for equality. Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address (3.9.2).
(leaving out details on comparison of pointers to member and or the null pointer constants - they continue down the same line of 'Do What I Mean':)
- [...] If both operands are null, they compare equal. Otherwise if only one is null, they compare unequal.[...]
The most 'conspicuous' caveat has to do with virtuals, and it does seem to be the logical thing to expect too:
- [...] if either is a pointer to a virtual member function, the result is unspecified. Otherwise they compare equal if and only if they would refer to the same member of the same most derived object (1.8) or the same subobject if they were dereferenced with a hypothetical object of the associated class type. [...]
From § 5.9 of the C++11 standard:
Pointers to objects or functions of the same type (after pointer conversions) can be compared, with a result defined as follows:
- If two pointers p and q of the same type point to the same object or function, or both point one past the end of the same array, or are both null, then
p<=q
andp>=q
both yield true andp<q
andp>q
both yield false.- If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of
p<q,
p>q,
p<=q,
andp>=q
are unspecified.- If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, recursively, the pointer to the later declared member compares greater provided the two members have the same access control (Clause 11) and provided their class is not a union.
- If two pointers point to non-static data members of the same object with different access control (Clause 11) the result is unspecified.
- If two pointers point to non-static data members of the same union object, they compare equal (after conversion to
void*
, if necessary). If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.- Other pointer comparisons are unspecified.
So, if you had:
int arr[3];
int *a = arr;
int *b = a + 1;
assert(a != b); // OK! well defined
Also OK:
struct X { int x,y; } s;
int *a = &s.x;
int *b = &s.y;
assert(b > a); // OK! well defined
But it depends on the something
in your question:
int g;
int main()
{
int h;
int i;
int *a = &g;
int *b = &h; // can't compare a <=> b
int *c = &i; // can't compare b <=> c, or a <=> c etc.
// but a==b, b!=c, a!=c etc. are supported just fine
}
§ 20.8.5/8: "For templates greater
, less
, greater_equal
, and less_equal
, the specializations for any pointer type yield a total order, even if the built-in operators <
, >
, <=
, >=
do not."
So, you can globally order any odd void*
as long as you use std::less<>
and friends, not bare operator<
.
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
Why do they let the exception bubble up? Isn't handling the error sooner better? Why bubble up?
For example let say you have some client-server application and client had made a request for some resource that couldn't be find out or for something else error some might have occurred at the server side while processing the user request then it is the duty of the server to tell the client why he couldn't get the thing he requested for,so to achieve that at server side, code is written to throw the exception using throw keyword instead of swallowing or handling it.if server handles it/swallow it, then there will be no chance of intimating to the client that what error had occurred.
Note:To give a clear description of what the error type has occurred we can create our own Exception object and throw it to the client.
scp file user@host:/path/on/host
Another source of this problem: I found that in Debian 9, the Python httplib2 is hardcoded to insist on TLS v1.0. So any application that uses httplib2 to connect to a server that insists on better security fails with TLSV1_ALERT_PROTOCOL_VERSION.
I fixed it by changing
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
to
context = ssl.SSLContext()
in /usr/lib/python3/dist-packages/httplib2/__init__.py .
Debian 10 doesn't have this problem.
My problem: I forgot to import a newly added project (added by my co-worker) into my eclipse workspace.
File > Import > Maven > Existing Maven Projects, find it in the dir-tree, check the single non-ghosted one which is not already added.
Details: My co-worker had added a new project which was a git submodule. Existing projects referred to it in their pom.xml. I had already done "git submodule init" and "git submodule update". mvn built fine from the command-line but I kept getting this "Missing artifact" error in eclipse pointing at the top of my pom.xml.
ok, everyone is making sense and I took all the pieces and put them here to help newbies like myself that need beginning to end explanation.
You make your big class that holds 2 classes, as per @Andrew's answer.
public class teamBoards{
public Boards Boards{get; set;}
public Team Team{get; set;}
}
Then in your controller you fill the 2 models. Sometimes you only need to fill one. Then in the return, you reference the big model and it will take the 2 inside with it to the View.
TeamBoards teamBoards = new TeamBoards();
teamBoards.Boards = (from b in db.Boards
where b.TeamId == id
select b).ToList();
teamBoards.Team = (from t in db.Teams
where t.TeamId == id
select t).FirstOrDefault();
return View(teamBoards);
At the top of the View
@model yourNamespace.Models.teamBoards
Then load your inputs or displays referencing the big Models contents:
@Html.EditorFor(m => Model.Board.yourField)
@Html.ValidationMessageFor(m => Model.Board.yourField, "", new { @class = "text-danger-yellow" })
@Html.EditorFor(m => Model.Team.yourField)
@Html.ValidationMessageFor(m => Model.Team.yourField, "", new { @class = "text-danger-yellow" })
And. . . .back at the ranch, when the Post comes in, reference the Big Class:
public ActionResult ContactNewspaper(teamBoards teamboards)
and make use of what the model(s) returned:
string yourVariable = teamboards.Team.yourField;
Probably have some DataAnnotation Validation stuff in the class and probably put if(ModelState.IsValid) at the top of the save/edit block. . .
As a more brute force method that I found worked for me:
First wrap the text inside the button in a span, and then apply this css to that span
var spanStyle = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)"
}
*above setup for inline styling
I usually store phone numbers as a BIGINT in E164 format.
E164 never start with a 0, with the first few digits being the country code.
+441234567890
+44 (0)1234 567890
01234 567890
etc. would be stored as 441234567890
.
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
I am in the process of figuring it out now but it seems as though the math depends on where you and your target are on the earth relative to true and magnetic North. For example:
float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) > myLocation.getBearing()){
thetaMeThem = myLocation.bearingTo(targetLocation) - azimuth + declination;}
See Sensor.TYPE_ORIENTATION for azimuth.
See getDeclination() for declination
This assumes declination is negative (west of true north) and theirBearing > yourBearing.
If declination is positive and yourBearing > theirBearing another option:
float thetaMeThem = 0.0;
if (myLocation.bearingTo(targetLocation) < myLocation.getBearing()){
thetaMeThem = azimuth - (myLocation.bearingTo(targetLocation) - declination);}
I haven't tested this fully but playing with the angles on paper got me here.
Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.
You can do that by adding your view directly to the keyWindow:
UIView *myView = /* <- Your custom view */;
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:myView];
UPDATE -- For Swift 4.1 and above
let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(myView)
UPDATE for iOS13 and above
keyWindow
is deprecated. You should use the following:
UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.addSubview(myView)
Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:
Not all these bullet points are 100% accurate, but you get the gist.
On the other hand:
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
I have used the Open Clover Tool for the code coverage, I have also been searching this for a long time. Its pretty straightforward, in the Coverage Explorer tab, you can find three square buttons which says the code lines you wanted to display, click on hide the coverage square box and its gone. Last button in the image below: