How to filter by string in JSONPath?
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
CSS: Control space between bullet and <li>
Use padding-left:1em; text-indent:-1em
for the <li>
tag.
Then, list-style-position: inside
for the <ul>
tag.
<ul style='list-style-position: inside;'>
<li style='padding-left: 1em; text-indent: -1em;'>Item 1</li>
</ul>
Enabling HTTPS on express.js
First, you need to create selfsigned.key and selfsigned.crt files.
Go to Create a Self-Signed SSL Certificate Or do following steps.
Go to the terminal and run the following command.
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt
- After that put the following information
- Country Name (2 letter code) [AU]: US
- State or Province Name (full name) [Some-State]: NY
- Locality Name (eg, city) []:NY
- Organization Name (eg, company) [Internet Widgits Pty Ltd]: xyz (Your - Organization)
- Organizational Unit Name (eg, section) []: xyz (Your Unit Name)
- Common Name (e.g. server FQDN or YOUR name) []: www.xyz.com (Your URL)
- Email Address []: Your email
After creation adds key & cert file in your code, and pass the options to the server.
const express = require('express');
const https = require('https');
const fs = require('fs');
const port = 3000;
var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
var options = {
key: key,
cert: cert
};
app = express()
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(options, app);
server.listen(port, () => {
console.log("server starting on port : " + port)
});
- Finally run your application using https.
More information https://github.com/sagardere/set-up-SSL-in-nodejs
How to add link to flash banner
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
Array versus linked-list
Only reason to use linked list is that insert the element is easy (removing also).
Disadvatige could be that pointers take a lot of space.
And about that coding is harder:
Usually you don't need code linked list (or only once) they are included in
STL
and it is not so complicated if you still have to do it.
python pandas remove duplicate columns
First step:- Read first row i.e all columns the remove all duplicate columns.
Second step:- Finally read only that columns.
cols = pd.read_csv("file.csv", header=None, nrows=1).iloc[0].drop_duplicates()
df = pd.read_csv("file.csv", usecols=cols)
Split a string into array in Perl
I found this one to be very simple!
my $line = "file1.gz file2.gz file3.gz";
my @abc = ($line =~ /(\w+[.]\w+)/g);
print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";
output:
file1.gz
file2.gz
file3.gz
Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.
How to reset a timer in C#?
You could write an extension method called Reset(), which
- calls Stop()-Start() for Timers.Timer and Forms.Timer
- calls Change for Threading.Timer
Bad operand type for unary +: 'str'
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
How do I add indices to MySQL tables?
A better option is to add the constraints directly during CREATE TABLE query (assuming you have the information about the tables)
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=INNODB;
How to initialize HashSet values by construction?
This is an elegant solution:
public static final <T> Set<T> makeSet(@SuppressWarnings("unchecked") T... o) {
return new HashSet<T>() {
private static final long serialVersionUID = -3634958843858172518L;
{
for (T x : o)
add(x);
}
};
}
Reading from memory stream to string
If you'd checked the results of stream.Read
, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;
.) However, it's easier to just call ToArray
:
settingsString = LocalEncoding.GetString(stream.ToArray());
(You'll need to change the type of stream
from Stream
to MemoryStream
, but that's okay as it's in the same method where you create it.)
Alternatively - and even more simply - just use StringWriter
instead of StreamWriter
. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.
I'm concerned by the way you're just catching Exception
and assuming that it means something harmless, by the way - without even logging anything. Note that using
statements are generally cleaner than writing explicit finally
blocks.
Export data from Chrome developer tool
I was trying to copy the size data measured from Chrome Network and stumbled on this post. I just found an easier way to "export" the data out to excel which is to copy the table and paste to excel.
The trick is click Control + A (select all) and once the entire table will be highlighted, paste it to Microsoft Excel. The only issue is if there are too many fields, not all rows are copied and you might have to copy and paste several times.
UPDATED: I found that copying the data only works when I turn off the filter options (the funnel-looking button above the table). – bendur
How to give a delay in loop execution using Qt
EDIT (removed wrong solution).
EDIT (to add this other option):
Another way to use it would be subclass QThread since it has protected *sleep methods.
QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);
Here's the code to create your own *sleep method.
#include <QThread>
class Sleeper : public QThread
{
public:
static void usleep(unsigned long usecs){QThread::usleep(usecs);}
static void msleep(unsigned long msecs){QThread::msleep(msecs);}
static void sleep(unsigned long secs){QThread::sleep(secs);}
};
and you call it by doing this:
Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);
This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.
Leaflet changing Marker color
In R, use the addAwesomeMarkers() function. Sample code producing red marker:
leaflet() %>%
addTiles() %>%
addAwesomeMarkers(lng = -77.03654, lat = 38.8973, icon = awesomeIcons(icon = 'ion-ionic', library = 'ion', markerColor = 'red'))
Link for ion icons: http://ionicons.com/
Font Awesome & Unicode
You can also use the FontAwesome icon with the CSS3 pseudo selector as shown below.
Ensure to set the font-family to FontAwesome as shown below:
table.dataTable thead th.sorting:after {font-family: FontAwesome;}
To get the above working, you must do the following:
- Download the FontAwesome css library here FontAwesome v4.7.0
- Extract from the zip file and include into your app root folder, the two folders as shown below:
- Reference only the css folder in the
<head></head>
section of your app as shown below:
angular2 submit form by pressing enter without submit button
Maybe you add keypress
or keydown
to the input fields and assign the event to function that will do the submit when enter is clicked.
Your template would look like this
<form (keydown)="keyDownFunction($event)">
<input type="text" />
</form
And you function inside the your class would look like this
keyDownFunction(event) {
if (event.keyCode === 13) {
alert('you just pressed the enter key');
// rest of your code
}
}
How to determine the number of days in a month in SQL Server?
You need to create a function, but it is for your own convenience. It works perfect and I never encountered any faulty computations using this function.
CREATE FUNCTION [dbo].[get_days](@date datetime)
RETURNS int
AS
BEGIN
SET @date = DATEADD(MONTH, 1, @date)
DECLARE @result int = (select DAY(DATEADD(DAY, -DAY(@date), @date)))
RETURN @result
END
How it works: subtracting the date's day number from the date itself gives you the last day of previous month. So, you need to add one month to the given date, subtract the day number and get the day component of the result.
C++: Where to initialize variables in constructor
See Should my constructors use "initialization lists" or "assignment"?
Briefly: in your specific case, it does not change anything. But:
- for class/struct members with constructors, it may be more efficient to use option 1.
- only option 1 allows you to initialize reference members.
- only option 1 allows you to initialize const members
- only option 1 allows you to initialize base classes using their constructor
- only option 2 allows you to initialize array or structs that do not have a constructor.
My guess for why option 2 is more common is that option 1 is not well-known, neither are its advantages. Option 2's syntax feels more natural to the new C++ programmer.
Why boolean in Java takes only true or false? Why not 1 or 0 also?
One thing that other answers haven't pointed out is that one advantage of not treating integers as truth values is that it avoids this C / C++ bug syndrome:
int i = 0;
if (i = 1) {
print("the sky is falling!\n");
}
In C / C++, the mistaken use of =
rather than ==
causes the condition to unexpectedly evaluate to "true" and update i
as an accidental side-effect.
In Java, that is a compilation error, because the value of the assigment i = 1
has type int
and a boolean
is required at that point. The only case where you'd get into trouble in Java is if you write lame code like this:
boolean ok = false;
if (ok = true) { // bug and lame style
print("the sky is falling!\n");
}
... which anyone with an ounce of "good taste" would write as ...
boolean ok = false;
if (ok) {
print("the sky is falling!\n");
}
Alternative to iFrames with HTML5
I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.
Changes to the parent site are picked up every 5 minutes.
var iframeReplacement = require('node-iframe-replacement');
// add iframe replacement to express as middleware (adds res.merge method)
app.use(iframeReplacement);
// create a regular express route
app.get('/', function(req, res){
// respond to this request with our fake-news content embedded within the BBC News home page
res.merge('fake-news', {
// external url to fetch
sourceUrl: 'http://www.bbc.co.uk/news',
// css selector to inject our content into
sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
// pass a function here to intercept the source html prior to merging
transform: null
});
});
The source contains a working example of injecting content into the BBC News home page.
How to set some xlim and ylim in Seaborn lmplot facetgrid
The lmplot
function returns a FacetGrid
instance. This object has a method called set
, to which you can pass key=value
pairs and they will be set on each Axes object in the grid.
Secondly, you can set only one side of an Axes limit in matplotlib by passing None
for the value you want to remain as the default.
Putting these together, we have:
g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))
How to deal with SettingWithCopyWarning in Pandas
Pandas dataframe copy warning
When you go and do something like this:
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
pandas.ix
in this case returns a new, stand alone dataframe.
Any values you decide to change in this dataframe, will not change the original dataframe.
This is what pandas tries to warn you about.
Why .ix
is a bad idea
The .ix
object tries to do more than one thing, and for anyone who has read anything about clean code, this is a strong smell.
Given this dataframe:
df = pd.DataFrame({"a": [1,2,3,4], "b": [1,1,2,2]})
Two behaviors:
dfcopy = df.ix[:,["a"]]
dfcopy.a.ix[0] = 2
Behavior one: dfcopy
is now a stand alone dataframe. Changing it will not change df
df.ix[0, "a"] = 3
Behavior two: This changes the original dataframe.
Use .loc
instead
The pandas developers recognized that the .ix
object was quite smelly[speculatively] and thus created two new objects which helps in the accession and assignment of data. (The other being .iloc
)
.loc
is faster, because it does not try to create a copy of the data.
.loc
is meant to modify your existing dataframe inplace, which is more memory efficient.
.loc
is predictable, it has one behavior.
The solution
What you are doing in your code example is loading a big file with lots of columns, then modifying it to be smaller.
The pd.read_csv
function can help you out with a lot of this and also make the loading of the file a lot faster.
So instead of doing this
quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
Do this
columns = ['STK', 'TPrice', 'TPCLOSE', 'TOpen', 'THigh', 'TLow', 'TVol', 'TAmt', 'TDate', 'TTime']
df = pd.read_csv(StringIO(str_of_all), sep=',', usecols=[0,3,2,1,4,5,8,9,30,31])
df.columns = columns
This will only read the columns you are interested in, and name them properly. No need for using the evil .ix
object to do magical stuff.
How to execute logic on Optional if not present?
First of all, your dao.find()
should either return an Optional<Obj>
or you will have to create one.
e.g.
Optional<Obj> = dao.find();
or you can do it yourself like:
Optional<Obj> = Optional.ofNullable(dao.find());
this one will return Optional<Obj>
if present or Optional.empty()
if not present.
So now let's get to the solution,
public Obj getObjectFromDB() {
return Optional.ofNullable(dao.find()).flatMap(ob -> {
ob.setAvailable(true);
return Optional.of(ob);
}).orElseGet(() -> {
logger.fatal("Object not available");
return null;
});
}
This is the one liner you're looking for :)
Concatenating variables in Bash
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
explanations
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
another solution
(less portable : require
bash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
See http://mywiki.wooledge.org/BashFAQ/013
How to change Screen buffer size in Windows Command Prompt from batch script
I know the question is 9 years old, but maybe for someone it will be interested furthermore. According to the question, to change the buffer size only, it can be used Powershell.
The shortest command with Powershell is:
powershell -command "&{(get-host).ui.rawui.buffersize=@{width=155;height=999};}"
Replace the values of width and height with your wanted values.
But supposedly the reason of your question is to modify the size of command line window without reducing of the buffer size. For that you can use the following command:
start /b powershell -command "&{$w=(get-host).ui.rawui;$w.buffersize=@{width=177;height=999};$w.windowsize=@{width=155;height=55};}"
There you can modify the size of buffer and window independly. To avoid an error message, consider that the values of buffersize must be bigger or equal to the values of windowsize.
Additional implemented is the start /b
command. The Powershell command sometimes takes a few seconds to execute. With this additional command, Powershell runs parallel and does not significantly delay the processing of the following commands.
Use StringFormat to add a string to a WPF XAML binding
In xaml
<TextBlock Text="{Binding CelsiusTemp}" />
In ViewModel
, this way setting the value also works:
public string CelsiusTemp
{
get { return string.Format("{0}°C", _CelsiusTemp); }
set
{
value = value.Replace("°C", "");
_CelsiusTemp = value;
}
}
How to mark a method as obsolete or deprecated?
The shortest way is by adding the ObsoleteAttribute
as an attribute to the method. Make sure to include an appropriate explanation:
[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }
You can also cause the compilation to fail, treating the usage of the method as an error instead of warning, if the method is called from somewhere in code like this:
[Obsolete("Method1 is deprecated, please use Method2 instead.", true)]
Accessing post variables using Java Servlets
For getting all post parameters there is Map which contains request param name as key and param value as key.
Map params = servReq.getParameterMap();
And to get parameters with known name normal
String userId=servReq.getParameter("user_id");
Best method to download image from url in Android
I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.
InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
Create array of regex matches
Set<String> keyList = new HashSet();
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher matcher = regex.matcher("Content goes here");
while(matcher.find()) {
keyList.add(matcher.group(1));
}
return keyList;
How to create an empty file with Ansible?
Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:
Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state
(I spent a few minutes working this out, so hopefully this speeds someone else up),
- stat:
path: "/etc/nologin"
register: p
- name: create fake 'nologin' shell
file:
path: "/etc/nologin"
owner: root
group: sys
mode: 0555
state: '{{ "file" if p.stat.exists else "touch" }}'
Nginx: stat() failed (13: permission denied)
You can also add which user will run the nginx. In the nginx.conf file, make the following changes:
user root;
You can add the above line as the first line in your nginx conf.
You can write the name of any user who has the permission to write in that directory.
Are dictionaries ordered in Python 3.6+?
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
Eclipse shows errors but I can't find them
For me, this happens with Maven and Eclipse/STS whenever I update my IDE or import an existing Maven project. Go to the "Problems tab" (Window -> Show View -> Problems) and see what it says. Recently, the problems tab showed Project configuration is not up-to-date ...
and suggested that I use Maven to update my project configuration, and this solved the "red X" problem. To do this, in the "Project Explorer" view, trigger the context menu and select Maven -> Update Project, as seen in this screenshot snippet:
How do I make a JAR from a .java file?
Although it is not recommended method but still it works
[7-Zip Software is needed]
Procedure to get jar from java files:
place all java files in one folder
right click on the folder
now click on Add to archive
you will get something like shown below
now just change zip
to jar
and click on ok
Sticky Header after scrolling down
I suggest to use sticky js it's have best option ever i have seen. nothing to do just ad this js on you
https://raw.githubusercontent.com/garand/sticky/master/jquery.sticky.js
and use below code :
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
Its git repo: https://github.com/garand/sticky
How can I show and hide elements based on selected option with jQuery?
To show the div while selecting one value and hide while selecting another value from dropdown box: -
$('#yourselectorid').bind('change', function(event) {
var i= $('#yourselectorid').val();
if(i=="sometext") // equal to a selection option
{
$('#divid').show();
}
elseif(i=="othertext")
{
$('#divid').hide(); // hide the first one
$('#divid2').show(); // show the other one
}
});
Count number of occurrences of a pattern in a file (even on same line)
To count all occurrences, use -o
. Try this:
echo afoobarfoobar | grep -o foo | wc -l
And man grep
of course (:
Update
Some suggest to use just grep -co foo
instead of grep -o foo | wc -l
.
Don't.
This shortcut won't work in all cases. Man page says:
-c print a count of matching lines
Difference in these approaches is illustrated below:
1.
$ echo afoobarfoobar | grep -oc foo
1
As soon as the match is found in the line (a{foo}barfoobar
) the searching stops. Only one line was checked and it matched, so the output is 1
. Actually -o
is ignored here and you could just use grep -c
instead.
2.
$ echo afoobarfoobar | grep -o foo
foo
foo
$ echo afoobarfoobar | grep -o foo | wc -l
2
Two matches are found in the line (a{foo}bar{foo}bar
) because we explicitly asked to find every occurrence (-o
). Every occurence is printed on a separate line, and wc -l
just counts the number of lines in the output.
Only read selected columns
Say the data are in file data.txt
, you can use the colClasses
argument of read.table()
to skip columns. Here the data in the first 7 columns are "integer"
and we set the remaining 6 columns to "NULL"
indicating they should be skipped
> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)),
+ header = TRUE)
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
Change "integer"
to one of the accepted types as detailed in ?read.table
depending on the real type of data.
data.txt
looks like this:
$ cat data.txt
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29
and was created by using
write.table(dat, file = "data.txt", row.names = FALSE)
where dat
is
dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L,
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L,
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L,
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))
If the number of columns is not known beforehand, the utility function count.fields
will read through the file and count the number of fields in each line.
## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))
javascript regex for special characters
How about this:-
var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,}$/;
It will allow a minimum of 6 characters including numbers, alphabets, and special characters
How to list only files and not directories of a directory Bash?
Listing content of some directory, without subdirectories
I like using ls
options, for sample:
-l
use a long listing format
-t
sort by modification time, newest first
-r
reverse order while sorting
-F
, --classify
append indicator (one of */=>@|) to entries
-h
, --human-readable
with -l and -s, print sizes like 1K 234M 2G etc...
Sometime --color
and all others. (See ls --help
)
Listing everything but folders
This will show files, symlinks, devices, pipe, sockets etc.
so
find /some/path -maxdepth 1 ! -type d
could be sorted by date easily:
find /some/path -maxdepth 1 ! -type d -exec ls -hltrF {} +
Listing files only:
or
find /some/path -maxdepth 1 -type f
sorted by size:
find /some/path -maxdepth 1 -type f -exec ls -lSF --color {} +
Prevent listing of hidden entries:
To not show hidden entries, where name begin by a dot, you could add ! -name '.*'
:
find /some/path -maxdepth 1 ! -type d ! -name '.*' -exec ls -hltrF {} +
Then
You could replace /some/path
by .
to list for current directory or ..
for parent directory.
How can I change the font size using seaborn FacetGrid?
You can scale up the fonts in your call to sns.set()
.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))
sns.set(font_scale=5) # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))
Currency format for display
This kind of functionality is built in.
When using a decimal you can use a format string "C" or "c".
decimal dec = 123.00M;
string uk = dec.ToString("C", new CultureInfo("en-GB")); // uk holds "£123.00"
string us = dec.ToString("C", new CultureInfo("en-US")); // us holds "$123.00"
How to get row index number in R?
I'm interpreting your question to be about getting row numbers.
- You can try
as.numeric(rownames(df))
if you haven't set the rownames. Otherwise use a sequence of 1:nrow(df)
.
- The
which()
function converts a TRUE/FALSE row index into row numbers.
Removing duplicate objects with Underscore for Javascript
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
Lets break this down. First lets group the array items by their stringified value
var grouped = _.groupBy(foo, function (f) {
return JSON.stringify(f);
});
grouped
looks like:
{
'{ "a" : "1" }' = [ { "a" : "1" } { "a" : "1" } ],
'{ "b" : "2" }' = [ { "b" : "2" } ]
}
Then lets grab the first element from each group
var bar = _.map(grouped, function(gr)
return gr[0];
});
bar
looks like:
[ { "a" : "1" }, { "b" : "2" } ]
Put it all together:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
Accessing all items in the JToken
In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);
foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
Console.WriteLine(sub_obj.Key);
}
I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).
I think the parsing works according to the following principles:
Every object is abstracted as a JToken
Cast to JObject where you expect a Dictionary
Cast to JValue if the JToken represents a terminal node and is a value
Cast to JArray if its an array
JValue.Value gives you the .NET type you need
How do I get a file name from a full path with PHP?
I've done this using the function PATHINFO
which creates an array with the parts of the path for you to use! For example, you can do this:
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/usr/admin/config
test.xml
xml
test
The use of this function has been available since PHP 5.2.0!
Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:
$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];
Do you (really) write exception safe code?
Leaving aside the confusion between SEH and C++ exceptions, you need to be aware that exceptions can be thrown at any time, and write your code with that in mind. The need for exception-safety is largely what drives the use of RAII, smart pointers, and other modern C++ techniques.
If you follow the well-established patterns, writing exception-safe code is not particularly hard, and in fact it's easier than writing code that handles error returns properly in all cases.
How to add headers to OkHttp request interceptor?
Faced similar issue with other samples, this Kotlin class worked for me
import okhttp3.Interceptor
import okhttp3.Response
class CustomInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain) : Response {
val request = chain.request().newBuilder()
.header("x-custom-header", "my-value")
.build()
return chain.proceed(request)
}
}
how to set auto increment column with sql developer
I found this post, which looks a bit old, but I figured I'd update everyone on my new findings.
I am using Oracle SQL Developer 4.0.2.15 on Windows.
Our database is Oracle 10g (version 10.2.0.1) running on Windows.
To make a column auto-increment in Oracle -
- Open up the database connection in the Connections tab
- Expand the Tables section, and right click the table that has the column you want to change to auto-increment, and select Edit...
- Choose the Columns section, and select the column you want to auto-increment (Primary Key column)
- Next, click the "Identity Column" section below the list of columns, and change type from None to "Column Sequence"
- Leave the default settings (or change the names of the sequence and trigger if you'd prefer) and then click OK
Your id column (primary key) will now auto-increment, but the sequence will be starting at 1.
If you need to increment the id to a certain point, you'll have to run a few alter statements against the sequence.
This post has some more details and how to overcome this.
I found the solution here
Hibernate dialect for Oracle Database 11g?
We had a problem with the (deprecated) dialect org.hibernate.dialect.Oracledialect
and Oracle 11g database using hibernate.hbm2ddl.auto = validate
mode.
With this dialect Hibernate was unable to found the sequences (because the implementation of the getQuerySequencesString()
method, that returns this query:
"select sequence_name from user_sequences;"
for which the execution returns an empty result from database).
Using the dialect org.hibernate.dialect.Oracle9iDialect
, or greater, solves the problem, due to a different implementation of getQuerySequencesString()
method:
"select sequence_name from all_sequences union select synonym_name from all_synonyms us, all_sequences asq where asq.sequence_name = us.table_name and asq.sequence_owner = us.table_owner;"
that returns all the sequences if executed, instead.
How to count frequency of characters in a string?
The shorted possible code using a HashMap. (With no forceful line saves)
private static Map<Character, Integer> findCharacterFrequency(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
/* Using getOrDefault(), since Java1.8 */
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
return map;
}
Difference between Static methods and Instance methods
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
What does this thread join code mean?
When thread tA call tB.join() its causes not only waits for tB to die or tA be interrupted itself but create happens-before relation between last statement in tB and next statement after tB.join() in tA thread.
All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
It means program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
threadB.join();
while (true)
System.out.print(sharedVar);
}
}
Always print
>> 1111111111111111111111111 ...
But program
class App {
// shared, not synchronized variable = bad practice
static int sharedVar = 0;
public static void main(String[] args) throws Exception {
Thread threadB = new Thread(() -> {sharedVar = 1;});
threadB.start();
// threadB.join(); COMMENT JOIN
while (true)
System.out.print(sharedVar);
}
}
Can print not only
>> 0000000000 ... 000000111111111111111111111111 ...
But
>> 00000000000000000000000000000000000000000000 ...
Always only '0'.
Because Java Memory Model don't require 'transfering' new value of 'sharedVar' from threadB to main thread without heppens-before relation (thread start, thread join, usage of 'synchonized' keyword, usage of AtomicXXX variables, etc).
HttpClient.GetAsync(...) never returns when using await/async
These two schools are not really excluding.
Here is the scenario where you simply have to use
Task.Run(() => AsyncOperation()).Wait();
or something like
AsyncContext.Run(AsyncOperation);
I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.
The library I need is async as it is expected to run async.
The only option. Run it as a normal sync call.
I am just saying to each its own.
How to tell if browser/tab is active
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
How to make a countdown timer in Android?
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Refer to this link.
Creating a blocking Queue<T> in .NET?
That looks very unsafe (very little synchronization); how about something like:
class SizeQueue<T>
{
private readonly Queue<T> queue = new Queue<T>();
private readonly int maxSize;
public SizeQueue(int maxSize) { this.maxSize = maxSize; }
public void Enqueue(T item)
{
lock (queue)
{
while (queue.Count >= maxSize)
{
Monitor.Wait(queue);
}
queue.Enqueue(item);
if (queue.Count == 1)
{
// wake up any blocked dequeue
Monitor.PulseAll(queue);
}
}
}
public T Dequeue()
{
lock (queue)
{
while (queue.Count == 0)
{
Monitor.Wait(queue);
}
T item = queue.Dequeue();
if (queue.Count == maxSize - 1)
{
// wake up any blocked enqueue
Monitor.PulseAll(queue);
}
return item;
}
}
}
(edit)
In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):
bool closing;
public void Close()
{
lock(queue)
{
closing = true;
Monitor.PulseAll(queue);
}
}
public bool TryDequeue(out T value)
{
lock (queue)
{
while (queue.Count == 0)
{
if (closing)
{
value = default(T);
return false;
}
Monitor.Wait(queue);
}
value = queue.Dequeue();
if (queue.Count == maxSize - 1)
{
// wake up any blocked enqueue
Monitor.PulseAll(queue);
}
return true;
}
}
Cast from VARCHAR to INT - MySQL
As described in Cast Functions and Operators:
The type for the result can be one of the following values:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
Therefore, you should use:
SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT
Difference between & and && in Java?
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).
if( x != null && x.equals("*BINGO*") {
then do something with x...
}
Pass element ID to Javascript function
The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.
This worked:
validateSelectizeDropdown('#PartCondition')
This did not:
validateSelectizeDropdown("#PartCondition")
And the function:
function validateSelectizeDropdown(name) {
if ($(name).val() === "") {
//do something
}
}
How to align absolutely positioned element to center?
Have you tried using?:
left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */
Not sure if it'll work, but it's worth a try...
Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...
How to uncommit my last commit in Git
If you aren't totally sure what you mean by "uncommit" and don't know if you want to use git reset
, please see "Revert to a previous Git commit".
If you're trying to understand git reset
better, please see "Can you explain what "git reset" does in plain English?".
If you know you want to use git reset
, it still depends what you mean by "uncommit". If all you want to do is undo the act of committing, leaving everything else intact, use:
git reset --soft HEAD^
If you want to undo the act of committing and everything you'd staged, but leave the work tree (your files intact):
git reset HEAD^
And if you actually want to completely undo it, throwing away all uncommitted changes, resetting everything to the previous commit (as the original question asked):
git reset --hard HEAD^
The original question also asked it's HEAD^
not HEAD
. HEAD
refers to the current commit - generally, the tip of the currently checked-out branch. The ^
is a notation which can be attached to any commit specifier, and means "the commit before". So, HEAD^
is the commit before the current one, just as master^
is the commit before the tip of the master branch.
Here's the portion of the git-rev-parse documentation describing all of the ways to specify commits (^
is just a basic one among many).
target="_blank" vs. target="_new"
TL;DR
USE _blank
The target attribute specifies where to open the linked document.
USAGE: target="xyz" [don't forget double quotes]
_blank Opens the linked document in a new window or tab
_self Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top Opens the linked document in the full body of the window
framename Opens the linked document in a named frame
SINCE "_new" is not any of these IT WILL COME UNDER "framename" so if a user re-clicks on that hyperlink it will not open a new tab instead update the existing tab. Whereas in _blank if user clicks twice then 2 new tabs open.
MsgBox "" vs MsgBox() in VBScript
A callable piece of code (routine) can be a Sub (called for a side effect/what it
does) or a Function (called for its return value) or a mixture of both. As the docs
for MsgBox
Displays a message in a dialog box, waits for the user to click a
button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
indicate, this routine is of the third kind.
The syntactical rules of VBScript are simple:
Use parameter list () when calling a (routine as a) Function
If you want to display a message to the user and need to know the user's
reponse:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.
Don't use parameter list () when calling a (routine as a) Sub
If you want to display a message to the user and are not interested
in the response:
MsgBox "Hello World!", 65, "MsgBox Example"
This beautiful simplicity is messed up by:
The design flaw of using () for parameter lists and to force call-by-value
semantics
>> Sub S(n) : n = n + 1 : End Sub
>> n = 1
>> S n
>> WScript.Echo n
>> S (n)
>> WScript.Echo n
>>
2
2
S (n) does not mean "call S with n", but "call S with a copy of n's value".
Programmers seeing that
>> s = "value"
>> MsgBox(s)
'works' are in for a suprise when they try:
>> MsgBox(s, 65, "MsgBox Example")
>>
Error Number: 1044
Error Description: Cannot use parentheses when calling a Sub
The compiler's leniency with regard to empty () in a Sub call. The 'pure'
Sub Randomize (called for the side effect of setting the random seed) can
be called by
Randomize()
although the () can neither mean "give me your return value) nor "pass
something by value". A bit more strictness here would force prgrammers to
be aware of the difference in
Randomize n
and
Randomize (n)
The Call statement that allows parameter list () in Sub calls:
s = "value"
Call MsgBox(s, 65, "MsgBox Example")
which further encourage programmers to use () without thinking.
(Based on What do you mean "cannot use parentheses?")
1064 error in CREATE TABLE ... TYPE=MYISAM
A complementary note about CREATE TABLE .. TYPE=""
syntax in SQL dump files
TLDR: If you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
Long story
As it was said by others, the TYPE
argument to CREATE TABLE
has been deprecated for a long time in MySQL. mysqldump
correctly uses the ENGINE
argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40
in versions of mysqldump
up to 5.7).
However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ...
command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE
will actually produce outdated syntax, including the TYPE
argument, if the sqlmode
variable is set to MYSQL40
or MYSQL323
.
Therefore, if you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
These sqlmode
s basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40
, MYSQL323
and several other similar sqlmode
s have themselves been deprecated and are not supported in MySQL 8.0 and higher.
If your server is still configured with these sqlmode
s and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode
locally for that program, by executing SET SESSION sql_mode = 'MYSQL40';
immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.
A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode
(that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode
(as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.
Getting indices of True values in a boolean list
You can use filter for it:
filter(lambda x: self.states[x], range(len(self.states)))
The range
here enumerates elements of your list and since we want only those where self.states
is True
, we are applying a filter based on this condition.
For Python > 3.0:
list(filter(lambda x: self.states[x], range(len(self.states))))
Can't find SDK folder inside Android studio path, and SDK manager not opening
If SDK folder is present in system, one can find in C:\Users\%USERNAME%\AppData\Local\Android
If Android/SDK folder is not found
Once done with downloading and installing Android Studio, you need to launch studio.
On launching Android studio for the first time, we get option to download further more components, in that we have SDK.
On downloading components one can find SDK under Appdata (C:\Users\%USERNAME%\AppData\Local\Android)
Creating a byte array from a stream
It really depends on whether or not you can trust s.Length
. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
With .NET 4 and above, I'd use Stream.CopyTo
, which is basically equivalent to the loop in my code - create the MemoryStream
, call stream.CopyTo(ms)
and then return ms.ToArray()
. Job done.
I should perhaps explain why my answer is longer than the others. Stream.Read
doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read
will keep going until the end of the stream or your specified size, but you still have to know the size to start with.
The above method will keep reading (and copying into a MemoryStream
) until it runs out of data. It then asks the MemoryStream
to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream
to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer
) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.
See this article for more info (and an alternative implementation).
Pandas dataframe get first row of each group
I'd suggest to use .nth(0)
rather than .first()
if you need to get the first row.
The difference between them is how they handle NaNs, so .nth(0)
will return the first row of group no matter what are the values in this row, while .first()
will eventually return the first not NaN
value in each column.
E.g. if your dataset is :
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4],
'value' : ["first","second","third", np.NaN,
"second","first","second","third",
"fourth","first","second"]})
>>> df.groupby('id').nth(0)
value
id
1 first
2 NaN
3 first
4 first
And
>>> df.groupby('id').first()
value
id
1 first
2 second
3 first
4 first
Capitalize words in string
Use This:
_x000D_
_x000D_
String.prototype.toTitleCase = function() {_x000D_
return this.charAt(0).toUpperCase() + this.slice(1);_x000D_
}_x000D_
_x000D_
let str = 'text';_x000D_
document.querySelector('#demo').innerText = str.toTitleCase();
_x000D_
<div class = "app">_x000D_
<p id = "demo"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_
contenteditable change events
Check this idea out.
http://pastie.org/1096892
I think it's close. HTML 5 really needs to add the change event to the spec. The only problem is that the callback function evaluates if (before == $(this).html()) before the content is actually updated in $(this).html(). setTimeout don't work, and it's sad. Let me know what you think.
Failed to find 'ANDROID_HOME' environment variable
In Windows, If you are running this command from VS code terminal and Even after setting up all the environment variable (i.e.build-tools, platform-tools, tools) it is not working trying running the same command from external cmd terminal.
In my case even after starting a new VS code terminal, it was not able to take the updated Environment path.
It worked when I ran the same command from Windows cmd.
Use FontAwesome or Glyphicons with css :before
This approach should be avoided. The default value for vertical-align
is baseline
. Changing the font-family of only the pseudo element will result in elements with differing fonts. Different fonts can have different font metrics and different baselines. In order for different baselines to align, the overall height of the element would have to increase. See this effect in action.
It is always better to have one element per font icon.
PHP cURL HTTP CODE return 0
Another reason for PHP to return http code 0 is timeout.
In my case, I had the following configuration:
curl_setopt($http, CURLOPT_TIMEOUT_MS,500);
It turned out that the request to the endpoint I was pointing to always took more than 500 ms, always timing out and always returning http code 0.
If you remove this setting (CURLOPT_TIMEOUT_MS) or put a higher value (in my case 5000), you'll get the actual http code, in my case a 200 (as expected).
See https://www.php.net/manual/en/function.curl-setopt.php
trigger click event from angularjs directive
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
What are alternatives to ExtJS?
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Leading client widget libraries
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework
with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Wikipedia • GitHub • Themes • Demos • Desktop widgets • SO
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
Full-stack frameworks
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
CSS libraries + minimal widgets
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Bootstrap
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Libraries using HTML Canvas
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
- Zebra - demos
No longer developed as of Dec 2014
- Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
- echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
- ampleSDK
- Simpler widgets livepipe.net
- JxLib
- rialto
- Simple UI kit
- Prototype-ui
Other lists
open the file upload dialogue box onclick the image
<!-- File input (hidden) -->
<input type="file" id="file1" style="display:none"/>
<!-- Trigger button -->
<a href="javascript:void(0)" onClick="openSelect('#file1')">
<script type="text/javascript">
function openSelect(file)
{
$(file).trigger('click');
}
</script>
What are rvalues, lvalues, xvalues, glvalues, and prvalues?
What are these new categories of expressions?
The FCD (n3092) has an excellent description:
— An lvalue (so called, historically, because lvalues could appear on the
left-hand side of an assignment
expression) designates a function or
an object. [ Example: If E is an
expression of pointer type, then
*E is an lvalue expression referring to the object or function to which E
points. As another example, the result
of calling a function whose return
type is an lvalue reference is an
lvalue. —end example ]
— An xvalue (an
“eXpiring” value) also refers to an
object, usually near the end of its
lifetime (so that its resources may be
moved, for example). An xvalue is the
result of certain kinds of expressions
involving rvalue references (8.3.2). [
Example: The result of calling a
function whose return type is an
rvalue reference is an xvalue. —end
example ]
— A glvalue (“generalized”
lvalue) is an lvalue or an xvalue.
—
An rvalue (so called, historically,
because rvalues could appear on the
right-hand side of an assignment
expressions) is an xvalue, a temporary
object (12.2) or subobject thereof, or
a value that is not associated with an
object.
— A prvalue (“pure” rvalue) is
an rvalue that is not an xvalue. [
Example: The result of calling a
function whose return type is not a
reference is a prvalue. The value of a
literal such as 12, 7.3e5, or true is
also a prvalue. —end example ]
Every
expression belongs to exactly one of
the fundamental classifications in
this taxonomy: lvalue, xvalue, or
prvalue. This property of an
expression is called its value
category. [ Note: The discussion of
each built-in operator in Clause 5
indicates the category of the value it
yields and the value categories of the
operands it expects. For example, the
built-in assignment operators expect
that the left operand is an lvalue and
that the right operand is a prvalue
and yield an lvalue as the result.
User-defined operators are functions,
and the categories of values they
expect and yield are determined by
their parameter and return types. —end
note
I suggest you read the entire section 3.10 Lvalues and rvalues though.
How do these new categories relate to the existing rvalue and lvalue categories?
Again:
Are the rvalue and lvalue categories in C++0x the same as they are in C++03?
The semantics of rvalues has evolved particularly with the introduction of move semantics.
Why are these new categories needed?
So that move construction/assignment could be defined and supported.
Row count where data exists
Assuming that your Sheet1
is not necessary active you would need to use this improved code of yours:
i = ActiveWorkbook.Worksheets("Sheet1").Range("A2" , Worksheets("Sheet1").Range("A2").End(xlDown)).Rows.Count
Look into full worksheet reference for second argument for Range(arg1, arg2)
which important in this situation.
How to negate specific word in regex?
If it's truly a word, bar
that you don't want to match, then:
^(?!.*\bbar\b).*$
The above will match any string that does not contain bar
that is on a word boundary, that is to say, separated from non-word characters. However, the period/dot (.
) used in the above pattern will not match newline characters unless the correct regex flag is used:
^(?s)(?!.*\bbar\b).*$
Alternatively:
^(?!.*\bbar\b)[\s\S]*$
Instead of using any special flag, we are looking for any character that is either white space or non-white space. That should cover every character.
But what if we would like to match words that might contain bar
, but just not the specific word bar
?
(?!\bbar\b)\b\[A-Za-z-]*bar[a-z-]*\b
(?!\bbar\b)
Assert that the next input is not bar
on a word boundary.
\b\[A-Za-z-]*bar[a-z-]*\b
Matches any word on a word boundary that contains bar
.
See Regex Demo
Equivalent of jQuery .hide() to set visibility: hidden
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
In Python How can I declare a Dynamic Array
Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:
# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]
# Create an array of objects:
MyList = [ {} for x in range( n ) ]
I love this because you can specify the contents and size dynamically, in one line!
One more for the road:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
Using Cookie in Asp.Net Mvc 4
userCookie.Expires.AddDays(365);
This line of code doesn't do anything. It is the equivalent of:
DateTime temp = userCookie.Expires.AddDays(365);
//do nothing with temp
You probably want
userCookie.Expires = DateTime.Now.AddDays(365);
How to deploy a Java Web Application (.war) on tomcat?
- copy the .war file in the
webapps
folder
- upload the file using the manager application -
http://host:port/manager
. You will have to setup some users beforehand.
- (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in
webapps/webappname
Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:
After you have it deployed (check the /logs
dir for any problems), it should be accessible via: http://host:port/yourwebappname/
. So in your case, one of those:
http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/
If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)
Dilemma: when to use Fragments vs Activities:
Don't forget that an activity is application's block/component which can be shared and started through Intent! So each activity in your application should solve only one kind of task. If you have only one task in your application then I think you need only one activity and many fragments if needed. Of course you can reuse fragments in future activities which solve another tasks. This approach will be clear and logical separation of tasks. And you no need to maintain one activity with different intent filter parameters for different sets of fragments. You define tasks at the design stage of the development process based on requirements.
SQL JOIN - WHERE clause vs. ON clause
The way I do it is:
Always put the join conditions in the ON
clause if you are doing an INNER JOIN
. So, do not add any WHERE conditions to the ON clause, put them in the WHERE
clause.
If you are doing a LEFT JOIN
, add any WHERE conditions to the ON
clause for the table in the right side of the join. This is a must, because adding a WHERE clause that references the right side of the join will convert the join to an INNER JOIN.
The exception is when you are looking for the records that are not in a particular table. You would add the reference to a unique identifier (that is not ever NULL) in the RIGHT JOIN table to the WHERE clause this way: WHERE t2.idfield IS NULL
. So, the only time you should reference a table on the right side of the join is to find those records which are not in the table.
How to declare 2D array in bash
2D array can be achieved in bash by declaring 1D array and then elements can be accessed using (r * col_size) + c)
. Below logic delcares 1D array (str_2d_arr
) and prints as 2D array.
col_size=3
str_2d_arr=()
str_2d_arr+=('abc' '200' 'xyz')
str_2d_arr+=('def' '300' 'ccc')
str_2d_arr+=('aaa' '400' 'ddd')
echo "Print 2D array"
col_count=0
for elem in ${str_2d_arr[@]}; do
if [ ${col_count} -eq ${col_size} ]; then
echo ""
col_count=0
fi
echo -e "$elem \c"
((col_count++))
done
echo ""
Output is
Print 2D array
abc 200 xyz
def 300 ccc
aaa 400 ddd
Below logic is very useful to get each row from the above declared 1D array str_2d_arr
.
# Get nth row and update to 2nd arg
get_row_n()
{
row=$1
local -n a=$2
start_idx=$((row * col_size))
for ((i = 0; i < ${col_size}; i++)); do
idx=$((start_idx + i))
a+=(${str_2d_arr[${idx}]})
done
}
arr=()
get_row_n 0 arr
echo "Row 0"
for e in ${arr[@]}; do
echo -e "$e \c"
done
echo ""
Output is
Row 0
abc 200 xyz
How to copy multiple files in one layer using a Dockerfile?
It might be worth mentioning that you can also create a .dockerignore
file, to exclude the files that you don't want to copy:
https://docs.docker.com/engine/reference/builder/#dockerignore-file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.
Add Keypair to existing EC2 instance
For Elasticbeanstalk environments, you can apply a key-value pair to a running instance like this:
- Create a key-value pair from EC2 -> Key Pairs (Under NETWORK & SECURITY tab)
- Go to Elasticbeanstalk and click on your application
- Go to configuration page and modify security settings
- Choose your EC2 key pair and click Apply
- Click confirm to confirm the update. It will terminate the environment and apply the key value to your environment.
Converting String to Cstring in C++
string name;
char *c_string;
getline(cin, name);
c_string = new char[name.length()];
for (int index = 0; index < name.length(); index++){
c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
// the char array
I know this is not the predefined method but thought it may be useful to someone nevertheless.
Request exceeded the limit of 10 internal redirects due to probable configuration error
This error occurred to me when I was debugging the PHP header() function:
header('Location: /aaa/bbb/ccc'); // error
If I use a relative path it works:
header('Location: aaa/bbb/ccc'); // success, but not what I wanted
However when I use an absolute path like /aaa/bbb/ccc
, it gives the exact error:
Request exceeded the limit of 10 internal redirects due to probable
configuration error. Use 'LimitInternalRecursion' to increase the
limit if necessary. Use 'LogLevel debug' to get a backtrace.
It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():
header('Location: /aaa/bbb/ccc');
exit;
And it works properly.
How to change target build on Android project?
There are three ways to resolve this issue.
Right click the project and click "Properties".
Then select "Android" from left. You can then select the target version
from right side.
Right Click on Project and select "run as" , then a drop down list will be open.
Select "Run Configuration" from Drop Down list.Then a form will be open ,
Select "Target" tab from "Form" and also select Android Version Api ,
On which you want to execute your application, it is a fastest way to check
your application on different Target Version.
Edit the following elements in the AndroidManifest.xml file
xml:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
Formatting doubles for output in C#
Digits after decimal point
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"
Thousands separator
String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"
Zero
Following code shows how can be formatted a zero (of double type).
String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""
Align numbers with spaces
String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "
Custom formatting for negative numbers and zero
String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"
Some funny examples
String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);
endsWith in JavaScript
Just another quick alternative that worked like a charm for me, using regex:
// Would be equivalent to:
// "Hello World!".endsWith("World!")
"Hello World!".match("World!$") != null
How to examine processes in OS X's Terminal?
if you are using ps, you can check the manual
man ps
there is a list of keywords allowing you to build what you need. for example to show, userid / processid / percent cpu / percent memory / work queue / command :
ps -e -o "uid pid pcpu pmem wq comm"
-e is similar to -A (all inclusive; your processes and others), and -o is to force a format.
if you are looking for a specific uid, you can chain it using awk or grep such as :
ps -e -o "uid pid pcpu pmem wq comm" | grep 501
this should (almost) show only for userid 501. try it.
Storing money in a decimal column - what precision and scale?
I would think that for a large part your or your client's requirements should dictate what precision and scale to use. For example, for the e-commerce website I am working on that deals with money in GBP only, I have been required to keep it to Decimal( 6, 2 ).
How to wait for async method to complete?
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}
How to install wget in macOS?
For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.
Install Xcode
Build OpenSSL
Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.
Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".
Build wget
Go to wget directory, configure:
./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
wget should configure and found OpenSSL, then make:
make
wget made out. Install wget:
make install
Or just copy wget to where you want.
Configure cert
You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:
New way:
If you machine doesn't have "/usr/local/ssl/" dir, first make it.
ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
Old way:
security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
Then put cert.pem to: "/usr/local/ssl/cert.pem"
DONE: It should be all right now.
Excel: Searching for multiple terms in a cell
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
Print second last column/field in awk
Did you tried to start from right to left by using the rev command ?
In this case you just need to print the 2nd column:
seq 12 | xargs -n5 | rev | awk '{ print $2}' | rev
4
9
11
How can I split a shell command over multiple lines when using an IF statement?
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
How to sum array of numbers in Ruby?
If you feel golfy, you can do
eval([123,321,12389]*?+)
This will create a string "123+321+12389" and then use function eval to do the sum. This is only for golfing purpose, you should not use it in proper code.
Comment out HTML and PHP together
I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.
Wrap all the content in this:
<?php
if(false){
?>
Here goes your PHP + HTML code
<?php
}
?>
Calling constructors in c++ without new
The compiler may well optimize the second form into the first form, but it doesn't have to.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Output from gcc 4.4:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor
UnicodeEncodeError: 'latin-1' codec can't encode character
Use the below snippet to convert the text from Latin to English
import unicodedata
def strip_accents(text):
return "".join(char for char in
unicodedata.normalize('NFKD', text)
if unicodedata.category(char) != 'Mn')
strip_accents('áéíñóúü')
output:
'aeinouu'
SQL Server stored procedure parameters
Why would you pass a parameter to a stored procedure that doesn't use it?
It sounds to me like you might be better of building dynamic SQL statements and then executing them. What you are trying to do with the SP won't work, and even if you could change what you are doing in such a way to accommodate varying numbers of parameters, you would then essentially be using dynamically generated SQL you are defeating the purpose of having/using a SP in the first place. SP's have a role, but there are not the solution in all cases.
HTML5 : Iframe No scrolling?
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
Repair all tables in one go
for plesk hosts, one of these should do: (both do the same)
mysqlrepair -uadmin -p$(cat /etc/psa/.psa.shadow) -A
# or
mysqlcheck -uadmin -p$(cat /etc/psa/.psa.shadow) --repair -A
SQLite error 'attempt to write a readonly database' during insert?
I got this error when I tried to write to a database on an Android system.
Apparently sqlite3 not only needs write permissions to the database file and the containing directory (as @austin-hyde already said in his answer) but also the environment variable TMPDIR
has to point to a (possibly writable) directory.
On my Android system I set it to TMPDIR="/data/local/tmp"
and now my script runs as expected :)
Edit:
If you can't set environment variables you can use one of the other methods listed here: https://www.sqlite.org/tempfiles.html#temporary_file_storage_locations
like PRAGMA temp_store_directory = 'directory-name';
How to make html <select> element look like "disabled", but pass values?
If you can supply a default value for your selects, then you can use the same approach for unchecked check boxes which requires a hidden input before the actual element, as these don't post a value if left unchecked:
<input type="hidden" name="myfield" value="default" />
<select name="myfield">
<option value="default" selected="selected">Default</option>
<option value="othervalue">Other value</option>
<!-- ... //-->
</select>
This will actually post the value "default" (without quotes, obviously) if the select is disabled by javascript (or jQuery) or even if your code writes the html disabling the element itself with the attribute: disabled="disabled".
catch specific HTTP error in python
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
How to sort a HashMap in Java
http://snipplr.com/view/2789/sorting-map-keys-by-comparing-its-values/
get the keys
List keys = new ArrayList(yourMap.keySet());
Sort them
Collections.sort(keys)
print them.
In any case, you can't have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time
].
Though you can push all these values to LinkedHashMap
, for later use as well.
Make A List Item Clickable (HTML/CSS)
HTML and CSS only.
_x000D_
_x000D_
#leftsideMenu ul li {_x000D_
border-bottom: 1px dashed lightgray;_x000D_
background-color: cadetblue;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a {_x000D_
padding: 8px 20px 8px 20px;_x000D_
color: white;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#leftsideMenu ul li a:hover {_x000D_
background-color: lightgreen;_x000D_
transition: 0.5s;_x000D_
padding-left: 30px;_x000D_
padding-right: 10px;_x000D_
}
_x000D_
<div id="leftsideMenu">_x000D_
<ul style="list-style-type:none">_x000D_
<li><a href="#">India</a></li>_x000D_
<li><a href="#">USA</a></li>_x000D_
<li><a href="#">Russia</a></li>_x000D_
<li><a href="#">China</a></li>_x000D_
<li><a href="#">Afganistan</a></li>_x000D_
<li><a href="#">Landon</a></li>_x000D_
<li><a href="#">Scotland</a></li>_x000D_
<li><a href="#">Ireland</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to draw a filled circle in Java?
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
// Assume x, y, and diameter are instance variables.
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2d.fill(circle);
...
}
Here are some docs about paintComponent (link).
You should override that method in your JPanel and do something similar to the code snippet above.
In your ActionListener you should specify x, y, diameter
and call repaint()
.
Create table using Javascript
Here is an example of drawing a table using raphael.js.
We can draw tables directly to the canvas of the browser using Raphael.js
Raphael.js is a javascript library designed specifically for artists and graphic designers.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id='panel'></div>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
paper = new Raphael(0,0,500,500);// width:500px, height:500px
var x = 100;
var y = 50;
var height = 50
var width = 100;
WriteTableRow(x,y,width*2,height,paper,"TOP Title");// draw a table header as merged cell
y= y+height;
WriteTableRow(x,y,width,height,paper,"Score,Player");// draw table header as individual cells
y= y+height;
for (i=1;i<=4;i++)
{
var k;
k = Math.floor(Math.random() * (10 + 1 - 5) + 5);//prepare table contents as random data
WriteTableRow(x,y,width,height,paper,i+","+ k + "");// draw a row
y= y+height;
}
function WriteTableRow(x,y,width,height,paper,TDdata)
{ // width:cell width, height:cell height, paper: canvas, TDdata: texts for a row. Separated each cell content with a comma.
var TD = TDdata.split(",");
for (j=0;j<TD.length;j++)
{
var rect = paper.rect(x,y,width,height).attr({"fill":"white","stroke":"red"});// draw outline
paper.text(x+width/2, y+height/2, TD[j]) ;// draw cell text
x = x + width;
}
}
</script>
</html>
Please check the preview image: https://i.stack.imgur.com/RAFhH.png
Build .so file from .c file using gcc command line
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
Key Shortcut for Eclipse Imports
You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports
via Java Editor
- Save Action
. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.
How do I best silence a warning about unused variables?
I found most of the presented answers work for local unused variable only, and will cause compile error for unused static global variable.
Another macro needed to suppress the warning of unused static global variable.
template <typename T>
const T* UNUSED_VARIABLE(const T& dummy) {
return &dummy;
}
#define UNUSED_GLOBAL_VARIABLE(x) namespace {\
const auto dummy = UNUSED_VARIABLE(x);\
}
static int a = 0;
UNUSED_GLOBAL_VARIABLE(a);
int main ()
{
int b = 3;
UNUSED_VARIABLE(b);
return 0;
}
This works because no warning will be reported for non-static global variable in anonymous namespace.
C++ 11 is required though
g++ -Wall -O3 -std=c++11 test.cpp
Javascript: output current datetime in YYYY/mm/dd hh:m:sec format
Alternative to answer of @JosephMarikle
If you do not want to figth against timezone UTC etc:
var dateString =
("0" + date.getUTCDate()).slice(-2) + "/" +
("0" + (date.getUTCMonth()+1)).slice(-2) + "/" +
date.getUTCFullYear() + " " +
//return HH:MM:SS with localtime without surprises
date.toLocaleTimeString()
console.log(fechaHoraActualCadena);
Variably modified array at file scope
Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.
Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.
How to grep for contents after pattern?
grep -Po 'potato:\s\K.*' file
-P
to use Perl regular expression
-o
to output only the match
\s
to match the space after potato:
\K
to omit the match
.*
to match rest of the string(s)
How to set custom header in Volley Request
As addition I'd like to share something I found regarding the Content-Type
:
On top of
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
.
.
.
return params;
}
I had to add:
@Override
public String getBodyContentType() {
return /*(for exmaple)*/ "application/json";
}
Don't ask me why, I just thought it might help some others that can't get the Content-Type
set right.
Xamarin.Forms ListView: Set the highlight color of a tapped item
In order to set the color of highlighted item you need to set the color of cell.SelectionStyle
in iOS.
This example is to set the color of tapped item to transparent.
If you want you can change it with other colors from UITableViewCellSelectionStyle
. This is to be written in the platform project of iOS by creating a new Custom ListView renderer in your Forms project.
public class CustomListViewRenderer : ListViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control == null)
{
return;
}
if (e.PropertyName == "ItemsSource")
{
foreach (var cell in Control.VisibleCells)
{
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
}
}
}
}
For android you can add this style in your values/styles.xml
<style name="ListViewStyle.Light" parent="android:style/Widget.ListView">
<item name="android:listSelector">@android:color/transparent</item>
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
How to open a link in new tab (chrome) using Selenium WebDriver?
for clicking on the link which expected to be opened from new tab use this
WebDriver driver = new ChromeDriver();
driver.get("https://www.yourSite.com");
WebElement link=driver.findElement(By.xpath("path_to_link"));
Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
.click(element)
.keyUp(Keys.LEFT_CONTROL)
.build()
.perform();
ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
Creating an empty Pandas DataFrame, then filling it?
If you simply want to create an empty data frame and fill it with some incoming data frames later, try this:
newDF = pd.DataFrame() #creates a new dataframe that's empty
newDF = newDF.append(oldDF, ignore_index = True) # ignoring index is optional
# try printing some data from newDF
print newDF.head() #again optional
In this example I am using this pandas doc to create a new data frame and then using append to write to the newDF with data from oldDF.
If I have to keep appending new data into this newDF from more than
one oldDFs, I just use a for loop to iterate over
pandas.DataFrame.append()
Reading a date using DataReader
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
How to create a link to a directory
Symbolic or soft link (files or directories, more flexible and self documenting)
# Source Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx
Hard link (files only, less flexible and not self documenting)
# Source Link
ln /home/jake/doc/test/2000/something /home/jake/xxx
More information: man ln
/home/jake/xxx
is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:
cd /home/jake/
ln -s /home/jake/doc/test/2000/something xxx
Generate C# class from XML
At first I thought the Paste Special was the holy grail! But then I tried it and my hair turned white just like the Indiana Jones movie.
But now I use http://xmltocsharp.azurewebsites.net/ and now I'm as young as ever.
Here's a segment of what it generated:
namespace Xml2CSharp
{
[XmlRoot(ElementName="entry")]
public class Entry {
[XmlElement(ElementName="hybrisEntryID")]
public string HybrisEntryID { get; set; }
[XmlElement(ElementName="mapicsLineSequenceNumber")]
public string MapicsLineSequenceNumber { get; set; }
How do I connect to a Websphere Datasource with a given JNDI name?
You need to define a resource reference in your application and then map that logical resource reference to the physical resource (data source) during deployment.
In your web.xml
, add the following configuration (modifying the names and properties as appropriate):
<resource-ref>
<description>Resource reference to my database</description>
<res-ref-name>jdbc/MyDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Then, during application deployment, WAS will prompt you to map this resource reference (jdbc/MyDB
) to the data source you created in WAS.
In your code, you can obtain the DataSource similar to how you've shown it in your example; however, the JNDI name you'll use to look it up should actually be the resource reference's name you defined (res-ref-name
), rather than the JNDI name of the physical data source. Also, you'll need to prefix the res-ref-name with the application naming context (java:comp/env/
).
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
MongoDB - Update objects in a document's array (nested updating)
For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.
The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:
db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:
db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
{$inc : {total : 1 , "items.$.price" : 1}} ,
false ,
true);
Datetime format Issue: String was not recognized as a valid DateTime
DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
Add new line in text file with Windows batch file
I believe you are using the
echo Text >> Example.txt
function?
If so the answer would be simply adding a "." (Dot) directly after the echo with nothing else there.
Example:
echo Blah
echo Blah 2
echo. #New line is added
echo Next Blah
VBA, if a string contains a certain letter
If you are looping through a lot of cells, use the binary function, it is much faster.
Using "<> 0" in place of "> 0" also makes it faster:
If InStrB(1, myString, "a", vbBinaryCompare) <> 0
SQL - select distinct only on one column
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
How to write and read a file with a HashMap?
The simplest solution that I can think of is using Properties class.
Saving the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream("data.properties"), null);
Loading the map:
Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));
for (String key : properties.stringPropertyNames()) {
ldapContent.put(key, properties.get(key).toString());
}
EDIT:
if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();
EDIT2:
instead of for loop (as suggested by OldCurmudgeon) in saving example:
properties.putAll(ldapContent);
however, for the loading example this is the best that can be done:
ldapContent = new HashMap<Object, Object>(properties);
Android - Dynamically Add Views into View
To make @Mark Fisher's answer more clear, the inserted view being inflated should be a xml file under layout folder but without a layout (ViewGroup) like LinearLayout etc. inside. My example:
res/layout/my_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/i_am_id"
android:text="my name"
android:textSize="17sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
Then, the insertion point should be a layout like LinearLayout:
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/aaa"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/insert_point"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</RelativeLayout>
Then the code should be
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.my_view, null);
ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
main.addView(view, 0);
}
The reason I post this very similar answer is that when I tried to implement Mark's solution, I got stuck on what xml file should I use for insert_point and the child view. I used layout in the child view firstly and it was totally not working, which took me several hours to figure out. So hope my exploration can save others' time.
How to disable a link using only CSS?
The pointer-events property allows for control over how HTML elements
respond to mouse/touch events – including CSS hover/active states,
click/tap events in Javascript, and whether or not the cursor is
visible.
That's not the only way you disable a Link, but a good CSS way which work in IE10+ and all new browsers:
_x000D_
_x000D_
.current-page {_x000D_
pointer-events: none;_x000D_
color: grey;_x000D_
}
_x000D_
<a href="#" class="current-page">This link is disabled</a>
_x000D_
_x000D_
_x000D_
Import data into Google Colaboratory
Simple way to import data from your googledrive - doing this save people time (don't know why google just doesn't list this step by step explicitly).
INSTALL AND AUTHENTICATE PYDRIVE
!pip install -U -q PyDrive ## you will have install for every colab session
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
UPLOADING
if you need to upload data from local drive:
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))
execute and this will display a choose file button - find your upload file - click open
After uploading, it will display:
sample_file.json(text/plain) - 11733 bytes, last modified: x/xx/2018 - %100 done
User uploaded file "sample_file.json" with length 11733 bytes
CREATE FILE FOR NOTEBOOK
If your data file is already in your gdrive, you can skip to this step.
Now it is in your google drive. Find the file in your google drive and right click. Click get 'shareable link.' You will get a window with:
https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn
Copy - '29PGh8XCts3mlMP6zRphvnIcbv27boawn' - that is the file ID.
In your notebook:
json_import = drive.CreateFile({'id':'29PGh8XCts3mlMP6zRphvnIcbv27boawn'})
json_import.GetContentFile('sample.json') - 'sample.json' is the file name that will be accessible in the notebook.
IMPORT DATA INTO NOTEBOOK
To import the data you uploaded into the notebook (a json file in this example - how you load will depend on file/data type - .txt,.csv etc. ):
sample_uploaded_data = json.load(open('sample.json'))
Now you can print to see the data is there:
print(sample_uploaded_data)
How do I write dispatch_after GCD in Swift 3, 4, and 5?
If you just want the delay function in
Swift 4 & 5
func delay(interval: TimeInterval, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + interval) {
closure()
}
}
You can use it like:
delay(interval: 1) {
print("Hi!")
}
RSA encryption and decryption in Python
In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
What are the parameters for the number Pipe - Angular 2
Regarding your first question.The pipe works as follows:
numberValue | number: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
2.Regarding your second question, Filter to zero decimal places as follows:
{{ numberValue | number: '1.0-0' }}
For further reading, checkout the following blog
Skip Git commit hooks
From man githooks
:
pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It
takes no parameter, and is invoked before obtaining the proposed commit log message
and making a commit. Exiting with non-zero status from this script causes the git
commit to abort.
how to bypass Access-Control-Allow-Origin?
It's a really bad idea to use *
, which leaves you wide open to cross site scripting. You basically want your own domain all of the time, scoped to your current SSL settings, and optionally additional domains. You also want them all to be sent as one header. The following will always authorize your own domain in the same SSL scope as the current page, and can optionally also include any number of additional domains. It will send them all as one header, and overwrite the previous one(s) if something else already sent them to avoid any chance of the browser grumbling about multiple access control headers being sent.
class CorsAccessControl
{
private $allowed = array();
/**
* Always adds your own domain with the current ssl settings.
*/
public function __construct()
{
// Add your own domain, with respect to the current SSL settings.
$this->allowed[] = 'http'
. ( ( array_key_exists( 'HTTPS', $_SERVER )
&& $_SERVER['HTTPS']
&& strtolower( $_SERVER['HTTPS'] ) !== 'off' )
? 's'
: null )
. '://' . $_SERVER['HTTP_HOST'];
}
/**
* Optionally add additional domains. Each is only added one time.
*/
public function add($domain)
{
if ( !in_array( $domain, $this->allowed )
{
$this->allowed[] = $domain;
}
/**
* Send 'em all as one header so no browsers grumble about it.
*/
public function send()
{
$domains = implode( ', ', $this->allowed );
header( 'Access-Control-Allow-Origin: ' . $domains, true ); // We want to send them all as one shot, so replace should be true here.
}
}
Usage:
$cors = new CorsAccessControl();
// If you are only authorizing your own domain:
$cors->send();
// If you are authorizing multiple domains:
foreach ($domains as $domain)
{
$cors->add($domain);
}
$cors->send();
You get the idea.
Find all packages installed with easy_install/pip?
Newer versions of pip have the ability to do what the OP wants via pip list -l
or pip freeze -l
(--list
).
On Debian (at least) the man page doesn't make this clear, and I only discovered it - under the assumption that the feature must exist - with pip list --help
.
There are recent comments that suggest this feature is not obvious in either the documentation or the existing answers (although hinted at by some), so I thought I should post. I would have preferred to do so as a comment, but I don't have the reputation points.