C99 way, also supported by VC++ compiler.
#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)
One more important thing needs to be highlighted. It's better to use params
because it is better for performance. When you call a method with params
argument and passed to it nothing:
public void ExampleMethod(params string[] args)
{
// do some stuff
}
call:
ExampleMethod();
Then a new versions of the .Net Framework do this (from .Net Framework 4.6):
ExampleMethod(Array.Empty<string>());
This Array.Empty
object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:
ExampleMethod(new string[] {});
If what you are needing is an array of arrays, you can do this way:
key:
- [ 'value11', 'value12', 'value13' ]
- [ 'value21', 'value22', 'value23' ]
you could have a computed property that returns a boolean dependent on whatever criteria you need.
<input type="text" :disabled=isDisabled>
then put your logic in a computed property...
computed: {
isDisabled() {
// evaluate whatever you need to determine disabled here...
return this.form.validated;
}
}
Enable CORS on backend server or add chrome extensions https://chrome.google.com/webstore/search/CORS?utm_source=chrome-ntp-icon and make ON
How about either of:
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
git log --all -- path/to/file
should work
boolean x;
for (x = false,
map.put("One", new Integer(1)),
map.put("Two", new Integer(2)),
map.put("Three", new Integer(3)); x;);
Ignoring the declaration of x
(which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.
Here's another alternative:
Sub subSleep(strSeconds) ' subSleep(2)
Dim objShell
Dim strCmd
set objShell = CreateObject("wscript.Shell")
'objShell.Run cmdline,1,False
strCmd = "%COMSPEC% /c ping -n " & strSeconds & " 127.0.0.1>nul"
objShell.Run strCmd,0,1
End Sub
In their latest release there's a directive called md-icon
<md-icon icon="img/icons/ic_refresh_24px.svg"></md-icon>
Python 3
urllib.request — Extensible library for opening URLs
from urllib.error import HTTPError
from urllib.request import urlretrieve
try:
urlretrieve(image_url, image_local_path)
except FileNotFoundError as err:
print(err) # something wrong with local path
except HTTPError as err:
print(err) # something wrong with url
Practical example:
Imagine that you are modelling something like an I2C bus (signals called SCL
for clock and SDA
for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.
scl <= 'H'; -- Testbench resistor pullup
Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'
Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.
If you have a line of code that relies on (scl'event and scl =
'1')
, then you'll get a false trigger.
If you have a line of code that relies on rising_edge(scl)
, then
you won't get a false trigger.
Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.
Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl)
condition (correct), but the (scl'event and scl = '1')
case will miss it (incorrect).
General Recommenation:
Use rising_edge(clk)
and falling_edge(clk)
instead of clk'event
for all code.
Another clean way to save the file is this:
import csv
import urllib
urllib.retrieve("your url goes here" , "output.csv")
You want set_ticks_position
rather than set_label_position
:
ax.xaxis.set_ticks_position('top') # the rest is the same
This gives me:
Platform-independent way (starting from c++11) is:
#include <thread>
std::this_thread::get_id();
Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:
str = str.replaceAll(",","."); // or "\\.", it doesn't matter...
Choose a database name in Initial Catalog
Data Source=HARIHARAN-PC\SQLEXPRESS;Initial Catalog=your database name;Integrated Security=True" ;
UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.
Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.
You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.
You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.
Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)
Then you can do something static like this:
myStringArray = { item_1, item_2, ... }
Or something iterative like this:
Dim x
For x = 0 To size_of_your_array
myStringArray(x) = data_source(x).Name
Next x
this works for me:
table {
border-collapse: collapse;
border-style: hidden;
}
table td, table th {
border: 1px solid black;
}
tested in FF 3.6 and Chromium 5.0, IE lacks support; from W3C:
Borders with the 'border-style' of 'hidden' take precedence over all other conflicting borders. Any border with this value suppresses all borders at this location.
Take a look at this project it outputs some interesting stats about keyspaces based on regexs and prefixes. It uses the DEBUG OBJECT
command and scans the db, identifying groups of keys and estimating the percentage of space they're taking up.
https://github.com/snmaynard/redis-audit
Output looks like this:
Summary
---------------------------------------------------+--------------+-------------------+---------------------------------------------------
Key | Memory Usage | Expiry Proportion | Last Access Time
---------------------------------------------------+--------------+-------------------+---------------------------------------------------
notification_3109439 | 88.14% | 0.0% | 2 minutes
user_profile_3897016 | 11.86% | 99.98% | 20 seconds
---------------------------------------------------+--------------+-------------------+---------------------------------------------------
Or this this one: https://github.com/sripathikrishnan/redis-rdb-tools which does a full analysis on the entire keyspace by analyzing a dump.rdb file offline. This one works well also. It can give you the avg/min/max size for the entries in your db, and will even do it based on a prefix.
I found a solution by myself after doing some research:
Now everything works fine.
You can use a kind of continue
by using a nested Do ... Loop While False
:
'This sample will output 1 and 3 only
Dim i As Integer
For i = 1 To 3: Do
If i = 2 Then Exit Do 'Exit Do is the Continue
Debug.Print i
Loop While False: Next i
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
All Landline Numbers and Mobile Number
^[\d]{2,4}[- ]?[\d]{3}[- ]?[\d]{3,5}|([0])?(\+\d{1,2}[- ]?)?[789]{1}\d{9}$
Cant update the DB row. I was facing the same error. Now working with following code:
_context.Entry(_SendGridSetting).CurrentValues.SetValues(vm);
await _context.SaveChangesAsync();
Try this:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
Keystore name: "debug.keystore"
Keystore password: "android"
Key alias: "androiddebugkey"
Key password: "android"
I use this information and successfully generate Signed APK.
Featured graphics guidelines:
http://android-developers.blogspot.cz/2011/10/android-market-featured-image.html
List of graphics assets for your application:
http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=1078870
You could also check our blog post summarizing all graphical assets for both Android and iOS:
http://www.skoumal.net/en/how-to-prepare-graphical-design-for-mobile-app/
i must recommend a library: Moment
code:
var target12 = '2016-12-08 9:32:45 PM';
console.log(moment(target12, 'YYYY-MM-DD h:m:s A').format('YYYY-MM-DD HH:mm:ss'));
For now, semantically closest one would be a tuple with fixed number of elements.
typealias buffer = (
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode,
SKSpriteNode, SKSpriteNode, SKSpriteNode, SKSpriteNode)
But this is (1) very uncomfortable to use and (2) memory layout is undefined. (at least unknown to me)
There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.
The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.
I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
Kind of pythonic way:
c = [x for x in a if a.index(x) in b]
SELECT e1.emp_id, e1.emp_name, e1.mgr_id, e2.emp_name as manager_name
FROM employee e1
JOIN employee e2
ON e1.mgr_id = e2.emp_id
ORDER BY e1.emp_id
*Here is the link to SQL Fiddle with a working example. http://www.sqlfiddle.com/#!17/392b5/9
Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
Following up on Mark's answer, if you're not using Jupyter for some reason, e.g. you want to do some quick testing on the console, you can use the DataFrame.to_string
method, which works from -- at least -- Pandas 0.12 (2014) onwards.
import pandas as pd
matrix = [(1, 23, 45), (789, 1, 23), (45, 678, 90)]
df = pd.DataFrame(matrix, columns=list('abc'))
print(df.to_string())
# outputs:
# a b c
# 0 1 23 45
# 1 789 1 23
# 2 45 678 90
Maybe (from git commit
man page):
git commit --no-verify
-n
--no-verify
This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).
As commented by Blaise, -n
can have a different role for certain commands.
For instance, git push -n
is actually a dry-run push.
Only git push --no-verify
would skip the hook.
Note: Git 2.14.x/2.15 improves the --no-verify behavior:
See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster
-- in commit c3e034f, 23 Aug 2017)
commit
: skip discarding the index if there is nopre-commit
hook"
git commit
" used to discard the index and re-read from the filesystem just in case thepre-commit
hook has updated it in the middle; this has been optimized out when we know we do not run thepre-commit
hook.
Davi Lima points out in the comments the git cherry-pick
does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue
, after a merge conflict resolution.
Depending on
and if you want
You could use the read
command, followed by if ... then ... else
:
echo -n "Is this a good question (y/n)? "
read answer
# if echo "$answer" | grep -iq "^y" ;then
if [ "$answer" != "${answer#[Yy]}" ] ;then
echo Yes
else
echo No
fi
(Thanks to Adam Katz's comment: Replaced the test above with one that is more portable and avoids one fork:)
But if you don't want the user to have to hit Return, you could write:
(Edited: As @JonathanLeffler rightly suggest, saving stty's configuration could be better than simply force them to sane.)
echo -n "Is this a good question (y/n)? "
old_stty_cfg=$(stty -g)
stty raw -echo ; answer=$(head -c 1) ; stty $old_stty_cfg # Careful playing with stty
if echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
Note: This was tested under sh, bash, ksh, dash and busybox!
Same, but waiting explicitly for y or n:
#/bin/sh
echo -n "Is this a good question (y/n)? "
old_stty_cfg=$(stty -g)
stty raw -echo
answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )
stty $old_stty_cfg
if echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
There are many tools which were built using libncurses
, libgtk
, libqt
or other graphical libraries. For example, using whiptail
:
if whiptail --yesno "Is this a good question" 20 60 ;then
echo Yes
else
echo No
fi
Depending on your system, you may need to replace whiptail
with another similiar tool:
dialog --yesno "Is this a good question" 20 60 && echo Yes
gdialog --yesno "Is this a good question" 20 60 && echo Yes
kdialog --yesno "Is this a good question" 20 60 && echo Yes
where 20
is height of dialog box in number of lines and 60
is width of the dialog box. These tools all have near same syntax.
DIALOG=whiptail
if [ -x /usr/bin/gdialog ] ;then DIALOG=gdialog ; fi
if [ -x /usr/bin/xdialog ] ;then DIALOG=xdialog ; fi
...
$DIALOG --yesno ...
read -p "Is this a good question (y/n)? " answer
case ${answer:0:1} in
y|Y )
echo Yes
;;
* )
echo No
;;
esac
I prefer to use case
so I could even test for yes | ja | si | oui
if needed...
Under bash, we can specify the length of intended input for for the read
command:
read -n 1 -p "Is this a good question (y/n)? " answer
Under bash, read
command accepts a timeout parameter, which could be useful.
read -t 3 -n 1 -p "Is this a good question (y/n)? " answer
[ -z "$answer" ] && answer="Yes" # if 'yes' have to be default choice
More sophisticated dialog boxes, beyond simple yes - no
purposes:
dialog --menu "Is this a good question" 20 60 12 y Yes n No m Maybe
Progress bar:
dialog --gauge "Filling the tank" 20 60 0 < <(
for i in {1..100};do
printf "XXX\n%d\n%(%a %b %T)T progress: %d\nXXX\n" $i -1 $i
sleep .033
done
)
Little demo:
#!/bin/sh
while true ;do
[ -x "$(which ${DIALOG%% *})" ] || DIALOG=dialog
DIALOG=$($DIALOG --menu "Which tool for next run?" 20 60 12 2>&1 \
whiptail "dialog boxes from shell scripts" >/dev/tty \
dialog "dialog boxes from shell with ncurses" \
gdialog "dialog boxes from shell with Gtk" \
kdialog "dialog boxes from shell with Kde" ) || exit
clear;echo "Choosed: $DIALOG."
for i in `seq 1 100`;do
date +"`printf "XXX\n%d\n%%a %%b %%T progress: %d\nXXX\n" $i $i`"
sleep .0125
done | $DIALOG --gauge "Filling the tank" 20 60 0
$DIALOG --infobox "This is a simple info box\n\nNo action required" 20 60
sleep 3
if $DIALOG --yesno "Do you like this demo?" 20 60 ;then
AnsYesNo=Yes; else AnsYesNo=No; fi
AnsInput=$($DIALOG --inputbox "A text:" 20 60 "Text here..." 2>&1 >/dev/tty)
AnsPass=$($DIALOG --passwordbox "A secret:" 20 60 "First..." 2>&1 >/dev/tty)
$DIALOG --textbox /etc/motd 20 60
AnsCkLst=$($DIALOG --checklist "Check some..." 20 60 12 \
Correct "This demo is useful" off \
Fun "This demo is nice" off \
Strong "This demo is complex" on 2>&1 >/dev/tty)
AnsRadio=$($DIALOG --radiolist "I will:" 20 60 12 \
" -1" "Downgrade this answer" off \
" 0" "Not do anything" on \
" +1" "Upgrade this anser" off 2>&1 >/dev/tty)
out="Your answers:\nLike: $AnsYesNo\nInput: $AnsInput\nSecret: $AnsPass"
$DIALOG --msgbox "$out\nAttribs: $AnsCkLst\nNote: $AnsRadio" 20 60
done
More sample? Have a look at Using whiptail for choosing USB device and USB removable storage selector: USBKeyChooser
Example:
#!/bin/bash
set -i
HISTFILE=~/.myscript.history
history -c
history -r
myread() {
read -e -p '> ' $1
history -s ${!1}
}
trap 'history -a;exit' 0 1 2 3 6
while myread line;do
case ${line%% *} in
exit ) break ;;
* ) echo "Doing something with '$line'" ;;
esac
done
This will create a file .myscript.history
in your $HOME
directory, than you could use readline's history commands, like Up, Down, Ctrl+r and others.
char *a = "stack overflow";
char *b = "new string, it's real";
int d = strlen(a);
b = malloc(d * sizeof(char));
b = strcpy(b,a);
printf("%s %s\n", a, b);
Use:
dateTimePicker.Value.ToString("yyyy/MM/dd")
Refer to the following link:
http://www.vbdotnetforums.com/schedule-time/15001-datetimepicker-format.html
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
$('.mybtn').on('click',_x000D_
function(){_x000D_
$('#myinput').attr('value', '');_x000D_
}_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="mybtn">CLEAR</button>_x000D_
<input type="text" id="myinput" name="myinput" value="?????????">
_x000D_
This will avoid any collision and it will be fast until we use the shifting in calculations.
int k = key.length();
int sum = 0;
for(int i = 0 ; i < k-1 ; i++){
sum += key.charAt(i)<<(5*i);
}
<b>request.META</b><br>
{% for k_meta, v_meta in request.META.items %}
<code>{{ k_meta }}</code> : {{ v_meta }} <br>
{% endfor %}
I am using xampp 1.7.3. Using inspiration from here: xampp 1.7.3 upgrade broken virtual hosts access forbidden
INSTEAD OF add <Directory> .. </Directory>
in httpd-vhosts.conf, I add it in httpd.conf right after <Directory "D:/xampplite/cgi-bin"> .. </Directory>
.
Here is what I add in httpd.conf:
<Directory "D:/CofeeShop">
AllowOverride All
Options All
Order allow,deny
Allow from all
</Directory>
And here is what I add in httpd-vhosts.conf
<VirtualHost *:8001>
ServerAdmin [email protected]
DocumentRoot "D:/CofeeShop"
ServerName localhost:8001
</VirtualHost>
I also add Listen 8001
in httpd.conf to complete my setting.
Hope it helps
You probably don't want to pass the car
object as a parameter, try just passing car.id
. What do you get when you inspect(params)
after clicking "Add to cart"?
While CMS is correct that passing strings into the parse method is generally unsafe, the new ECMA-262 5th Edition (aka ES5) specification in section 15.9.4.2 suggests that Date.parse()
actually should handle ISO-formatted dates. The old specification made no such claim. Of course, old browsers and some current browsers still do not provide this ES5 functionality.
Your second example isn't wrong. It is the specified date in UTC, as implied by Date.prototype.toISOString()
, but is represented in your local timezone.
In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:
declare
myname varchar2(20) := 'tom';
begin
for result_cursor in (select * from mytable where first_name = myname) loop
dbms_output.put_line(result_cursor.first_name);
dbms_output.put_line(result_cursor.other_field);
end loop;
end;
If you have a query that returns exactly one row, then you can use the select...into...
syntax, e.g.:
declare
myname varchar2(20);
begin
select first_name into myname
from mytable
where person_id = 123;
end;
You could copy the XAMPP shortcut into "Local Disk C /users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up"...
This will make the control panel start up with the computer. Then if you were to select the configuration in the top right hand corner of the control panel you can make Apache and MySQL auto start... This is a quite long-winded get around, but it works for Windows 10.
A single listening port can accept more than one connection simultaneously.
There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.
Each TCP/IP packet has basically four fields for addressing. These are:
source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>
Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).
If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port
varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.
However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.
So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.
The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.
I've put up some algorithms to do image interpolation on html canvas pixel arrays that might be useful here:
https://web.archive.org/web/20170104190425/http://jsperf.com:80/pixel-interpolation/2
These can be copy/pasted and can be used inside of web workers to resize images (or any other operation that requires interpolation - I'm using them to defish images at the moment).
I haven't added the lanczos stuff above, so feel free to add that as a comparison if you'd like.
Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).
Jquery:
$(document).on('click','#test-element',function(){
alert("You clicked the element with and ID of 'test-element'");
});
As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element
but not for any that follow.
If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document
instead of test-element
. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different document
s and therefore you are clicking the document.
If neither of these are the answer, posting HTML will go a long way toward figuring it out.
Try this its working..
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '<?php echo base_url();?>student_ajax/insert',
data: $('form').serialize(),
success: function (response) {
alert('form was submitted');
}
error:function() {
alert('fail');
}
});
});
});
</script>
The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:
Converting an Object to a Map
The
new Map()
constructor accepts an iterable ofentries
. WithObject.entries
, you can easily convert fromObject
toMap
:const obj = { foo: 'bar', baz: 42 }; const map = new Map(Object.entries(obj)); console.log(map); // Map { foo: "bar", baz: 42 }
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.
It may seem obvious to some but some may simply copy/paste this code:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So what happens if I pass something like '/path/to/fileWithSecrets' to this script? The given script will happily send any file the webserver-user has access to.
Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?
You should use
$this->db->where('$accommodation >=', minvalue);
$this->db->where('$accommodation <=', maxvalue);
I'm not sure of syntax, so I beg your pardon if it's not correct.
Anyway BETWEEN
is implemented using >=min && <=max.
This is the meaning of my example.
EDITED:
Looking at this link I think you could write:
$this->db->where("$accommodation BETWEEN $minvalue AND $maxvalue");
Python is an interesting language in that while there is usually one (or two) "obvious" ways to accomplish any given task, flexibility still exists.
s = "string"
i = 0
print (s + repr(i))
The above code snippet is written in Python3 syntax but the parentheses after print were always allowed (optional) until version 3 made them mandatory.
Hope this helps.
Caitlin
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
Testing this one in 2020:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Verify yourself
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;_x000D_
const str = `some12*Nuts`;_x000D_
let m;_x000D_
_x000D_
if ((m = regex.exec(str)) !== null) {_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
An uninitialized Boolean
member (actually a reference to an object of type Boolean
) will have the default value of null
.
An uninitialized boolean
(primitive) member will have the default value of false
.
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.
If you need to get the work done inside Pg:
to_json(value)
https://www.postgresql.org/docs/9.3/static/functions-json.html#FUNCTIONS-JSON-TABLE
If you want input comma separated string as input & apply in in query in that then you can make Function like:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(MAX))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end;
You can use it like :
Declare @Values VARCHAR(MAX);
set @Values ='1,2,5,7,10';
Select * from DBTable
Where id in (select items from [dbo].[Split] (@Values, ',') )
Alternatively if you don't have comma-separated string as input, You can try Table variable
OR TableType
Or Temp table
like: INSERT using LIST into Stored Procedure
UPDATE : check Peter's answer below for a builtin solution :
This is a helper to set a persistent cookie:
import datetime
def set_cookie(response, key, value, days_expire=7):
if days_expire is None:
max_age = 365 * 24 * 60 * 60 # one year
else:
max_age = days_expire * 24 * 60 * 60
expires = datetime.datetime.strftime(
datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
"%a, %d-%b-%Y %H:%M:%S GMT",
)
response.set_cookie(
key,
value,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None,
)
Use the following code before sending a response.
def view(request):
response = HttpResponse("hello")
set_cookie(response, 'name', 'jujule')
return response
UPDATE : check Peter's answer below for a builtin solution :
With Spring Boot
its not necessary to have any config file like persistence.xml
. You can configure with annotations
Just configure your DB config for JPA in the
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
Then you can use CrudRepository
provided by Spring where you have standard CRUD
transaction methods. There you can also implement your own SQL's
like JPQL
.
@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
And if you still need to use the Entity Manager
you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
@PersistenceContext
private EntityManager em;
}
This should be in your pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
The Python runstats Module is for just this sort of thing. Install runstats from PyPI:
pip install runstats
Runstats summaries can produce the mean, variance, standard deviation, skewness, and kurtosis in a single pass of data. We can use this to create your "running" version.
from runstats import Statistics
stats = [Statistics() for num in range(len(data[0]))]
for row in data:
for index, val in enumerate(row):
stats[index].push(val)
for index, stat in enumerate(stats):
print 'Index', index, 'mean:', stat.mean()
print 'Index', index, 'standard deviation:', stat.stddev()
Statistics summaries are based on the Knuth and Welford method for computing standard deviation in one pass as described in the Art of Computer Programming, Vol 2, p. 232, 3rd edition. The benefit of this is numerically stable and accurate results.
Disclaimer: I am the author the Python runstats module.
There is a very good real-life example of the pattern - The car starter engine.
As drivers, we just turn the key on and the car get started. As simple as possible. Behind the scenes, many other car systems are involved (as battery, engine, fuel, etc.), in order the car to start successfully, but they are hidden behind the starter.
As you can see, the car starter is the Facade. It gives us easy to use interface, without worrying about the complexity of all other car systems.
Let's summarize:
The Facade pattern simplifies and hides the complexity of large code blocks or APIs, providing a cleaner, understandable and easy of use interface.
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
In Short,
Logins will have the access of the server.
and
Users will have the access of the database.
There is already an ISO standard for this; no need to invent your own scheme:
http://en.wikipedia.org/wiki/ISO_5218
Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.
In your module build.gradle file make sure you have the correct plugin set. it should be
apply plugin: 'android'
Yes. Use the ternary operator.
condition ? true_expression : false_expression;
Since the application path of a JAR
and an application running from inside an IDE
differs, I wrote the following code to consistently return the correct current directory:
import java.io.File;
import java.net.URISyntaxException;
public class ProgramDirectoryUtilities
{
private static String getJarName()
{
return new File(ProgramDirectoryUtilities.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getName();
}
private static boolean runningFromJAR()
{
String jarName = getJarName();
return jarName.contains(".jar");
}
public static String getProgramDirectory()
{
if (runningFromJAR())
{
return getCurrentJARDirectory();
} else
{
return getCurrentProjectDirectory();
}
}
private static String getCurrentProjectDirectory()
{
return new File("").getAbsolutePath();
}
private static String getCurrentJARDirectory()
{
try
{
return new File(ProgramDirectoryUtilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParent();
} catch (URISyntaxException exception)
{
exception.printStackTrace();
}
return null;
}
}
Simply call getProgramDirectory()
and you should be good either way.
You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.
If the type Player
has a default constructor, you can create a temporary object by doing Player()
, and that should work for your case:
vectorOfGamers.push_back(Player());
Using implicit wait works for me.
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
Refer to this answer Selenium c# Webdriver: Wait Until Element is Present
Using fairly simple code:
int i;
int value;
int n;
char ch;
/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
n = sscanf(argv[i], "%d%c", &value, &ch);
if (n != 1) {
/* sscanf didn't find a number to convert, so it wasn't a number */
}
else {
/* It was */
}
}
You can use Modernizr to detect simply IE or not IE, by checking for SVG SMIL animation support.
If you've included SMIL feature detection in your Modernizr setup, you can use a simple CSS approach, and target the .no-smil class that Modernizr applies to the html element:
html.no-smil {
/* IE/Edge specific styles go here - hide HTML5 content and show Flash content */
}
Alternatively, you could use Modernizr with a simple JavaScript approach, like so:
if ( Modernizr.smil ) {
/* set HTML5 content */
} else {
/* set IE/Edge/Flash content */
}
Bear in mind, IE/Edge might someday support SMIL, but there are currently no plans to do so.
For reference, here's a link to the SMIL compatibility chart at caniuse.com.
getDimensions(id) {
var obj = questions.filter(function(node) {
return node.id==id;
});
return obj;
}
coffee-script
can accomplish this with aplomb..
for x in [ 'a', 'b', 'c' ] then "#{x}" : true
[ { a: true }, { b: true }, { c: true } ]
A small combination from a couple of the examples below and created this simple piece:
function ajax(url, method, data, async)
{
method = typeof method !== 'undefined' ? method : 'GET';
async = typeof async !== 'undefined' ? async : false;
if (window.XMLHttpRequest)
{
var xhReq = new XMLHttpRequest();
}
else
{
var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if (method == 'POST')
{
xhReq.open(method, url, async);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(data);
}
else
{
if(typeof data !== 'undefined' && data !== null)
{
url = url+'?'+data;
}
xhReq.open(method, url, async);
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(null);
}
//var serverResponse = xhReq.responseText;
//alert(serverResponse);
}
// Example usage below (using a string query):
ajax('http://www.google.com');
ajax('http://www.google.com', 'POST', 'q=test');
OR if your parameters are object(s) - minor additional code adjustment:
var parameters = {
q: 'test'
}
var query = [];
for (var key in parameters)
{
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]));
}
ajax('http://www.google.com', 'POST', query.join('&'));
Both should be fully browser + version compatible.
# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled
rand_line_sampler() {
N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines
N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines
N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1
# vector to have the 0 (fail) with size of N_t_m_d
echo '0' > vector_0.temp
for i in $(seq 1 1 $N_t_m_d); do
echo "0" >> vector_0.temp
done
# vector to have the 1 (success) with size of desired number of lines
echo '1' > vector_1.temp
for i in $(seq 1 1 $N_d_m_1); do
echo "1" >> vector_1.temp
done
cat vector_1.temp vector_0.temp | shuf > rand_vector.temp
paste -d" " rand_vector.temp $1 |
awk '$1 != 0 {$1=""; print}' |
sed 's/^ *//' > sampled_file.txt # file with the sampled lines
rm vector_0.temp vector_1.temp rand_vector.temp
}
rand_line_sampler "parameter_1" "parameter_2"
I fixed this issue by installing jre
, I have jdk
already installed but jre
was not installed.
For me I had to put the whole interval in single quotes not just the value of the interval.
select id,
title,
created_at + interval '1 day' * claim_window as deadline from projects
Instead of
select id,
title,
created_at + interval '1' day * claim_window as deadline from projects
A hidden attribute is a boolean attribute (True/False). When this attribute is used on an element, it removes all relevance to that element. When a user views the html page, elements with the hidden attribute should not be visible.
Example:
<p hidden>You can't see this</p>
Aria-hidden attributes indicate that the element and ALL of its descendants are still visible in the browser, but will be invisible to accessibility tools, such as screen readers.
Example:
<p aria-hidden="true">You can't see this</p>
Take a look at this. It should answer all your questions.
Note: ARIA stands for Accessible Rich Internet Applications
Sources: Paciello Group
Here's the query example to check the existence of multiple fields:
{
"query": {
"bool": {
"filter": [
{
"exists": {
"field": "field_1"
}
},
{
"exists": {
"field": "field_2"
}
},
{
"exists": {
"field": "field_n"
}
}
]
}
}
}
The easiest method you can use is this:
System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
This will take care of everything you requested.
In some browsers:
flex:1;
does not equal flex:1 1 0;
flex:1;
= flex:1 1 0n;
(where n is a length unit).
The key point here is that flex-basis requires a length unit.
In Chrome for example flex:1
and flex:1 1 0
produce different results. In most circumstances it may appear that flex:1 1 0;
is working but let's examine what really happens:
Flex basis is ignored and only flex-grow and flex-shrink are applied.
flex:1 1 0;
= flex:1 1;
= flex:1;
This may at first glance appear ok however if the applied unit of the container is nested; expect the unexpected!
Try this example in CHROME
.Wrap{_x000D_
padding:10px;_x000D_
background: #333;_x000D_
}_x000D_
.Flex110x, .Flex1, .Flex110, .Wrap {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-direction: column;_x000D_
flex-direction: column;_x000D_
}_x000D_
.Flex110 {_x000D_
-webkit-flex: 1 1 0;_x000D_
flex: 1 1 0;_x000D_
}_x000D_
.Flex1 {_x000D_
-webkit-flex: 1;_x000D_
flex: 1;_x000D_
}_x000D_
.Flex110x{_x000D_
-webkit-flex: 1 1 0%;_x000D_
flex: 1 1 0%;_x000D_
}
_x000D_
FLEX 1 1 0_x000D_
<div class="Wrap">_x000D_
<div class="Flex110">_x000D_
<input type="submit" name="test1" value="TEST 1">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1_x000D_
<div class="Wrap">_x000D_
<div class="Flex1">_x000D_
<input type="submit" name="test2" value="TEST 2">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
FLEX 1 1 0%_x000D_
<div class="Wrap">_x000D_
<div class="Flex110x">_x000D_
<input type="submit" name="test3" value="TEST 3">_x000D_
</div>_x000D_
</div>
_x000D_
It should be noted that this fails because some browsers have failed to adhere to the specification.
Browsers that use the full flex specification:
Latest versions of Chrome seem to have finally rectified this issue but other browsers still have not.
Tested and working in Chrome Ver 74.
A solution without the Desktop environment is BrowserLauncher2. This solution is more general as on Linux, Desktop is not always available.
The lenghty answer is posted at https://stackoverflow.com/a/21676290/873282
You can create a custom class GradientView
:
Swift 5
class GradientView: UIView {
override open class var layerClass: AnyClass {
return CAGradientLayer.classForCoder()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let gradientLayer = layer as! CAGradientLayer
gradientLayer.colors = [UIColor.white.cgColor, UIColor.black.cgColor]
}
}
In the storyboard, set the class type to any view that you want to have gradient background:
This is better in the following ways:
CLayer
NSConstraint
as usual on the UIView
First of all, if you dont know, from Android Oreo i.e API level 26 it's compulsory that notifications are resgitered with a channel.
In that case many tutorials might confuse you because they show different example for notification above oreo and below.
So here is is a common code which runs on both above and below oreo:
String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";
NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setContentTitle(TitleTB.getText().toString())
.setContentText(MessageTB.getText().toString())
.build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
Date dd= new Date();
SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
String s=ft.format(dd);
return Integer.parseInt(s);
}
Video Tutorial: YOUTUBE VIDEO
In case you want to download this demo: GitHub Link
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
Yes, but the syntax is different than what you have
SELECT
<fields>
FROM
<table1>
LEFT JOIN <table2>
ON <criteria for join>
AND <other criteria for join>
LEFT JOIN <table3>
ON <criteria for join>
AND <other criteria for join>
I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):
Generate sertificate request:
Generate private key:
openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
Generate certificate request:
openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
Keep user.key
(and password) and send certificate request user.csr
to bank for my sertificate
Receive 2 certificate: my client root certificate clientId.crt
and bank root certificate: bank.crt
Create Java keystore (enter key password and set keystore password):
openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
Don't pay attention on output: unable to write 'random state'
. Java PKCS12 keystore.p12
created.
Add into keystore bank.crt
(for simplicity I've used one keystore):
keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
Check keystore certificates by:
keytool -list -keystore keystore.p12
Ready for Java code:) I've used Spring Boot RestTemplate
with add org.apache.httpcomponents.httpcore
dependency:
@Bean("sslRestTemplate")
public RestTemplate sslRestTemplate() throws Exception {
char[] storePassword = appProperties.getSslStorePassword().toCharArray();
URL keyStore = new URL(appProperties.getSslStore());
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(keyStore, storePassword)
// use storePassword twice (with key password do not work)!!
.loadKeyMaterial(keyStore, storePassword, storePassword)
.build();
// Solve "Certificate doesn't match any of the subject alternative names"
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
// restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
return restTemplate;
}
//Do this
int IS_NULL_PTR(char *k){
memset(&k, k, sizeof k);
if(k) { return 71; } ;
return 72;
}
int PRINT_PTR_SAFE(char *KR){
char *E=KR;;
if (IS_NULL_PTR(KR)==71){
printf("%s\r\n",KR);
} else {
printf("%s","(null)\r\n");
}
}
int main(int argc,char *argv[]){
int i=0;
char *A=malloc(sizeof(char)*9);
;strcpy(A,"hello world");
for (i=((int)(A))-10;i<1e+40;i++){
PRINT_PTR_SAFE(i);
}
}
//Then watch the show!
//Edit as you wish. Just credit me if you really want more of this.
Is something like this what you want to do?
$return_arr = array();
$fetch = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
It returns a json string in this format:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
OR something like this:
$year = date('Y');
$month = date('m');
$json_array = array(
//Each array below must be pulled from database
//1st record
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
//2nd record
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
);
echo json_encode($json_array);
Always use :::
. There are two reasons: efficiency and type safety.
Efficiency
x ::: y ::: z
is faster than x ++ y ++ z
, because :::
is right associative. x ::: y ::: z
is parsed as x ::: (y ::: z)
, which is algorithmically faster than (x ::: y) ::: z
(the latter requires O(|x|) more steps).
Type safety
With :::
you can only concatenate two List
s. With ++
you can append any collection to List
, which is terrible:
scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)
++
is also easy to mix up with +
:
scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab
another solution for variety sake..
public extension String {
public var validPhoneNumber:Bool {
let types:NSTextCheckingType = [.PhoneNumber]
guard let detector = try? NSDataDetector(types: types.rawValue) else { return false }
if let match = detector.matchesInString(self, options: [], range: NSMakeRange(0, characters.count)).first?.phoneNumber {
return match == self
}else{
return false
}
}
}
//and use like so:
if "16465551212".validPhoneNumber {
print("valid phone number")
}
when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.
The test code:
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int arraySz;
char *a;
unsigned int *q;
for (arraySz = 5; arraySz <= 64; arraySz++) {
printf ("%02d - ", arraySz);
a = new char[arraySz];
unsigned char *p = (unsigned char *) a;
q = (unsigned int *) (a - 4);
printf ("%02d\n", (*q));
delete[] (a);
}
}
on my machine dumps out:
05 - 19
06 - 19
07 - 19
08 - 19
09 - 19
10 - 19
11 - 19
12 - 19
13 - 27
14 - 27
15 - 27
16 - 27
17 - 27
18 - 27
19 - 27
20 - 27
21 - 35
22 - 35
23 - 35
24 - 35
25 - 35
26 - 35
27 - 35
28 - 35
29 - 43
30 - 43
31 - 43
32 - 43
33 - 43
34 - 43
35 - 43
36 - 43
37 - 51
38 - 51
39 - 51
40 - 51
41 - 51
42 - 51
43 - 51
44 - 51
45 - 59
46 - 59
47 - 59
48 - 59
49 - 59
50 - 59
51 - 59
52 - 59
53 - 67
54 - 67
55 - 67
56 - 67
57 - 67
58 - 67
59 - 67
60 - 67
61 - 75
62 - 75
63 - 75
64 - 75
I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.
The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
Just run the command:
php artisan migrate:refresh --seed
Assuming you're getting norm
from scipy.stats
, you probably just need to sort your list:
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial
And so I get:
you can use json_decode
function
foreach (json_decode($response) as $area)
{
print_r($area); // this is your area from json response
}
See this fiddle
Since macOS Big Sur and IntelliJ IDEA 2020.3.2 you can use "open projects in tabs on macOS Big Sur" feature. To use it, you have to enable this feature in your system settings:
System Preferences -> General -> Prefer tabs [always] when opening documents
After this step, when you will try to open second project in IntelliJ, choose New Window
(yes, New Window
, not This Window
).
It should result with opening new project in same window, but in the new card:
use stunnel on your server, to send with gmail. google it.
The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.
When page has no meta viewport tag:
When page has either of these two meta tags:
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">
<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">
With <meta name="viewport" content="width=device-width">
:
With <meta name="viewport" content="height=device-height">
:
With <meta name="viewport" content="height=device-height,width=device-width">
:
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">
With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">
If you absolutely position the elements inside the div, you can set the padding top and bottom to 50%.
So something like this:
#s7 {
position: relative;
width:100%;
padding: 50% 0;
margin:auto;
overflow: hidden;
z-index:1;
}
I assume you're talking about on the command-line - if it's in a script, then a new-line acts as a command delimiter.
On the command line, use a semi-colon ';'
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID
If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE()
as the default value for that column, and don't allow NULLs
To prevent unexpected margins and other browser-specific behavior in the future, I'd recommend to include reset.css in your stylesheets.
Be aware that you'll have to set the h[1..6] font size and weight to make headings look like headings again after that, and many other things.
I get this one all the time. It means that the user started to download a file, and then it either failed, or they cancelled it.
To reproduce the exception try do this yourself - however I'm unaware of any ways to prevent it (except for handling this specific exception only).
You need to decide what the best way forward is depending on your app.
If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:
PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}
In my case I chose the Force Update
checkbox while pushing. It worked like a charm.
You would use QMessageBox::question
for that.
Example in a hypothetical widget's slot:
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
// ...
void MyWidget::someSlot() {
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Test", "Quit?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
qDebug() << "Yes was clicked";
QApplication::quit();
} else {
qDebug() << "Yes was *not* clicked";
}
}
Should work on Qt 4 and 5, requires QT += widgets
on Qt 5, and CONFIG += console
on Win32 to see qDebug()
output.
See the StandardButton
enum to get a list of buttons you can use; the function returns the button that was clicked. You can set a default button with an extra argument (Qt "chooses a suitable default automatically" if you don't or specify QMessageBox::NoButton
).
Go into options. You most likely have 'Manual Sort" turned on. You need to go and change to radio button to "ascending > date". You can also right click the row/column, "more sorting options". It took me forever to find this solution...
irb> 'now is the time'[0...-4]
=> "now is the "
Scanner.next()
does not read a newline but reads the next token, delimited by whitespace (by default, if useDelimiter()
was not used to change the delimiter pattern). To read a line use Scanner.nextLine()
.
Once you read a single line you can use String.split(",")
to separate the line into fields. This enables identification of lines that do not consist of the required number of fields. Using useDelimiter(",");
would ignore the line-based structure of the file (each line consists of a list of fields separated by a comma). For example:
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine();
String[] fields = line.split(",");
if (fields.length >= 4) // At least one address specified.
{
for (String field: fields) System.out.print(field + "|");
System.out.println();
}
else
{
System.err.println("Invalid record: " + line);
}
}
As already mentioned, using a CSV library is recommended. For one, this (and useDelimiter(",")
solution) will not correctly handle quoted identifiers containing ,
characters.
Following example for getting first character from a string might help someone
string anyNameForString = "" + stringVariableName[0];
You can also try use "doctor" command. It will fix most cases.
npx @react-native-community/cli doctor
var x = $('#h_v').val();
alert(x);
I couldn't get .destroy() to work either so this is what I'm doing. The chart_parent div is where I want the canvas to show up. I need the canvas to resize each time, so this answer is an extension of the above one.
HTML:
<div class="main_section" >
<div id="chart_parent"></div>
<div id="legend"></div>
</div>
JQuery:
$('#chart').remove(); // this is my <canvas> element
$('#chart_parent').append('<label for = "chart">Total<br /><canvas class="chart" id="chart" width='+$('#chart_parent').width()+'><canvas></label>');
After editing @Wesley Rice's answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!
Read each line of a file in and operate on it line-by-line like this:
#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
echo "$line"
done < "$input"
This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!
Syntax: Read file line by line on a Bash Unix & Linux shell:
1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
2.while read -r line; do COMMAND; done < input.file
3. The-r
option passed to read command prevents backslash escapes from being interpreted.
4. AddIFS=
option before read command to prevent leading/trailing whitespace from being trimmed -
5.while IFS= read -r line; do COMMAND_on $line; done < input.file
And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? - here's my answer:
Note that FILES_STAGED
is a variable containing the absolute path to a file which contains a bunch of lines where each line is a relative path to a file I'd like to do git add
on. This code snippet is about to become part of the "eRCaGuy_dotfiles/useful_scripts/sync_git_repo_to_build_machine.sh" file in this project, to enable easy syncing of files in development from one PC (ex: a computer I code on) to another (ex: a more powerful computer I build on): https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.
while IFS= read -r line
do
echo " git add \"$line\""
git add "$line"
done < "$FILES_STAGED"
git add
on it: Is it possible to `git add` a list of files from a file?I get the same error when I specify my HTTPS URL as : https://www.mywebsite.com . However it works fine when I specify it without the three W's as : https://mywebsite.com .
Float to string - String.valueOf()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float - Float.parseFloat()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
Truncate drops the decimal point.
The short answer is primitives are data types, while references are pointers, which do not hold their values but point to their values and are used on/with objects.
Primatives:
boolean
character
byte
short
integer
long
float
double
Lots of good references that explain these basic concepts. http://www.javaforstudents.co.uk/Types
I found this one useful. For VB.NET developers:
Public Shared Function GetFromFileName(ByVal fileName As String) As String
Return GetFromExtension(Path.GetExtension(fileName).Remove(0, 1))
End Function
Public Shared Function GetFromExtension(ByVal extension As String) As String
If extension.StartsWith("."c) Then
extension = extension.Remove(0, 1)
End If
If MIMETypesDictionary.ContainsKey(extension) Then
Return MIMETypesDictionary(extension)
End If
Return "unknown/unknown"
End Function
Private Shared ReadOnly MIMETypesDictionary As New Dictionary(Of String, String)() From { _
{"ai", "application/postscript"}, _
{"aif", "audio/x-aiff"}, _
{"aifc", "audio/x-aiff"}, _
{"aiff", "audio/x-aiff"}, _
{"asc", "text/plain"}, _
{"atom", "application/atom+xml"}, _
{"au", "audio/basic"}, _
{"avi", "video/x-msvideo"}, _
{"bcpio", "application/x-bcpio"}, _
{"bin", "application/octet-stream"}, _
{"bmp", "image/bmp"}, _
{"cdf", "application/x-netcdf"}, _
{"cgm", "image/cgm"}, _
{"class", "application/octet-stream"}, _
{"cpio", "application/x-cpio"}, _
{"cpt", "application/mac-compactpro"}, _
{"csh", "application/x-csh"}, _
{"css", "text/css"}, _
{"dcr", "application/x-director"}, _
{"dif", "video/x-dv"}, _
{"dir", "application/x-director"}, _
{"djv", "image/vnd.djvu"}, _
{"djvu", "image/vnd.djvu"}, _
{"dll", "application/octet-stream"}, _
{"dmg", "application/octet-stream"}, _
{"dms", "application/octet-stream"}, _
{"doc", "application/msword"}, _
{"dtd", "application/xml-dtd"}, _
{"dv", "video/x-dv"}, _
{"dvi", "application/x-dvi"}, _
{"dxr", "application/x-director"}, _
{"eps", "application/postscript"}, _
{"etx", "text/x-setext"}, _
{"exe", "application/octet-stream"}, _
{"ez", "application/andrew-inset"}, _
{"gif", "image/gif"}, _
{"gram", "application/srgs"}, _
{"grxml", "application/srgs+xml"}, _
{"gtar", "application/x-gtar"}, _
{"hdf", "application/x-hdf"}, _
{"hqx", "application/mac-binhex40"}, _
{"htm", "text/html"}, _
{"html", "text/html"}, _
{"ice", "x-conference/x-cooltalk"}, _
{"ico", "image/x-icon"}, _
{"ics", "text/calendar"}, _
{"ief", "image/ief"}, _
{"ifb", "text/calendar"}, _
{"iges", "model/iges"}, _
{"igs", "model/iges"}, _
{"jnlp", "application/x-java-jnlp-file"}, _
{"jp2", "image/jp2"}, _
{"jpe", "image/jpeg"}, _
{"jpeg", "image/jpeg"}, _
{"jpg", "image/jpeg"}, _
{"js", "application/x-javascript"}, _
{"kar", "audio/midi"}, _
{"latex", "application/x-latex"}, _
{"lha", "application/octet-stream"}, _
{"lzh", "application/octet-stream"}, _
{"m3u", "audio/x-mpegurl"}, _
{"m4a", "audio/mp4a-latm"}, _
{"m4b", "audio/mp4a-latm"}, _
{"m4p", "audio/mp4a-latm"}, _
{"m4u", "video/vnd.mpegurl"}, _
{"m4v", "video/x-m4v"}, _
{"mac", "image/x-macpaint"}, _
{"man", "application/x-troff-man"}, _
{"mathml", "application/mathml+xml"}, _
{"me", "application/x-troff-me"}, _
{"mesh", "model/mesh"}, _
{"mid", "audio/midi"}, _
{"midi", "audio/midi"}, _
{"mif", "application/vnd.mif"}, _
{"mov", "video/quicktime"}, _
{"movie", "video/x-sgi-movie"}, _
{"mp2", "audio/mpeg"}, _
{"mp3", "audio/mpeg"}, _
{"mp4", "video/mp4"}, _
{"mpe", "video/mpeg"}, _
{"mpeg", "video/mpeg"}, _
{"mpg", "video/mpeg"}, _
{"mpga", "audio/mpeg"}, _
{"ms", "application/x-troff-ms"}, _
{"msh", "model/mesh"}, _
{"mxu", "video/vnd.mpegurl"}, _
{"nc", "application/x-netcdf"}, _
{"oda", "application/oda"}, _
{"ogg", "application/ogg"}, _
{"pbm", "image/x-portable-bitmap"}, _
{"pct", "image/pict"}, _
{"pdb", "chemical/x-pdb"}, _
{"pdf", "application/pdf"}, _
{"pgm", "image/x-portable-graymap"}, _
{"pgn", "application/x-chess-pgn"}, _
{"pic", "image/pict"}, _
{"pict", "image/pict"}, _
{"png", "image/png"}, _
{"pnm", "image/x-portable-anymap"}, _
{"pnt", "image/x-macpaint"}, _
{"pntg", "image/x-macpaint"}, _
{"ppm", "image/x-portable-pixmap"}, _
{"ppt", "application/vnd.ms-powerpoint"}, _
{"ps", "application/postscript"}, _
{"qt", "video/quicktime"}, _
{"qti", "image/x-quicktime"}, _
{"qtif", "image/x-quicktime"}, _
{"ra", "audio/x-pn-realaudio"}, _
{"ram", "audio/x-pn-realaudio"}, _
{"ras", "image/x-cmu-raster"}, _
{"rdf", "application/rdf+xml"}, _
{"rgb", "image/x-rgb"}, _
{"rm", "application/vnd.rn-realmedia"}, _
{"roff", "application/x-troff"}, _
{"rtf", "text/rtf"}, _
{"rtx", "text/richtext"}, _
{"sgm", "text/sgml"}, _
{"sgml", "text/sgml"}, _
{"sh", "application/x-sh"}, _
{"shar", "application/x-shar"}, _
{"silo", "model/mesh"}, _
{"sit", "application/x-stuffit"}, _
{"skd", "application/x-koan"}, _
{"skm", "application/x-koan"}, _
{"skp", "application/x-koan"}, _
{"skt", "application/x-koan"}, _
{"smi", "application/smil"}, _
{"smil", "application/smil"}, _
{"snd", "audio/basic"}, _
{"so", "application/octet-stream"}, _
{"spl", "application/x-futuresplash"}, _
{"src", "application/x-wais-source"}, _
{"sv4cpio", "application/x-sv4cpio"}, _
{"sv4crc", "application/x-sv4crc"}, _
{"svg", "image/svg+xml"}, _
{"swf", "application/x-shockwave-flash"}, _
{"t", "application/x-troff"}, _
{"tar", "application/x-tar"}, _
{"tcl", "application/x-tcl"}, _
{"tex", "application/x-tex"}, _
{"texi", "application/x-texinfo"}, _
{"texinfo", "application/x-texinfo"}, _
{"tif", "image/tiff"}, _
{"tiff", "image/tiff"}, _
{"tr", "application/x-troff"}, _
{"tsv", "text/tab-separated-values"}, _
{"txt", "text/plain"}, _
{"ustar", "application/x-ustar"}, _
{"vcd", "application/x-cdlink"}, _
{"vrml", "model/vrml"}, _
{"vxml", "application/voicexml+xml"}, _
{"wav", "audio/x-wav"}, _
{"wbmp", "image/vnd.wap.wbmp"}, _
{"wbmxl", "application/vnd.wap.wbxml"}, _
{"wml", "text/vnd.wap.wml"}, _
{"wmlc", "application/vnd.wap.wmlc"}, _
{"wmls", "text/vnd.wap.wmlscript"}, _
{"wmlsc", "application/vnd.wap.wmlscriptc"}, _
{"wrl", "model/vrml"}, _
{"xbm", "image/x-xbitmap"}, _
{"xht", "application/xhtml+xml"}, _
{"xhtml", "application/xhtml+xml"}, _
{"xls", "application/vnd.ms-excel"}, _
{"xml", "application/xml"}, _
{"xpm", "image/x-xpixmap"}, _
{"xsl", "application/xml"}, _
{"xslt", "application/xslt+xml"}, _
{"xul", "application/vnd.mozilla.xul+xml"}, _
{"xwd", "image/x-xwindowdump"}, _
{"xyz", "chemical/x-xyz"}, _
{"zip", "application/zip"} _
}
As others have pointed out, you cannot savely cast them, since a List<Object>
isn't a List<Customer>
. What you could do, is to define a view on the list that does in-place type checking. Using Google Collections that would be:
return Lists.transform(list, new Function<Object, Customer>() {
public Customer apply(Object from) {
if (from instanceof Customer) {
return (Customer)from;
}
return null; // or throw an exception, or do something else that makes sense.
}
});
HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.
I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:
final RequestConfig params = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
httpPost.setConfig(params);
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
For testing purposes I use the following:
//return assoc array when called from outside the class it will only contain public properties and values
var_dump(get_object_vars($obj));
If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let
, etc...) so you can live within the limits of what older browsers support.
Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.
Here's a version of your code written in ES5 syntax with the Bluebird promise library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>
<script>
'use strict';
var promise = new Promise(function(resolve) {
setTimeout(function() {
resolve("result");
}, 1000);
});
promise.then(function(result) {
alert("Fulfilled: " + result);
}, function(error) {
alert("Rejected: " + error);
});
</script>
cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:
$.ajax({
type: 'POST',
url:'url.do',
data: formData,
success: function(data, textStatus, request){
alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
According to docs the XMLHttpRequest object is available as of jQuery 1.4.
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.
private string[] GetAssembly(string[] assemblyNames)
{
string [] locations = new string[assemblyNames.Length];
for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)
{
locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
}
return locations;
}
For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/
If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.
It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.
I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/
Change the number of @grid-columns
. Then use -offset
. Changing the number of columns will allow you to control the amount of space between columns. E.g.
variables.less (approx line 294).
@grid-columns: 20;
someName.html
<div class="row">
<div class="col-md-4 col-md-offset-1">First column</div>
<div class="col-md-13 col-md-offset-1">Second column</div>
</div>
The problem I had was due to the fact that I was unknowingly editing the default values and not a new Tomcat instance at all. Click the plus sign at the top left part of the Run window and select Tomcat | Local from there.
you need to install and import reduce from functools
python package
I run vscode from my command line by navigating to the folder with the code and running
code .
If you do that all your bash
/zsh
variables are passed into vs code. You can update your .bashrc
/.zshrc
file or just do
export KEY=value
before opening it.
Also remember, when running on alternate ports, you need to specify the port on the URL:
There may be firewalls or proxy servers to consider depending on your environment.
Updated answer for April, 2020:
I've had a lot of success, recently, with cpp-httplib (both as a client and a server). It's mature and its approximate, single-threaded RPS is around 6k.
On more of the bleeding edge, there's a really promising framework, cpv-framework, that can get around 180k RPS on two cores (and will scale well with the number of cores because it's based on the seastar framework, which powers the fastest DBs on the planet, scylladb).
However, cpv-framework is still relatively immature; so, for most uses, I highly recommend cpp-httplib.
This recommendation replaces my previous answer (8 years ago).
For existing jobs you're editing, the JDK drop-down choice may not be available if you've just added a single JDK config in the 'Configure System' Jenkins settings.
However, it is available for new jobs.
Surprisingly, if you add a second JDK config, it becomes available in an existing job too.
This looks to me like a bug (tested in Jenkins ver. 1.629).
See a similar issue raised here: JDK selection is hidden even when a JDK is configured
How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull()
.
Just some testing about it:
public class PrimitiveTypesV2 {
public static void main (String[] args) {
Class typesList[] = {
Boolean.class , Byte.class, Character.class, Short.class, Integer.class,
Long.class, Float.class, Double.class, Boolean.TYPE, Byte.TYPE, Character.TYPE,
Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE
};
try {
for ( Class type : typesList ) {
if (type.isPrimitive()) {
System.out.println("Primitive type:\t" + type);
}
else {
boolean hasSize = false;
java.lang.reflect.Field fields[] = type.getFields();
for (int count=0; count<fields.length; count++) {
if (fields[count].getName().contains("SIZE")) hasSize = true;
}
if (hasSize) {
System.out.println("Bits size of type " + type + " :\t\t\t" + type.getField("SIZE").getInt(type) );
double value = type.getField("MIN_VALUE").getDouble(type);
long longVal = Math.round(value);
if ( (value - longVal) == 0) {
System.out.println("Min value for type " + type + " :\t\t" + longVal );
longVal = Math.round(type.getField("MAX_VALUE").getDouble(type));
System.out.println("Max value for type " + type + " :\t\t" + longVal );
}
else {
System.out.println("Min value for type " + type + " :\t\t" + value );
value = type.getField("MAX_VALUE").getDouble(type);
System.out.println("Max value for type " + type + " :\t\t" + value );
}
}
else {
System.out.println(type + "\t\t\t type without SIZE field.");
}
} // if not primitive
} // for typesList
} catch (Exception e) {e.printStackTrace();}
} // main
} // class PrimitiveTypes
If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:
class ExDateTime extends DateTime{
public static function createFromFormat($frmt,$time,$timezone=null){
$v = explode('.', phpversion());
if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
return parent::createFromFormat($frmt,$time,$timezone);
}
return new DateTime(date($frmt, strtotime($time)), $timezone);
}
}
and than you can use this class without problems:
ExDateTime::createFromFormat('d.m.Y G:i',$timevar);
Run this command
sudo pip install mysql-python;
now you can run your command.
python manage.py startapp filename;
When you invoke destroy
or destroy_all
on an ActiveRecord
object, the ActiveRecord
'destruction' process is initiated, it analyzes the class you're deleting, it determines what it should do for dependencies, runs through validations, etc.
When you invoke delete
or delete_all
on an object, ActiveRecord
merely tries to run the DELETE FROM tablename WHERE conditions
query against the db, performing no other ActiveRecord
-level tasks.
The best way to handle styling is by using classes with set of css properties.
example:
<Component className={this.getColor()} />
getColor() {
let class = "badge m2";
class += this.state.count===0 ? "warning" : danger;
return class;
}
Oneliner:
thefirst = [i for i in range(10) if i > 3][0]
If youre not sure that any element will be valid according to the criteria, you should enclose this with try/except
since that [0]
can raise an IndexError
.
Another solution would be using [class.active]
.
Example :
<ol class="breadcrumb">
<li [class.active]="step=='step1'" (click)="step='step1'">Step1</li>
</ol>
Using ternary operator:
message = "blah" if 'key1' in dict else "booh"
print(message)
you can use always:
'C:/mydir'
this works both in linux and windows. Other posibility is
'C:\\mydir'
if you have problems with some names you can also try raw string literals:
r'C:\mydir'
however best practice is to use the os.path
module functions that always select the correct configuration for your OS:
os.path.join(mydir, myfile)
From python 3.4 you can also use the pathlib module. This is equivelent to the above:
pathlib.Path(mydir, myfile)
or
pathlib.Path(mydir) / myfile
The general consensus is that you do not (should not) need to dispose of HttpClient.
Many people who are intimately involved in the way it works have stated this.
See Darrel Miller's blog post and a related SO post: HttpClient crawling results in memory leak for reference.
I'd also strongly suggest that you read the HttpClient chapter from Designing Evolvable Web APIs with ASP.NET for context on what is going on under the hood, particularly the "Lifecycle" section quoted here:
Although HttpClient does indirectly implement the IDisposable interface, the standard usage of HttpClient is not to dispose of it after every request. The HttpClient object is intended to live for as long as your application needs to make HTTP requests. Having an object exist across multiple requests enables a place for setting DefaultRequestHeaders and prevents you from having to re-specify things like CredentialCache and CookieContainer on every request as was necessary with HttpWebRequest.
Or even open up DotPeek.
From http://www.dba-oracle.com/t_isnumeric.htm
LENGTH(TRIM(TRANSLATE(, ' +-.0123456789', ' '))) is null
If there is anything left in the string after the TRIM it must be non-numeric characters.
Your code works for me on Chrome (5.0.375), and Safari (5.0). Doesn't loop on Firefox (3.6).
var song = new Audio("file");
song.loop = true;
document.body.appendChild(song);?
If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):
mokey 0 /home/jj33 > nslookup example.ad Server: 172.16.2.10 Address: 172.16.2.10#53 Non-authoritative answer: Name: example.ad Address: 172.16.6.2 Name: example.ad Address: 172.16.141.160 Name: example.ad Address: 172.16.7.9 Name: example.ad Address: 172.19.1.14 Name: example.ad Address: 172.19.1.3 Name: example.ad Address: 172.19.1.11 Name: example.ad Address: 172.16.3.2
Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.
I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
In the same location where the JVM's stdout is placed. If you have a Tomcat server, this will be the catalina_(date).out
file.
This does work for me. In below example, Alpha range can be a value between 0 to 255. Previously, I made a mistake by thinking that it must be a value of percentage.
Dim x as integer = 230
Panel1.BackColor = Color.FromArgb(x, Color.Blue)
Are you looking for the syntax to open them:
Dim wkbk As Workbook
Set wkbk = Workbooks.Open("C:\MyDirectory\mysheet.xlsx")
Then, you can use wkbk.Sheets(1).Range("3:3")
(or whatever you need)
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Use this to get the time in milliseconds (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970])
.
What if you want to do a comparison for values that ARE NOT equal? Just using a "NOT" in front of the previously mentioned comparisons does not work. The best I could come up with is:
(Field1 <> Field2) OR (NULLIF(Field1, Field2) IS NOT NULL) OR (NULLIF(Field2, Field1) IS NOT NULL)
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
Try this
var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);
var i = 0, req_index = "";
$.each(json, function(index, value){
if(index == 'key2'){
req_index = i;
}
i++;
});
alert(req_index);
object[] newarray = new object[oldarray.Length-1];
for(int x=0; x < array.Length; x++)
{
if(!(array[x] == value_of_array_to_delete))
// if(!(x == array_index_to_delete))
{
newarray[x] = oldarray[x];
}
}
There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using
canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);
These two link also help
http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o
http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html
you need to add Content-Length: 0
in your request header.
a very descriptive example of how to test is given here
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
Swift will not allow you to initialise super class with out initialising the properties, reverse of Obj C. So you have to initialise all properties before calling "super.init".
Please go to http://blog.scottlogic.com/2014/11/20/swift-initialisation.html. It gives a nice explanation to your problem.
You can use a DecimalFormat, or String.format("%.2f", a);
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.
It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
So, percent-encode the plus character and other special characters.
The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.
My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)
Your code for setting value for hidden input is correct. Here is the example. Maybe you have some conditions in your if
statements that are not allowing your scripts to execute.
For performance, especially when you're iterating over a large range, xrange()
is usually better. However, there are still a few cases why you might prefer range()
:
In python 3, range()
does what xrange()
used to do and xrange()
does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange()
.
range()
can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange()
has to reconstruct the integer object every time, but range()
will have real integer objects. (It will always perform worse in terms of memory however)
xrange()
isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.
[Edit] There are a couple of posts mentioning how range()
will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range()
and xrange()
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.
Super late to this thread but here goes.
TLDR; Add the following block in your AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
// HERE: replace "Verlag" with your font
[[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
....
}
A few ways you can do this outside of using a plugin like react-native-global-props
so Ill walk you though step by step.
First let's create a location for our assets. Let's make the following directory at our root.
```
ios/
static/
fonts/
```
Now let's add a "React Native" NPM in our package.json
"rnpm": {
"static": [
"./static/fonts/"
]
}
Now we can run "react-native link" to add our assets to our native apps.
That should add your font names into the projects .plist
(for VS code users run code ios/*/Info.plist
to confirm)
Here let's assume Verlag
is the font you added, it should look something like this:
<dict>
<plist>
.....
<key>UIAppFonts</key>
<array>
<string>Verlag Bold Italic.otf</string>
<string>Verlag Book Italic.otf</string>
<string>Verlag Light.otf</string>
<string>Verlag XLight Italic.otf</string>
<string>Verlag XLight.otf</string>
<string>Verlag-Black.otf</string>
<string>Verlag-BlackItalic.otf</string>
<string>Verlag-Bold.otf</string>
<string>Verlag-Book.otf</string>
<string>Verlag-LightItalic.otf</string>
</array>
....
</dict>
</plist>
Now that you mapped them, now let's make sure they are actually there and being loaded (this is also how you'd do it manually).
Go to "Build Phase" > "Copy Bundler Resource"
, If it didn't work you'll a manually add under them here.
First open your XCode logs, like:
Then you can add the following block in your AppDelegate.m
to log the names of the Fonts and the Font Family.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
.....
for (NSString* family in [UIFont familyNames])
{
NSLog(@"%@", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(@" %@", name);
}
}
...
}
Once you run you should find your fonts if loaded correctly, here we found ours in logs like this:
2018-05-07 10:57:04.194127-0700 MyApp[84024:1486266] Verlag
2018-05-07 10:57:04.194266-0700 MyApp[84024:1486266] Verlag-Book
2018-05-07 10:57:04.194401-0700 MyApp[84024:1486266] Verlag-BlackItalic
2018-05-07 10:57:04.194516-0700 MyApp[84024:1486266] Verlag-BoldItalic
2018-05-07 10:57:04.194616-0700 MyApp[84024:1486266] Verlag-XLight
2018-05-07 10:57:04.194737-0700 MyApp[84024:1486266] Verlag-Bold
2018-05-07 10:57:04.194833-0700 MyApp[84024:1486266] Verlag-Black
2018-05-07 10:57:04.194942-0700 MyApp[84024:1486266] Verlag-XLightItalic
2018-05-07 10:57:04.195170-0700 MyApp[84024:1486266] Verlag-LightItalic
2018-05-07 10:57:04.195327-0700 MyApp[84024:1486266] Verlag-BookItalic
2018-05-07 10:57:04.195510-0700 MyApp[84024:1486266] Verlag-Light
So now we know it loaded the Verlag
family and are the fonts inside that family
Verlag-Book
Verlag-BlackItalic
Verlag-BoldItalic
Verlag-XLight
Verlag-Bold
Verlag-Black
Verlag-XLightItalic
Verlag-LightItalic
Verlag-BookItalic
Verlag-Light
These are now the case sensitive names we can use in our font family we can use in our react native app.
Then to set a default font to add your font family name in your AppDelegate.m
with this line
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
// ADD THIS LINE (replace "Verlag" with your font)
[[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
....
}
Done.
The "call" solution has some problems.
It fails with many different contents, as the parameters of a CALL
are parsed twice by the parser.
These lines will produce more or less strange problems
one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty
the end
Therefore you shouldn't use the value of %%a
with a call, better move it to a variable and then call a function with only the name of the variable.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "myVar=%%a"
call :processLine myVar
)
goto :eof
:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
First things first, hover the mouse over the grey area below. Not part of the answer, but absolutely has to be said:
If you have a shell script that does "checkout, build, deploy" all by itself, then why are you using Jenkins? You are foregoing all the features of Jenkins that make it what it is. You might as well have a cron or an SVN post-commit hook call the script directly. Jenkins performing the SVN checkout itself is crucial. It allows the builds to be triggered only when there are changes (or on timer, or manual, if you prefer). It keeps track of changes between builds. It shows those changes, so you can see which build was for which set of changes. It emails committers when their changes caused successful or failed build (again, as configured as you prefer). It will email committers when their fixes fixed the failing build. And more and more. Jenkins archiving the artifacts also makes them available, per build, straight off Jenkins. While not as crucial as the SVN checkout, this is once again an integral part of what makes it Jenkins. Same with deploying. Unless you have a single environment, deployment usually happens to multiple environments. Jenkins can keep track of which environment a specific build (with specific set of SVN changes) is deployed it, through the use of Promotions. You are foregoing all of this. It sounds like you are told "you have to use Jenkins" but you don't really want to, and you are doing it just to get your bosses off your back, just to put a checkmark "yes, I've used Jenkins"
The short answer is: the exit code of last command of the Jenkin's Execute Shell build step is what determines the success/failure of the Build Step. 0
- success, anything else
- failure.
Note, this is determining the success/failure of the build step, not the whole job run. The success/failure of the whole job run can further be affected by multiple build steps, and post-build actions and plugins.
You've mentioned Build step 'Execute shell' marked build as failure
, so we will focus just on a single build step. If your Execute shell build step only has a single line that calls your shell script, then the exit code of your shell script will determine the success/failure of the build step. If you have more lines, after your shell script execution, then carefully review them, as they are the ones that could be causing failure.
Finally, have a read here Jenkins Build Script exits after Google Test execution. It is not directly related to your question, but note that part about Jenkins launching the Execute Shell build step, as a shell script with /bin/sh -xe
The -e
means that the shell script will exit with failure, even if just 1 command fails, even if you do error checking for that command (because the script exits before it gets to your error checking). This is contrary to normal execution of shell scripts, which usually print the error message for the failed command (or redirect it to null and handle it by other means), and continue.
To circumvent this, add set +e
to the top of your shell script.
Since you say your script does all it is supposed to do, chances are the failing command is somewhere at the end of the script. Maybe a final echo? Or copy of artifacts somewhere? Without seeing the full console output, we are just guessing.
Please post the job run's console output, and preferably the shell script itself too, and then we could tell you exactly which line is failing.
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
you can try this one
var obj = {
"a": "test1",
"b": "test2"
};
const findSpecificStr = (obj, str) => {
return Object.values(obj).includes(str);
}
findSpecificStr(obj, 'test1');
You should add a .gitignore file to your project and add /.idea
to it. You should add each directory / file in one line.
If you have an existing .gitignore file then you should simply add a new line to the file and put /.idea
to the new line.
After that run git rm -r --cached .idea
command.
If you faced an error you can run git rm -r -f --cached .idea
command. After all run git add .
and then git commit -m "Removed .idea directory and added a .gitignore file"
and finally push the changes by running git push
command.
s = "BINGO"
print(" ".join(s))
Should do it.
Yes, I'm answering my own question, but I haven't found it here yet and thought this was a rather slick thing:
...in VB.NET:
String.Join(",", CType(TargetArrayList.ToArray(Type.GetType("System.String")), String()))
...in C#
string.Join(",", (string[])TargetArrayList.ToArray(Type.GetType("System.String")))
The only "gotcha" to these is that the ArrayList must have the items stored as Strings if you're using Option Strict to make sure the conversion takes place properly.
EDIT: If you're using .net 2.0 or above, simply create a List(Of String) type object and you can get what you need with. Many thanks to Joel for bringing this up!
String.Join(",", TargetList.ToArray())
Highly recommend something more like this:
public class Person {
public string Name {get; set;}
public string Email {get; set;}
}
var people = new List<Person>();
Easier to read, easy to code.
I'm not sure if it will add deleted files, but git add .
from the root will add all untracked files.
.....
$("#testID #testID2").removeClass("test2").addClass("test3");
Because you have assigned an id to img too, you can simply do this too:
$("#testID2").removeClass("test2").addClass("test3");
And finally, you can do this too:
$("#testID img").removeClass("test2").addClass("test3");
from psutil import process_iter
from termcolor import colored
names = []
ids = []
x = 0
z = 0
k = 0
for proc in process_iter():
name = proc.name()
y = len(name)
if y>x:
x = y
if y<x:
k = y
id = proc.pid
names.insert(z, name)
ids.insert(z, id)
z += 1
print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
z = x
print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))
Dim distinctValues As List(Of Double) = (From r In _
DirectCast(DataTable.AsEnumerable(),IEnumerable(Of DataRow)) Where (Not r.IsNull("ColName")) _
Select r.Field(Of Double)("ColName")).Distinct().ToList()
Try this
val intent = Intent(this, Page2::class.java)
startActivity(intent)
clearInterval()
Note, you can start and pause your code with this capability. The name is a bit deceptive, since it says CLEAR, but it doesn't clear anything. It actually pauses.
Test with this code:
HTML:
<div id='count'>100</div>
<button id='start' onclick='start()'>Start</button>
<button id='stop' onclick='stop()'>Stop</button>
JavaScript:
let count;
function start(){
count = setInterval(timer,100) /// HERE WE RUN setInterval()
}
function timer(){
document.getElementById('count').innerText--;
}
function stop(){
clearInterval(count) /// here we PAUSE setInterval() with clearInterval() code
}
_x000D_
You should use an AsyncTask (or other way to perform a network operation on background).
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create and execute the download task
MyAsyncTask async = new MyAsyncTask();
async.execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
//execute on background (out of the UI thread)
protected Long doInBackground(URL... urls) {
DownloadFiles();
}
}
More info about AsyncTask on Android documentation
Hope it helps.
I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.
This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.
Let's first tackle "the elephant in the room" – that xpath is slower than css.
With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?
If there is a difference, it is in a fraction of a millisecond.
Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.
So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.
There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.
The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:
Here's the test code (python):
from selenium import webdriver
import timeit
if __name__ == '__main__':
xpath_locator = '//div[@class="button-section col-xs-12 row"]'
css_locator = 'div.button-section.col-xs-12.row'
repetitions = 1000
driver = webdriver.Chrome()
driver.get('https://www.browserstack.com/')
css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)",
number=repetitions, globals=globals())
xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)',
number=repetitions, globals=globals())
driver.quit()
print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, css_time, (css_time/repetitions)*1000))
print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, xpath_time, (xpath_time/repetitions)*1000))
For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.
The locators are:
Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".
The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).
Here's the output:
css total time 1000 repeats: 8.84s, per find: 8.84ms xpath total time for 1000 repeats: 8.52s, per find: 8.52ms
Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.
Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):
xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'
The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:
css total time 1000 repeats: 8.60s, per find: 8.60ms xpath total time for 1000 repeats: 8.75s, per find: 8.75ms
Diff of 0.15ms.
As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.
They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?
The same code as above, with these changes in:
The url is now http://the-internet.herokuapp.com/tables
; there are 2 tests.
The locators for the first one - "Finding Elements By ID and Class" - are:
css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"
And here is the outcome:
css total time 1000 repeats: 8.24s, per find: 8.24ms xpath total time for 1000 repeats: 8.45s, per find: 8.45ms
Diff of 0.2 milliseconds.
The "Finding Elements By Traversing":
css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"
The result:
css total time 1000 repeats: 9.29s, per find: 9.29ms xpath total time for 1000 repeats: 8.79s, per find: 8.79ms
This time it is 0.5 ms (in reverse, xpath turned out "faster" here).
So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.
So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.
Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.
Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"
With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.
Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4))
; embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).
The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.
Finally, again very subjective - which one to chose?
IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.
Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.
Short answer:
There is no difference in semantic.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
Further reading:
RequestMapping
can be used at class level:
This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
while GetMapping
only applies to method:
Annotation for mapping HTTP GET requests onto specific handler methods.
Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,
this.setState({
myArray: [...this.state.myArray, 'new value']
})