Remove all files in a directory
Please see my answer here:
https://stackoverflow.com/a/24844618/2293304
It's a long and ugly, but reliable and efficient solution.
It resolves a few problems which are not addressed by the other answerers:
- It correctly handles symbolic links, including not calling
shutil.rmtree()
on a symbolic link (which will pass the os.path.isdir()
test if it links to a directory).
- It handles read-only files nicely.
Change grid interval and specify tick labels in Matplotlib
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
Convert String to double in Java
There is another way too.
Double temp = Double.valueOf(str);
number = temp.doubleValue();
Double is a class and "temp" is a variable.
"number" is the final number you are looking for.
How to import js-modules into TypeScript file?
2021 Solution
If you're still getting this error message:
TS7016: Could not find a declaration file for module './myjsfile'
Then you might need to add the following to tsconfig.json
{
"compilerOptions": {
...
"allowJs": true,
"checkJs": false,
...
}
}
This prevents typescript from trying to apply module types to the imported javascript.
Is it possible to pass parameters programmatically in a Microsoft Access update query?
I just tested this and it works in Access 2010.
Say you have a SELECT query with parameters:
PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));
You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].
Now you create an UPDATE query based on that query:
UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));
You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].
You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:
Sub paramTest()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
qdf!startID = 1 ' specify
qdf!endID = 2 ' parameters
qdf.Execute
Set qdf = Nothing
End Sub
jQuery SVG, why can't I addClass?
Based on above answers I created the following API
/*
* .addClassSVG(className)
* Adds the specified class(es) to each of the set of matched SVG elements.
*/
$.fn.addClassSVG = function(className){
$(this).attr('class', function(index, existingClassNames) {
return ((existingClassNames !== undefined) ? (existingClassNames + ' ') : '') + className;
});
return this;
};
/*
* .removeClassSVG(className)
* Removes the specified class to each of the set of matched SVG elements.
*/
$.fn.removeClassSVG = function(className){
$(this).attr('class', function(index, existingClassNames) {
var re = new RegExp('\\b' + className + '\\b', 'g');
return existingClassNames.replace(re, '');
});
return this;
};
When to use the different log levels
I think that SYSLOG levels NOTICE and ALERT/EMERGENCY are largely superfluous for application-level logging - while CRITICAL/ALERT/EMERGENCY may be useful alert levels for an operator that may trigger different actions and notifications, to an application admin it's all the same as FATAL. And I just cannot sufficiently distinguish between being given a notice or some information. If the information is not noteworthy, it's not really information :)
I like Jay Cincotta's interpretation best - tracing your code's execution is something very useful in tech support, and putting trace statements into the code liberally should be encouraged - especially in combination with a dynamic filtering mechanism for logging the trace messages from specific application components. However DEBUG level to me indicates that we're still in the process of figuring out what's going on - I see DEBUG level output as a development-only option, not as something that should ever show up in a production log.
There is however a logging level that I like to see in my error logs when wearing the hat of a sysadmin as much as that of tech support, or even developer: OPER, for OPERATIONAL messages. This I use for logging a timestamp, the type of operation invoked, the arguments supplied, possibly a (unique) task identifier, and task completion. It's used when e.g. a standalone task is fired off, something that is a true invocation from within the larger long-running app. It's the sort of thing I want always logged, no matter whether anything goes wrong or not, so I consider the level of OPER to be higher than FATAL, so you can only turn it off by going to totally silent mode. And it's much more than mere INFO log data - a log level often abused for spamming logs with minor operational messages of no historical value whatsoever.
As the case dictates this information may be directed to a separate invocation log, or may be obtained by filtering it out of a large log recording more information. But it's always needed, as historical info, to know what was being done - without descending to the level of AUDIT, another totally separate log level that has nothing to do with malfunctions or system operation, doesn't really fit within the above levels (as it needs its own control switch, not a severity classification) and which definitely needs its own separate log file.
Python: convert string from UTF-8 to Latin-1
If the previous answers do not solve your problem, check the source of the data that won't print/convert properly.
In my case, I was using json.load
on data incorrectly read from file by not using the encoding="utf-8"
. Trying to de-/encode the resulting string to latin-1
just does not help...
How to compile and run C in sublime text 3?
The best way would be just to use a Makefile for your project and ST3 will automatically detect build system for your project. For example. If you press shift + ctrl/cmd +B you will see this:
Git's famous "ERROR: Permission to .git denied to user"
After Googling for few days, I found this is the only question similar to my situation.
However, I just solved the problem! So I am putting my answer here to help anyone else searching for this issue.
Here is what I did:
Open "Keychain Access.app" (You can find it in Spotlight or LaunchPad)
Select "All items" in Category
Search "git"
Delete every old & strange item
Try to Push again and it just WORKED
Can't install APK from browser downloads
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
Change the Blank Cells to "NA"
My function takes into account factor, character vector and potential attributes, if you use haven or foreign package to read external files. Also it allows matching different self-defined na.strings. To transform all columns, simply use lappy: df[] = lapply(df, blank2na, na.strings=c('','NA','na','N/A','n/a','NaN','nan'))
See more the comments:
#' Replaces blank-ish elements of a factor or character vector to NA
#' @description Replaces blank-ish elements of a factor or character vector to NA
#' @param x a vector of factor or character or any type
#' @param na.strings case sensitive strings that will be coverted to NA. The function will do a trimws(x,'both') before conversion. If NULL, do only trimws, no conversion to NA.
#' @return Returns a vector trimws (always for factor, character) and NA converted (if matching na.strings). Attributes will also be kept ('label','labels', 'value.labels').
#' @seealso \code{\link{ez.nan2na}}
#' @export
blank2na = function(x,na.strings=c('','.','NA','na','N/A','n/a','NaN','nan')) {
if (is.factor(x)) {
lab = attr(x, 'label', exact = T)
labs1 <- attr(x, 'labels', exact = T)
labs2 <- attr(x, 'value.labels', exact = T)
# trimws will convert factor to character
x = trimws(x,'both')
if (! is.null(lab)) lab = trimws(lab,'both')
if (! is.null(labs1)) labs1 = trimws(labs1,'both')
if (! is.null(labs2)) labs2 = trimws(labs2,'both')
if (!is.null(na.strings)) {
# convert to NA
x[x %in% na.strings] = NA
# also remember to remove na.strings from value labels
labs1 = labs1[! labs1 %in% na.strings]
labs2 = labs2[! labs2 %in% na.strings]
}
# the levels will be reset here
x = factor(x)
if (! is.null(lab)) attr(x, 'label') <- lab
if (! is.null(labs1)) attr(x, 'labels') <- labs1
if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
} else if (is.character(x)) {
lab = attr(x, 'label', exact = T)
labs1 <- attr(x, 'labels', exact = T)
labs2 <- attr(x, 'value.labels', exact = T)
# trimws will convert factor to character
x = trimws(x,'both')
if (! is.null(lab)) lab = trimws(lab,'both')
if (! is.null(labs1)) labs1 = trimws(labs1,'both')
if (! is.null(labs2)) labs2 = trimws(labs2,'both')
if (!is.null(na.strings)) {
# convert to NA
x[x %in% na.strings] = NA
# also remember to remove na.strings from value labels
labs1 = labs1[! labs1 %in% na.strings]
labs2 = labs2[! labs2 %in% na.strings]
}
if (! is.null(lab)) attr(x, 'label') <- lab
if (! is.null(labs1)) attr(x, 'labels') <- labs1
if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
} else {
x = x
}
return(x)
}
Axios Delete request with body and headers?
So after a number of tries, I found it working.
Please follow the order sequence it's very important else it won't work
axios.delete(URL, {
headers: {
Authorization: authorizationToken
},
data: {
source: source
}
});
A general tree implementation?
node = { 'parent':0, 'left':0, 'right':0 }
import copy
root = copy.deepcopy(node)
root['parent'] = -1
left = copy
just to show another thought on implementation if you stick to the "OOP"
class Node:
def __init__(self,data):
self.data = data
self.child = {}
def append(self, title, child):
self.child[title] = child
CEO = Node( ('ceo', 1000) )
CTO = ('cto',100)
CFO = ('cfo', 10)
CEO.append('left child', CTO)
CEO.append('right child', CFO)
print CEO.data
print ' ', CEO.child['left child']
print ' ', CEO.child['right child']
Convert string to Python class object?
I don't see why this wouldn't work. It's not as concrete as everyone else's answers but if you know the name of your class then it's enough.
def str_to_class(name):
if name == "Foo":
return Foo
elif name == "Bar":
return Bar
Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
The NoSuchMethodError javadoc says this:
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
In your case, this Error is a strong indication that your webapp is using the wrong version of the JAR defining the org.objectweb.asm.*
classes.
Plot two graphs in same plot in R
You could use the ggplotly()
function from the plotly package to turn any of the gggplot2 examples here into an interactive plot, but I think this sort of plot is better without ggplot2:
# call Plotly and enter username and key
library(plotly)
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot_ly(x = x) %>%
add_lines(y = y1, color = I("red"), name = "Red") %>%
add_lines(y = y2, color = I("green"), name = "Green")
MySQL "WITH" clause
Oracle does support WITH.
It would look like this.
WITH emps as (SELECT * FROM Employees)
SELECT * FROM emps WHERE ID < 20
UNION ALL
SELECT * FROM emps where Sex = 'F'
@ysth WITH is hard to google because it's a common word typically excluded from searches.
You'd want to look at the SELECT docs to see how subquery factoring works.
I know this doesn't answer the OP but I'm cleaning up any confusion ysth may have started.
Javac is not found
Start off by opening a cmd.exe session, changing directory to the "program files" directory that has the javac.exe executable and running .\javac.exe.
If that doesn't work, reinstall java. If that works, odds are you will find (in doing that task) that you've installed a 64 bit javac.exe
, or a slightly different release number of javac.exe
, or in a different drive, etc. and selecting the right entry in your path will become child's play.
Only use the semicolon between directories in the PATH environment variable, and remember that in some systems, you need to log out and log back in before the new environment variable is accessible to all environments.
Define preprocessor macro through CMake?
To do this for a specific target, you can do the following:
target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.
Floating Point Exception C++ Why and what is it?
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.
Host binding and Host listening
This is the simple example to use both of them:
import {
Directive, HostListener, HostBinding
}
from '@angular/core';
@Directive({
selector: '[Highlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') mouseover() {
this.backgroundColor = 'green';
};
@HostListener('mouseleave') mouseleave() {
this.backgroundColor = 'white';
}
@HostBinding('style.backgroundColor') get setColor() {
return this.backgroundColor;
};
private backgroundColor = 'white';
constructor() {}
}
Introduction:
HostListener can bind an event to the element.
HostBinding can bind a style to the element.
this is directive, so we can use it for
Some Text
So according to the debug, we can find that this div has been binded
style = "background-color:white"
Some Text
we also can find that EventListener of this div has two event: mouseenter
and mouseleave
. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.
Angular CLI SASS options
ng set --global defaults.styleExt=scss
is deprecated since ng6. You will get this message:
get/set have been deprecated in favor of the config command
You should use:
ng config schematics.@schematics/angular:component '{ styleext: "scss"}'
If you want to target a specific project (replace {project} with your project's name):
ng config projects.{project}.schematics.@schematics/angular:component '{ styleext: "scss"}'
R apply function with multiple parameters
Just pass var2 as an extra argument to one of the apply functions.
mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
var1*var2
}
var2 <- 2
sapply(mylist,myfxn,var2=var2)
This passes the same var2
to every call of myfxn
. If instead you want each call of myfxn
to get the 1st/2nd/3rd/etc. element of both mylist
and var2
, then you're in mapply
's domain.
Setting width and height
The below worked for me - but dont forget to put this in the "options" param.
var myChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
maintainAspectRatio: false,
responsive:true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
How to retrieve Jenkins build parameters using the Groovy API?
In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:
def myParam = env.getProperty(dynamicParamName)
In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:
def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName
LINQ to SQL - Left Outer Join with multiple join conditions
You need to introduce your join condition before calling DefaultIfEmpty()
. I would just use extension method syntax:
from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value
Or you could use a subquery:
from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
where f.otherid == 17
select f).DefaultIfEmpty()
where p.companyid == 100
select f.value
How can I concatenate strings in VBA?
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
Send email from localhost running XAMMP in PHP using GMAIL mail server
Here's the link that gives me the answer:
[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip
[Modify] the php.ini file to use it (commented out the other lines):
[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25
; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(ignore the "Unix only" bit, since we actually are using sendmail)
You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com
To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)
How to mute an html5 video player using jQuery
Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example
Javascript - check array for value
If you don't care about legacy browsers:
if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )
if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:
if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )
There can be only one auto column
CREATE TABLE book (
id INT AUTO_INCREMENT primary key NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Change a web.config programmatically with C# (.NET)
This is a method that I use to update AppSettings, works for both web and desktop applications. If you need to edit connectionStrings you can get that value from System.Configuration.ConnectionStringSettings config = configFile.ConnectionStrings.ConnectionStrings["YourConnectionStringName"];
and then set a new value with config.ConnectionString = "your connection string";
. Note that if you have any comments in the connectionStrings
section in Web.Config
these will be removed.
private void UpdateAppSettings(string key, string value)
{
System.Configuration.Configuration configFile = null;
if (System.Web.HttpContext.Current != null)
{
configFile =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
}
else
{
configFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
How do I break a string in YAML over multiple lines?
There are 5 6 NINE (or 63*, depending how you count) different ways to write multi-line strings in YAML.
TL;DR
Use >
most of the time: interior line breaks are stripped out, although you get one at the end:
key: >
Your long
string here.
Use |
if you want those linebreaks to be preserved as \n
(for instance, embedded markdown with paragraphs).
key: |
### Heading
* Bullet
* Points
Use >-
or |-
instead if you don't want a linebreak appended at the end.
Use "..."
if you need to split lines in the middle of words or want to literally type linebreaks as \n
:
key: "Antidisestab\
lishmentarianism.\n\nGet on it."
YAML is crazy.
Block scalar styles (>
, |
)
These allow characters such as \
and "
without escaping, and add a new line (\n
) to the end of your string.
>
Folded style removes single newlines within the string (but adds one at the end, and converts double newlines to singles):
Key: >
this is my very very very
long string
? this is my very very very long string\n
|
Literal style turns every newline within the string into a literal newline, and adds one at the end:
Key: |
this is my very very very
long string
? this is my very very very\nlong string\n
Here's the official definition from the YAML Spec 1.2
Scalar content can be written in block notation, using a literal style (indicated by “|”) where all line breaks are significant. Alternatively, they can be written with the folded style (denoted by “>”) where each line break is folded to a space unless it ends an empty or a more-indented line.
Block styles with block chomping indicator (>-
, |-
, >+
, |+
)
You can control the handling of the final new line in the string, and any trailing blank lines (\n\n
) by adding a block chomping indicator character:
>
, |
: "clip": keep the line feed, remove the trailing blank lines.
>-
, |-
: "strip": remove the line feed, remove the trailing blank lines.
>+
, |+
: "keep": keep the line feed, keep trailing blank lines.
"Flow" scalar styles (
, "
, '
)
These have limited escaping, and construct a single-line string with no new line characters. They can begin on the same line as the key, or with additional newlines first.
plain style (no escaping, no #
or :
combinations, limits on first character):
Key: this is my very very very
long string
double-quoted style (\
and "
must be escaped by \
, newlines can be inserted with a literal \n
sequence, lines can be concatenated without spaces with trailing \
):
Key: "this is my very very \"very\" loooo\
ng string.\n\nLove, YAML."
→ "this is my very very \"very\" loooong string.\n\nLove, YAML."
single-quoted style (literal '
must be doubled, no special characters, possibly useful for expressing strings starting with double quotes):
Key: 'this is my very very "very"
long string, isn''t it.'
→ "this is my very very \"very\" long string, isn't it."
Summary
In this table, _
means space character
. \n
means "newline character" (\n
in JavaScript), except for the "in-line newlines" row, where it means literally a backslash and an n).
> | " ' >- >+ |- |+
-------------------------|------|-----|-----|-----|------|------|------|------
Trailing spaces | Kept | Kept | | | | Kept | Kept | Kept | Kept
Single newline => | _ | \n | _ | _ | _ | _ | _ | \n | \n
Double newline => | \n | \n\n | \n | \n | \n | \n | \n | \n\n | \n\n
Final newline => | \n | \n | | | | | \n | | \n
Final dbl nl's => | | | | | | | Kept | | Kept
In-line newlines | No | No | No | \n | No | No | No | No | No
Spaceless newlines| No | No | No | \ | No | No | No | No | No
Single quote | ' | ' | ' | ' | '' | ' | ' | ' | '
Double quote | " | " | " | \" | " | " | " | " | "
Backslash | \ | \ | \ | \\ | \ | \ | \ | \ | \
" #", ": " | Ok | Ok | No | Ok | Ok | Ok | Ok | Ok | Ok
Can start on same | No | No | Yes | Yes | Yes | No | No | No | No
line as key |
Examples
Note the trailing spaces on the line before "spaces."
- >
very "long"
'string' with
paragraph gap, \n and
spaces.
- |
very "long"
'string' with
paragraph gap, \n and
spaces.
- very "long"
'string' with
paragraph gap, \n and
spaces.
- "very \"long\"
'string' with
paragraph gap, \n and
s\
p\
a\
c\
e\
s."
- 'very "long"
''string'' with
paragraph gap, \n and
spaces.'
- >-
very "long"
'string' with
paragraph gap, \n and
spaces.
[
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.\n",
"very \"long\"\n'string' with\n\nparagraph gap, \\n and \nspaces.\n",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces.",
"very \"long\" 'string' with\nparagraph gap, \\n and spaces."
]
Block styles with indentation indicators
Just in case the above isn't enough for you, you can add a "block indentation indicator" (after your block chomping indicator, if you have one):
- >8
My long string
starts over here
- |+1
This one
starts here
Addendum
If you insert extra spaces at the start of not-the-first lines in Folded style, they will be kept, with a bonus newline. This doesn't happen with flow styles:
- >
my long
string
- my long
string
? ["my long\n string\n", "my long string"]
I can't even.
*
2 block styles, each with 2 possible block chomping indicators (or none), and with 9 possible indentation indicators (or none), 1 plain style and 2 quoted styles: 2 x (2 + 1) x (9 + 1) + 1 + 2 = 63
Some of this information has also been summarised here.
Iterating through array - java
You should definitely encapsulate this logic into a method.
There is no benefit to repeating identical code multiple times.
Also, if you place the logic in a method and it changes, you only need to modify your code in one place.
Whether or not you want to use a 3rd party library is an entirely different decision.
Using CookieContainer with WebClient class
I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)
internal static class MyWebRequestCreator
{
private static IWebRequestCreate myCreator;
public static IWebRequestCreate MyHttp
{
get
{
if (myCreator == null)
{
myCreator = new MyHttpRequestCreator();
}
return myCreator;
}
}
private class MyHttpRequestCreator : IWebRequestCreate
{
public WebRequest Create(Uri uri)
{
var req = System.Net.WebRequest.CreateHttp(uri);
req.CookieContainer = new CookieContainer();
return req;
}
}
}
Now all you have to do is opt in for which domains you want to use this:
WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);
That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it.
You can also register for "http" prefix to opt in for everything everywhere.
Best way to compare dates in Android
Your code could be reduced to
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
or
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
catalog_outdated = 1;
}
How to toggle (hide / show) sidebar div using jQuery
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
Just disable scroll not hide it?
I like to stick to the "overflow: hidden" method and just add padding-right that's equal to the scrollbar width.
Get scrollbar width function, by lostsource.
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
When showing the overlay, add "noscroll" class to html and add padding-right to body:
$(html).addClass("noscroll");
$(body).css("paddingRight", getScrollbarWidth() + "px");
When hiding, remove the class and padding:
$(html).removeClass("noscroll");
$(body).css("paddingRight", 0);
The noscroll style is just this:
.noscroll { overflow: hidden; }
Note that if you have any elements with position:fixed you need to add the padding to those elements too.
Comments in Android Layout xml
ctrl+shift+/ You can comment the code.
<!--
<View
android:layout_marginTop="@dimen/d10dp"
android:id="@+id/view1"
android:layout_below="@+id/tv_change_password"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#c0c0c0"/>-->
Run function from the command line
python -c 'from myfile import hello; hello()'
where myfile
must be replaced with the basename of your Python script. (E.g., myfile.py
becomes myfile
).
However, if hello()
is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
This allows you to execute the script simply by running python myfile.py
or python -m myfile
.
Some explanation here: __name__
is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__"
.
ldconfig error: is not a symbolic link
You need to include the path of the libraries inside /etc/ld.so.conf, and rerun ldconfig to upate the list
Other possibility is to include in the env variable LD_LIBRARY_PATH the path to your library, and rerun the executable.
check the symbolic links if they point to a valid library ...
You can add the path directly in /etc/ld.so.conf, without include...
run ldconfig -p
to see whether your library is well included in the cache.
curl_init() function not working
For PHP 7 and Windows x64
libeay32.dll, libssh2.dll and ssleay32.dll should not be in apache/bin and should only exist in php directory and add php directory in system environment variable. This work for me.
Obvisouly in php.ini you should have enable php_curl.dll as well.
How to Set JPanel's Width and Height?
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
Multi-line string with extra space (preserved indentation)
There are many ways to do it. For me, piping the indented string into sed works nicely.
printf_strip_indent() {
printf "%s" "$1" | sed "s/^\s*//g"
}
printf_strip_indent "this is line one
this is line two
this is line three" > "file.txt"
This answer was based on Mateusz Piotrowski's answer but refined a bit.
Notice: Array to string conversion in
Even simpler:
$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");
note the quotes around username in the $_SESSION reference.
Left Outer Join using + sign in Oracle 11g
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
Where is web.xml in Eclipse Dynamic Web Project
If you don't see the web.xml file in WEB-INF folder,
- Select Deployment Descriptor and right click on it.
- Then select the Generate Deployment Descriptor Stub
Finally you get web.xml file.
Event system in Python
If I do code in pyQt I use QT sockets/signals paradigm, same is for django
If I'm doing async I/O I use native select module
If I'm usign a SAX python parser I'm using event API provided by SAX. So it looks like I'm victim of underlying API :-)
Maybe you should ask yourself what do you expect from event framework/module. My personal preference is to use Socket/Signal paradigm from QT. more info about that can be found here
How do I compile the asm generated by GCC?
Yes, gcc can also compile assembly source code. Alternatively, you can invoke as
, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)
How to Delete node_modules - Deep Nested Folder in Windows
Delete Deep Netsted Folder like node_modules in Windows
Option 1
Delete using rimraf
NPM package
Open command prompt and change your directory to the folder where
node_modules
folder exists.
Run
rimraf node_modules
Missing rimraf ERROR then Install
npm install rimraf -g
When the installation completes, run
rimraf node_modules
Option 2:
Detele without installing anything
Create a folder with name test
in any Drive
robocopy /MIR c:\test D:\UserData\FolderToDelete > NUL
delete the folder test
and FolderToDelete
as both are empty
Why this is an issue in windows?
One of the deep nested folder structure is node_modules, Windows can’t delete the folder as its name is too long. To solve this, Easy solution, install a node module RimRaf
asp.net Button OnClick event not firing
If you are using updatepanel on onclick event, this may happen.
Use 'EnableEventValidation="false"' in your page markup like this :
<%@ Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>
Hope this helps
How to make Bitmap compress without change the bitmap size?
If you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your image and use 0 instead of 100 in quality.
Quality Accepts 0 - 100
0 = MAX Compression (Least Quality which is suitable for Small images)
100 = Least Compression (MAX Quality which is suitable for Big images)
How to hide Soft Keyboard when activity starts
If your application is targeting Android API Level 21 or more than there is a default method available.
editTextObj.setShowSoftInputOnFocus(false);
Make sure you have set below code in EditText
XML tag.
<EditText
....
android:enabled="true"
android:focusable="true" />
How to suppress Pandas Future warning ?
Warnings are annoying. As mentioned in other answers, you can suppress them using:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:
import warnings
warnings.filterwarnings("error")
But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:
import warnings
warnings.simplefilter(action='error', category=FutureWarning)
return in for loop or outside loop
Now someone told me that this is not very good programming because I
use the return statement inside a loop and this would cause garbage
collection to malfunction.
That's a bunch of rubbish. Everything inside the method would be cleaned up unless there were other references to it in the class or elsewhere (a reason why encapsulation is important). As a rule of thumb, it's generally better to use one return statement simply because it is easier to figure out where the method will exit.
Personally, I would write:
Boolean retVal = false;
for(int i=0; i<array.length; ++i){
if(array[i]==valueToFind) {
retVal = true;
break; //Break immediately helps if you are looking through a big array
}
}
return retVal;
JAX-RS / Jersey how to customize error handling?
You could also write a reusable class for QueryParam-annotated variables
public class DateParam {
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
private Calendar date;
public DateParam(String in) throws WebApplicationException {
try {
date = Calendar.getInstance();
date.setTime(format.parse(in));
}
catch (ParseException exception) {
throw new WebApplicationException(400);
}
}
public Calendar getDate() {
return date;
}
public String format() {
return format.format(value.getTime());
}
}
then use it like this:
private @QueryParam("from") DateParam startDateParam;
private @QueryParam("to") DateParam endDateParam;
// ...
startDateParam.getDate();
Although the error handling is trivial in this case (throwing a 400 response), using this class allows you to factor-out parameter handling in general which might include logging etc.
The POM for project is missing, no dependency information available
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
How to POST a FORM from HTML to ASPX page
Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...
Catch a thread's exception in the caller thread in Python
This was a nasty little problem, and I'd like to throw my solution in. Some other solutions I found (async.io for example) looked promising but also presented a bit of a black box. The queue / event loop approach sort of ties you to a certain implementation. The concurrent futures source code, however, is around only 1000 lines, and easy to comprehend. It allowed me to easily solve my problem: create ad-hoc worker threads without much setup, and to be able to catch exceptions in the main thread.
My solution uses the concurrent futures API and threading API. It allows you to create a worker which gives you both the thread and the future. That way, you can join the thread to wait for the result:
worker = Worker(test)
thread = worker.start()
thread.join()
print(worker.future.result())
...or you can let the worker just send a callback when done:
worker = Worker(test)
thread = worker.start(lambda x: print('callback', x))
...or you can loop until the event completes:
worker = Worker(test)
thread = worker.start()
while True:
print("waiting")
if worker.future.done():
exc = worker.future.exception()
print('exception?', exc)
result = worker.future.result()
print('result', result)
break
time.sleep(0.25)
Here's the code:
from concurrent.futures import Future
import threading
import time
class Worker(object):
def __init__(self, fn, args=()):
self.future = Future()
self._fn = fn
self._args = args
def start(self, cb=None):
self._cb = cb
self.future.set_running_or_notify_cancel()
thread = threading.Thread(target=self.run, args=())
thread.daemon = True #this will continue thread execution after the main thread runs out of code - you can still ctrl + c or kill the process
thread.start()
return thread
def run(self):
try:
self.future.set_result(self._fn(*self._args))
except BaseException as e:
self.future.set_exception(e)
if(self._cb):
self._cb(self.future.result())
...and the test function:
def test(*args):
print('args are', args)
time.sleep(2)
raise Exception('foo')
How to sum all the values in a dictionary?
You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.
Example:
c={"a":123,"b":4,"d":4,"c":-1001,"x":2002,"y":1001}
sum(list(c.values()))
How do you read CSS rule values with JavaScript?
This version will go through all of the stylesheets on a page. For my needs, the styles were usually in the 2nd to last of the 20+ stylesheets, so I check them backwards.
var getStyle = function(className){
var x, sheets,classes;
for( sheets=document.styleSheets.length-1; sheets>=0; sheets-- ){
classes = document.styleSheets[sheets].rules || document.styleSheets[sheets].cssRules;
for(x=0;x<classes.length;x++) {
if(classes[x].selectorText===className) {
return (classes[x].cssText ? classes[x].cssText : classes[x].style.cssText);
}
}
}
return false;
};
Ignore cells on Excel line graph
Not for blanks in the middle of a range, but this works for a complex chart from a start date until infinity (ie no need to adjust the chart's data source each time informatiom is added), without showing any lines for dates that have not yet been entered. As you add dates and data to the spreadsheet, the chart expands. Without it, the chart has a brain hemorrhage.
So, to count a complex range of conditions over an extended period of time but only if the date of the events is not blank :
=IF($B6<>"",(COUNTIF($O6:$O6,Q$5)),"") returns “#N/A” if there is no date in column B.
In other words, "count apples or oranges or whatever in column O (as determined by what is in Q5) but only if column B (the dates) is not blank". By returning “#N/A”, the chart will skip the "blank" rows (blank as in a zero value or rather "#N/A").
From that table of returned values you can make a chart from a date in the past to infinity
How do you add a timer to a C# console application
You can also create your own (if unhappy with the options available).
Creating your own Timer
implementation is pretty basic stuff.
This is an example for an application that needed COM object access on the same thread as the rest of my codebase.
/// <summary>
/// Internal timer for window.setTimeout() and window.setInterval().
/// This is to ensure that async calls always run on the same thread.
/// </summary>
public class Timer : IDisposable {
public void Tick()
{
if (Enabled && Environment.TickCount >= nextTick)
{
Callback.Invoke(this, null);
nextTick = Environment.TickCount + Interval;
}
}
private int nextTick = 0;
public void Start()
{
this.Enabled = true;
Interval = interval;
}
public void Stop()
{
this.Enabled = false;
}
public event EventHandler Callback;
public bool Enabled = false;
private int interval = 1000;
public int Interval
{
get { return interval; }
set { interval = value; nextTick = Environment.TickCount + interval; }
}
public void Dispose()
{
this.Callback = null;
this.Stop();
}
}
You can add events as follows:
Timer timer = new Timer();
timer.Callback += delegate
{
if (once) { timer.Enabled = false; }
Callback.execute(callbackId, args);
};
timer.Enabled = true;
timer.Interval = ms;
timer.Start();
Window.timers.Add(Environment.TickCount, timer);
To make sure the timer works you need to create an endless loop as follows:
while (true) {
// Create a new list in case a new timer
// is added/removed during a callback.
foreach (Timer timer in new List<Timer>(timers.Values))
{
timer.Tick();
}
}
Should I use the datetime or timestamp data type in MySQL?
2016 +: what I advise is to set your Mysql timezone to UTC and use DATETIME:
Any recent front-end framework (Angular 1/2, react, Vue,...) can easily and automatically convert your UTC datetime to local time.
Additionally:
(Unless you are likely to change the timezone of your servers)
Example with AngularJs
// back-end: format for angular within the sql query
SELECT DATE_FORMAT(my_datetime, "%Y-%m-%dT%TZ")...
// font-end Output the localised time
{{item.my_datetime | date :'medium' }}
All localised time format available here:
https://docs.angularjs.org/api/ng/filter/date
CSS force image resize and keep aspect ratio
Fullscreen presentation:
img[data-attribute] {height: 100vh;}
Keep in mind that if the view-port height is greater than the image the image will naturally degrade relative to the difference.
How do I integrate Ajax with Django applications?
Further from yuvi's excellent answer, I would like to add a small specific example on how to deal with this within Django (beyond any js that will be used). The example uses AjaxableResponseMixin
and assumes an Author model.
import json
from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def render_to_json_response(self, context, **response_kwargs):
data = json.dumps(context)
response_kwargs['content_type'] = 'application/json'
return HttpResponse(data, **response_kwargs)
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return self.render_to_json_response(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return self.render_to_json_response(data)
else:
return response
class AuthorCreate(AjaxableResponseMixin, CreateView):
model = Author
fields = ['name']
Source: Django documentation, Form handling with class-based views
The link to version 1.6 of Django is no longer available updated to version 1.11
Turning Sonar off for certain code
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
ERROR Source option 1.5 is no longer supported. Use 1.6 or later
I got this error: "Source option 5 is no longer supported. Use 6 or later"
after I changed the pom.xml
<java.version>7</java.version>
to
<java.version>11</java.version>
Later to realise the property was used with a dash insteal of a dot:
<source>${java-version}</source>
<target>${java-version}</target>
(swearings), I replaced the dot with a dash and the error went away:
<java-version>11</javaversion>
Find html label associated with a given input
It is actually far easier to add an id to the label in the form itself, for example:
<label for="firstName" id="firstNameLabel">FirstName:</label>
<input type="text" id="firstName" name="firstName" class="input_Field"
pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
title="Alphabetic, Space, Dash Only, 2-25 Characters Long"
autocomplete="on" required
/>
Then, you can simply use something like this:
if (myvariableforpagelang == 'es') {
// set field label to spanish
document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
// set field tooltip (title to spanish
document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}
The javascript does have to be in a body onload function to work.
Just a thought, works beautifully for me.
How do I lock the orientation to portrait mode in a iPhone Web Application?
// CSS hack to prevent layout breaking in landscape
// e.g. screens larger than 320px
html {
width: 320px;
overflow-x: hidden;
}
This, or a similar CSS solution, will at least preserve your layout if that is what you are after.
The root solution is accounting for device's capabilities rather than attempting to limit them. If the device doesn't allow you the appropriate limitation than a simple hack is your best bet since the design is essentially incomplete. The simpler the better.
display: inline-block extra margin
For the record, that margin and padding resetting didn't do the trick for me, but this quote from one of the comments above turned out to be crucial and solved the issue for me: "If i put the divs on the same line it margin disappears."
Disable copy constructor
You can make the copy constructor private and provide no implementation:
private:
SymbolIndexer(const SymbolIndexer&);
Or in C++11, explicitly forbid it:
SymbolIndexer(const SymbolIndexer&) = delete;
How to select min and max values of a column in a datatable?
int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;
foreach (DataRow dr in table.Rows)
{
int accountLevel = dr.Field<int>("AccountLevel");
minAccountLevel = Math.Min(minAccountLevel, accountLevel);
maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
}
Yes, this really is the fastest way. Using the Linq Min
and Max
extensions will always be slower because you have to iterate twice. You could potentially use Linq Aggregate
, but the syntax isn't going to be much prettier than this already is.
Unique Key constraints for multiple columns in Entity Framework
With Entity Framework 6.1, you can now do this:
[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }
[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }
The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN
How do I change the figure size with subplots?
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
Confused about stdin, stdout and stderr?
Using ps -aux reveals current processes, all of which are listed in /proc/ as /proc/(pid)/, by calling cat /proc/(pid)/fd/0 it prints anything that is found in the standard output of that process I think. So perhaps,
/proc/(pid)/fd/0 - Standard Output File
/proc/(pid)/fd/1 - Standard Input File
/proc/(pid)/fd/2 - Standard Error File
for example
But only worked this well for /bin/bash other processes generally had nothing in 0 but many had errors written in 2
PowerShell To Set Folder Permissions
In case you had to deal with a lot of subfolders contatining subfolders and other recursive stuff. Small improvment of @Mike L'Angelo:
$mypath = "path_to_folder"
$myacl = Get-Acl $mypath
$myaclentry = "username","FullControl","Allow"
$myaccessrule = New-Object System.Security.AccessControl.FileSystemAccessRule($myaclentry)
$myacl.SetAccessRule($myaccessrule)
Get-ChildItem -Path "$mypath" -Recurse -Force | Set-Acl -AclObject $myacl -Verbose
Verbosity is optional in the last line
How to print a specific row of a pandas DataFrame?
If you want to display at row=159220
row=159220
#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])
#To display in print format
display(res.loc[row])
display(res.iloc[row])
How to display line numbers in 'less' (GNU)
From the manual:
-N or --LINE-NUMBERS
Causes a line number to be displayed at the beginning of each
line in the display.
You can also toggle line numbers without quitting less by typing -N
.
It is possible to toggle any of less's command line options in this way.
No input file specified
GoDaddy is currently (Feb '13) supporting modification of FastCGI for some accounts using PHP 5.2.x or earlier. See GoDaddy article "Disabling FastCGI in Your Hosting Account".
(In my case, this is apparently necessary to help get the current version of LimeSurvey (2.0) towards a running state.)
How to run mysql command on bash?
This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.
mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'
Remove Item from ArrayList
String[] mString = new String[] {"B", "D", "F"};
for (int j = 0; j < mString.length-1; j++) {
List_Of_Array.remove(mString[j]);
}
plain count up timer in javascript
Check this:
_x000D_
_x000D_
var minutesLabel = document.getElementById("minutes");_x000D_
var secondsLabel = document.getElementById("seconds");_x000D_
var totalSeconds = 0;_x000D_
setInterval(setTime, 1000);_x000D_
_x000D_
function setTime() {_x000D_
++totalSeconds;_x000D_
secondsLabel.innerHTML = pad(totalSeconds % 60);_x000D_
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));_x000D_
}_x000D_
_x000D_
function pad(val) {_x000D_
var valString = val + "";_x000D_
if (valString.length < 2) {_x000D_
return "0" + valString;_x000D_
} else {_x000D_
return valString;_x000D_
}_x000D_
}
_x000D_
<label id="minutes">00</label>:<label id="seconds">00</label>
_x000D_
_x000D_
_x000D_
download a file from Spring boot rest service
I want to share a simple approach for downloading files with JavaScript (ES6), React and a Spring Boot backend:
- Spring boot Rest Controller
Resource from org.springframework.core.io.Resource
@SneakyThrows
@GetMapping("/files/{filename:.+}/{extraVariable}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename, @PathVariable String extraVariable) {
Resource file = storageService.loadAsResource(filename, extraVariable);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
- React, API call using AXIOS
Set the responseType to arraybuffer to specify the type of data contained in the response.
export const DownloadFile = (filename, extraVariable) => {
let url = 'http://localhost:8080/files/' + filename + '/' + extraVariable;
return axios.get(url, { responseType: 'arraybuffer' }).then((response) => {
return response;
})};
Final step > downloading
with the help of js-file-download you can trigger browser to save data to file as if it was downloaded.
DownloadFile('filename.extension', 'extraVariable').then(
(response) => {
fileDownload(response.data, filename);
}
, (error) => {
// ERROR
});
New lines inside paragraph in README.md
Interpreting newlines as <br />
used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.
Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change
a
b
c
into
a__
b__
c
(where _
is a blank space).
Or, you can add explicit <br />
tags.
a <br />
b <br />
c
Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?
inside OnCreate method :-
{
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener((View.OnClickListener)this);
b = (Button)findViewById(R.id.button2);
b.setOnClickListener((View.OnClickListener)this);
}
@Override
public void OnClick(View v){
switch(v.getId()){
case R.id.button1:
//whatever
break;
case R.id.button2:
//whatever
break;
}
Does Go have "if x in" construct similar to Python?
Another solution if the list contains static values.
eg: checking for a valid value from a list of valid values:
func IsValidCategory(category string) bool {
switch category {
case
"auto",
"news",
"sport",
"music":
return true
}
return false
}
jQuery datepicker to prevent past date
//disable future dates
$('#datetimepicker1').datetimepicker({
format: 'DD-MM-YYYY',
maxDate: new Date
});
//disable past dates
$('#datetimepicker2').datetimepicker({
format: 'DD-MM-YYYY',
minDate: new Date
});
Creating a new empty branch for a new project
Make an empty new branch like this:
true | git mktree | xargs git commit-tree | xargs git branch proj-doc
If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:
git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc
which might be more convenient than git branch --orphan
if that would leave you with a lot of git rm
and git mv
ing to do.
Try
git branch --set-upstream proj-doc origin/proj-doc
and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.
Capturing count from an SQL query
You'll get converting errors with:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
Use instead:
string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
found = true;
} else {
found = false;
}
Escape text for HTML
Didn't see this here
System.Web.HttpUtility.JavaScriptStringEncode("Hello, this is Satan's Site")
it was the only thing that worked (asp 4.0+) when dealing with html like this. The'
gets rendered as '
(using htmldecode) in the html, causing it to fail:
<a href="article.aspx?id=268" onclick="tabs.open('modules/xxx/id/268', 'It's Allstars'); return false;">It's Allstars</a>
What is the difference between CMD and ENTRYPOINT in a Dockerfile?
Most people explain it perfectly here, so I won't repeat all the answers. But to get a good feeling I would suggest testing it yourself by looking at the processes in the container.
Create a tiny Dockerfile of the form:
FROM ubuntu:latest
CMD /bin/bash
Build it, run it in with docker run -it theimage
and run ps -eo ppid,pid,args
in the container.
Compare this output to the output you receive from ps when using:
docker run -it theimage bash
- Rebuilding the image but with
ENTRYPOINT /bin/bash
and running it in both ways
- Using
CMD ["/bin/bash"]
- ...
This way you will easily see the differences between all possible methods for yourself.
Passing an array to a query using a WHERE clause
Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.
I found that each string needed to be encapsulated in single quotes to work with the IN()
function.
Here is my solution
foreach($status as $status_a) {
$status_sql[] = '\''.$status_a.'\'';
}
$status = implode(',',$status_sql);
$sql = mysql_query("SELECT * FROM table WHERE id IN ($status)");
As you can see the first function wraps each array variable in single quotes (\')
and then implodes the array.
NOTE: $status
does not have single quotes in the SQL statement.
There is probably a nicer way to add the quotes but this works.
VSCode single to double quote automatic replace
There only solution that worked for me:
and only for Angular Projects:
Just go into your project ".editorconfig" file and paste 'quote_type = single'.
Hope it should work for you as well.
Display List in a View MVC
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
How to restart tomcat 6 in ubuntu
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
How to return the output of stored procedure into a variable in sql server
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return
statement
create proc myproc
as
begin
return 1
end
go
declare @i int
exec @i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
@a int output,
@b varchar(50) output
as
begin
select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare @t table (name varchar(100))
insert @t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
How do I check if a SQL Server text column is empty?
To get only empty values (and not null values):
SELECT * FROM myTable WHERE myColumn = ''
To get both null and empty values:
SELECT * FROM myTable WHERE myColumn IS NULL OR myColumn = ''
To get only null values:
SELECT * FROM myTable WHERE myColumn IS NULL
To get values other than null and empty:
SELECT * FROM myTable WHERE myColumn <> ''
And remember use LIKE phrases only when necessary because they will degrade performance compared to other types of searches.
What is default list styling (CSS)?
You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:
.my_container ul {list-style:disc outside none; margin-left:40px;}
How to create Password Field in Model Django
See my code which may help you.
models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
How can I change cols of textarea in twitter-bootstrap?
UPDATE: As of Bootstrap 3.0, the input-*
classes described below for setting the width of input elements were removed. Instead use the col-*
classes to set the width of input elements. Examples are provided in the documentation.
In Bootstrap 2.3, you'd use the input classes for setting the width.
<textarea class="input-mini"></textarea>
<textarea class="input-small"></textarea>
<textarea class="input-medium"></textarea>
<textarea class="input-large"></textarea>
<textarea class="input-xlarge"></textarea>
<textarea class="input-xxlarge"></textarea>?
<textarea class="input-block-level"></textarea>?
Do a find for "Control sizing" for examples in the documentation.
But for height I think you'd still use the rows attribute.
How to avoid "RuntimeError: dictionary changed size during iteration" error?
I would try to avoid inserting empty lists in the first place, but, would generally use:
d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty
If prior to 2.7:
d = dict( (k, v) for k,v in d.iteritems() if v )
or just:
empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
del[k]
Is there a sleep function in JavaScript?
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.
Passing an array as a function parameter in JavaScript
As @KaptajnKold had answered
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
And you don't need to define every parameters for call_me function either.
You can just use arguments
function call_me () {
// arguments is a array consisting of params.
// arguments[0] == 'p0',
// arguments[1] == 'p1',
// arguments[2] == 'p2'
}
Detect whether there is an Internet connection available on Android
The getActiveNetworkInfo() method of ConnectivityManager returns a
NetworkInfo instance representing the first connected network
interface it can find or null if none if the interfaces are connected.
Checking if this method returns null should be enough to tell if an
internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
You will also need:
in your
android manifest.
Edit:
Note that having an active network interface doesn't guarantee that a
particular networked service is available. Networks issues, server
downtime, low signal, captive portals, content filters and the like
can all prevent your app from reaching a server. For instance you
can't tell for sure if your app can reach Twitter until you receive a
valid response from the Twitter service.
getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.
Referenced Project gets "lost" at Compile Time
Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile
.
With inconsistent versions, specifically with one being Client Profile
and the other not, then it works at design time but fails at compile time. A real gotcha.
There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile
, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...
AngularJS: How to make angular load script inside ng-include?
To dynamically load recaptcha from a ui-view
I use the following method:
In application.js
:
.directive('script', function($parse, $rootScope, $compile) {
return {
restrict: 'E',
terminal: true,
link: function(scope, element, attr) {
if (attr.ngSrc) {
var domElem = '<script src="'+attr.ngSrc+'" async defer></script>';
$(element).append($compile(domElem)(scope));
}
}
};
});
In myPartial.client.view.html
:
<script type="application/javascript" ng-src="http://www.google.com/recaptcha/api.js?render=explicit&onload=vcRecaptchaApiLoaded"></script>
Enum String Name from Value
Just cast the int to the enumeration type:
EnumDisplayStatus status = (EnumDisplayStatus) statusFromDatabase;
string statusString = status.ToString();
Reorder / reset auto increment primary key
You could drop the primary key column and re-create it. All the ids should then be reassigned in order.
However this is probably a bad idea in most situations. If you have other tables that have foreign keys to this table then it will definitely not work.
Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window
Sorry this is and old thread but some people would still need this I guess,
Note: I achieved this using Animate.css library for animating the fade.
I used your code and just added .hidden class (using bootstrap's hidden class) but you can still just define
.hidden { opacity: 0; }
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).removeClass('hidden');
$(this).addClass('animated fadeInUp');
} else {
$(this).addClass('hidden');
}
});
});
});
Another Note: Applying this to containers might cause it to be glitchy.
slf4j: how to log formatted message, object array, exception
As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.
So, writing (in SLF4J version 1.7.x and later)
logger.error("one two three: {} {} {}", "a", "b",
"c", new Exception("something went wrong"));
or writing (in SLF4J version 1.6.x)
logger.error("one two three: {} {} {}", new Object[] {"a", "b",
"c", new Exception("something went wrong")});
will yield
one two three: a b c
java.lang.Exception: something went wrong
at Example.main(Example.java:13)
at java.lang.reflect.Method.invoke(Method.java:597)
at ...
The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.
Convert Long into Integer
If you are using Java 8 Do it as below
import static java.lang.Math.toIntExact;
public class DateFormatSampleCode {
public static void main(String[] args) {
long longValue = 1223321L;
int longTointValue = toIntExact(longValue);
System.out.println(longTointValue);
}
}
Fast check for NaN in NumPy
If you're comfortable with numba it allows to create a fast short-circuit (stops as soon as a NaN is found) function:
import numba as nb
import math
@nb.njit
def anynan(array):
array = array.ravel()
for i in range(array.size):
if math.isnan(array[i]):
return True
return False
If there is no NaN
the function might actually be slower than np.min
, I think that's because np.min
uses multiprocessing for large arrays:
import numpy as np
array = np.random.random(2000000)
%timeit anynan(array) # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.64 ms per loop
But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:
array = np.random.random(2000000)
array[100] = np.nan
%timeit anynan(array) # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.65 ms per loop
Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan
) but ultimatly do the same as my anynan
function.
Missing Maven dependencies in Eclipse project
This same problem happened to me, and it was because there an error in downloading a jar due to repo issues, indicated by a red flag in the pom.xml
.
I added another repository so the red flag in the pom.xml
disappeared and Eclipse then loaded the pom again, resolved its issue and listed the maven dependencies in Project Explorer. it sounds simple and obvious to resolve visible issues, but since Eclipse was quite happy to run maven, and build successfully, it was not obvious that the red flag and repo issue were at the root of its unwillingness to parse the pom and list the maven dependencies
php delete a single file in directory
<?php
if(isset($_GET['delete'])){
$delurl=$_GET['delete'];
unlink($delurl);
}
?>
<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href=\"$entry\">$entry</a> | <a href=\"?delete=$entry\">Delete</a><br>";
}
}
closedir($handle);
}
?>
This is It
What's the difference between integer class and numeric class in R
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
Return a `struct` from a function in C
As far as I can remember, the first versions of C only allowed to return a value that
could fit into a processor register, which means that you could only return a pointer to
a struct. The same restriction applied to function arguments.
More recent versions allow to pass around larger data objects like structs.
I think this feature was already common during the eighties or early nineties.
Arrays, however, can still be passed and returned only as pointers.
Python: How to get stdout after running os.system?
I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:
import os
batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
fp = open('output.txt', "r")
output = fp.read()
fp.close()
os.remove('output.txt')
print(output)
How do I create a file at a specific path?
where is the file created?
In the application's current working directory. You can use os.getcwd
to check it, and os.chdir
to change it.
Opening file in the root directory probably fails due to lack of privileges.
What is size_t in C?
To go into why size_t
needed to exist and how we got here:
In pragmatic terms, size_t
and ptrdiff_t
are guaranteed to be 64 bits wide on a 64-bit implementation, 32 bits wide on a 32-bit implementation, and so on. They could not force any existing type to mean that, on every compiler, without breaking legacy code.
A size_t
or ptrdiff_t
is not necessarily the same as an intptr_t
or uintptr_t
. They were different on certain architectures that were still in use when size_t
and ptrdiff_t
were added to the Standard in the late ’80s, and becoming obsolete when C99 added many new types but not gone yet (such as 16-bit Windows). The x86 in 16-bit protected mode had a segmented memory where the largest possible array or structure could be only 65,536 bytes in size, but a far
pointer needed to be 32 bits wide, wider than the registers. On those, intptr_t
would have been 32 bits wide but size_t
and ptrdiff_t
could be 16 bits wide and fit in a register. And who knew what kind of operating system might be written in the future? In theory, the i386 architecture offers a 32-bit segmentation model with 48-bit pointers that no operating system has ever actually used.
The type of a memory offset could not be long
because far too much legacy code assumes that long
is exactly 32 bits wide. This assumption was even built into the UNIX and Windows APIs. Unfortunately, a lot of other legacy code also assumed that a long
is wide enough to hold a pointer, a file offset, the number of seconds that have elapsed since 1970, and so on. POSIX now provides a standardized way to force the latter assumption to be true instead of the former, but neither is a portable assumption to make.
It couldn’t be int
because only a tiny handful of compilers in the ’90s made int
64 bits wide. Then they really got weird by keeping long
32 bits wide. The next revision of the Standard declared it illegal for int
to be wider than long
, but int
is still 32 bits wide on most 64-bit systems.
It couldn’t be long long int
, which anyway was added later, since that was created to be at least 64 bits wide even on 32-bit systems.
So, a new type was needed. Even if it weren’t, all those other types meant something other than an offset within an array or object. And if there was one lesson from the fiasco of 32-to-64-bit migration, it was to be specific about what properties a type needed to have, and not use one that meant different things in different programs.
font awesome icon in select option
I used this solution and it worked with Font Awesome 5: https://stackoverflow.com/a/50973559/3813846
What made the difference in my case was to add font-weight: 900;
to the class. Keep in mind to 'fa' to the value.
Example of my code:
<select class="text-primary fa-select" name="class_logo" required>
<option value="fa address-book"> address-book</option>
<option value="fa adjust"> adjust</option>
<option value="fa air-freshener"> air-freshener</option>
</select>
CSS:
.fa-select {
font-family: 'Lato', 'Font Awesome 5 Free';
font-weight: 900;
}
Edit: If you are mixing Solid Icons with Brand Icons in the select, change the CSS as follows:
.fa-select {
font-family: 'Lato', 'Font Awesome 5 Free', 'Font Awesome 5 Brands';
font-weight: 900;
}
CakePHP find method with JOIN
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
matplotlib colorbar in each subplot
This can be easily solved with the the utility make_axes_locatable
. I provide a minimal example that shows how this works and should be readily adaptable:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
m1 = np.random.rand(3, 3)
m2 = np.arange(0, 3*3, 1).reshape((3, 3))
fig = plt.figure(figsize=(16, 12))
ax1 = fig.add_subplot(121)
im1 = ax1.imshow(m1, interpolation='None')
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im1, cax=cax, orientation='vertical')
ax2 = fig.add_subplot(122)
im2 = ax2.imshow(m2, interpolation='None')
divider = make_axes_locatable(ax2)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im2, cax=cax, orientation='vertical');
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error
Whether or not the "date" '0000-00-00" is a valid "date" is irrelevant to the question.
"Just change the database" is seldom a viable solution.
Facts:
- MySQL allows a date with the value of zeros.
- This "feature" enjoys widespread use with other languages.
So, if I "just change the database", thousands of lines of PHP code will break.
Java programmers need to accept the MySQL zero-date and they need to put a zero date back into the database, when other languages rely on this "feature".
A programmer connecting to MySQL needs to handle null and 0000-00-00 as well as valid dates. Changing 0000-00-00 to null is not a viable option, because then you can no longer determine if the date was expected to be 0000-00-00 for writing back to the database.
For 0000-00-00, I suggest checking the date value as a string, then changing it to ("y",1), or ("yyyy-MM-dd",0001-01-01), or into any invalid MySQL date (less than year 1000, iirc). MySQL has another "feature": low dates are automatically converted to 0000-00-00.
I realize my suggestion is a kludge. But so is MySQL's date handling.
And two kludges don't make it right. The fact of the matter is, many programmers will have to handle MySQL zero-dates forever.
Launching a website via windows commandline
IE has a setting, located in Tools
/ Internet options
/ Advanced
/ Browsing
, called Reuse windows for launching shortcuts
, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).
clear data inside text file in c++
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
How to Copy Contents of One Canvas to Another Canvas Locally
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
How do I determine the size of my array in C?
The macro ARRAYELEMENTCOUNT(x)
that everyone is making use of evaluates incorrectly. This, realistically, is just a sensitive matter, because you can't have expressions that result in an 'array' type.
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))
ARRAYELEMENTCOUNT(p + 1);
Actually evaluates as:
(sizeof (p + 1) / sizeof (p + 1[0]));
Whereas
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])
ARRAYELEMENTCOUNT(p + 1);
It correctly evaluates to:
(sizeof (p + 1) / sizeof (p + 1)[0]);
This really doesn't have a lot to do with the size of arrays explicitly. I've just noticed a lot of errors from not truly observing how the C preprocessor works. You always wrap the macro parameter, not an expression in might be involved in.
This is correct; my example was a bad one. But that's actually exactly what should happen. As I previously mentioned p + 1
will end up as a pointer type and invalidate the entire macro (just like if you attempted to use the macro in a function with a pointer parameter).
At the end of the day, in this particular instance, the fault doesn't really matter (so I'm just wasting everyone's time; huzzah!), because you don't have expressions with a type of 'array'. But really the point about preprocessor evaluation subtles I think is an important one.
SQL Add foreign key to existing column
Maybe you got your columns backwards??
ALTER TABLE Employees
ADD FOREIGN KEY (UserID) <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id) <-- this needs to be a column of the ActiveDirectories table
Could it be that the column is called ID
in the Employees
table, and UserID
in the ActiveDirectories
table?
Then your command should be:
ALTER TABLE Employees
ADD FOREIGN KEY (ID) <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID) <-- column in table "ActiveDirectories"
RegEx to parse or validate Base64 data
To validate base64 image we can use this regex
/^data:image/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}
private validBase64Image(base64Image: string): boolean {
const regex = /^data:image\/(?:gif|png|jpeg|bmp|webp)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}/;
return base64Image && regex.test(base64Image);
}
Format decimal for percentage values?
I have found the above answer to be the best solution, but I don't like the leading space before the percent sign. I have seen somewhat complicated solutions, but I just use this Replace addition to the answer above instead of using other rounding solutions.
String.Format("Value: {0:P2}.", 0.8526).Replace(" %","%") // formats as 85.26% (varies by culture)
Use find command but exclude files in two directories
Here's how you can specify that with find
:
find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"
Explanation:
find .
- Start find from current working directory (recursively by default)
-type f
- Specify to find
that you only want files in the results
-name "*_peaks.bed"
- Look for files with the name ending in _peaks.bed
! -path "./tmp/*"
- Exclude all results whose path starts with ./tmp/
! -path "./scripts/*"
- Also exclude all results whose path starts with ./scripts/
Testing the Solution:
$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"
./d/4
./c/3
./e/a
./e/b
./e/5
You were pretty close, the -name
option only considers the basename, where as -path
considers the entire path =)
how to prevent css inherit
Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).
An example of its use:
li * {
display: initial;
}
How to modify existing, unpushed commit messages?
If the commit you want to fix isn’t the most recent one:
git rebase --interactive $parent_of_flawed_commit
If you want to fix several flawed commits, pass the parent of the oldest one of them.
An editor will come up, with a list of all commits since the one you gave.
- Change
pick
to reword
(or on old versions of Git, to edit
) in front of any commits you want to fix.
- Once you save, Git will replay the listed commits.
For each commit you want to reword, Git will drop you back into your editor. For each commit you want to edit, Git drops you into the shell. If you’re in the shell:
- Change the commit in any way you like.
git commit --amend
git rebase --continue
Most of this sequence will be explained to you by the output of the various commands as you go. It’s very easy; you don’t need to memorise it – just remember that git rebase --interactive
lets you correct commits no matter how long ago they were.
Note that you will not want to change commits that you have already pushed. Or maybe you do, but in that case you will have to take great care to communicate with everyone who may have pulled your commits and done work on top of them. How do I recover/resynchronise after someone pushes a rebase or a reset to a published branch?
How do I make a dictionary with multiple keys to one value?
It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.
let's go to the code example,
In [6]: a = 10
In [7]: id(a)
Out[7]: 10914656
In [8]: b = 10
In [9]: id(b)
Out[9]: 10914656
In [10]: c = 11
In [11]: id(c)
Out[11]: 10914688
In [12]: d = 21
In [13]: id(d)
Out[13]: 10915008
In [14]: e = 11
In [15]: id(e)
Out[15]: 10914688
In [16]: e = 21
In [17]: id(e)
Out[17]: 10915008
In [18]: e is d
Out[18]: True
In [19]: e = 30
In [20]: id(e)
Out[20]: 10915296
From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.
so any variable which is having same value shares the memory.
Not for list and dictionary objects
let's come to your question.
when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.
you can simply use it like this
In [49]: dictionary = {
...: 'k1':1,
...: 'k2':1,
...: 'k3':2,
...: 'k4':2}
...:
...:
In [50]: id(dictionary['k1'])
Out[50]: 10914368
In [51]: id(dictionary['k2'])
Out[51]: 10914368
In [52]: id(dictionary['k3'])
Out[52]: 10914400
In [53]: id(dictionary['k4'])
Out[53]: 10914400
From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P
How to auto generate migrations with Sequelize CLI from Sequelize models?
It's 2020 and many of these answers no longer apply to the Sequelize v4/v5/v6 ecosystem.
The one good answer says to use sequelize-auto-migrations
, but probably is not prescriptive enough to use in your project. So here's a bit more color...
Setup
My team uses a fork of sequelize-auto-migrations
because the original repo is has not been merged a few critical PRs. #56 #57 #58 #59
$ yarn add github:scimonster/sequelize-auto-migrations#a063aa6535a3f580623581bf866cef2d609531ba
Edit package.json:
"scripts": {
...
"db:makemigrations": "./node_modules/sequelize-auto-migrations/bin/makemigration.js",
...
}
Process
Note: Make sure you’re using git (or some source control) and database backups so that you can undo these changes if something goes really bad.
- Delete all old migrations if any exist.
- Turn off
.sync()
- Create a mega-migration that migrates everything in your current models (
yarn db:makemigrations --name "mega-migration"
).
- Commit your
01-mega-migration.js
and the _current.json
that is generated.
- if you've previously run
.sync()
or hand-written migrations, you need to “Fake” that mega-migration by inserting the name of it into your SequelizeMeta table. INSERT INTO SequelizeMeta Values ('01-mega-migration.js')
.
- Now you should be able to use this as normal…
- Make changes to your models (add/remove columns, change constraints)
- Run
$ yarn db:makemigrations --name whatever
- Commit your
02-whatever.js
migration and the changes to _current.json
, and _current.bak.json
.
- Run your migration through the normal sequelize-cli:
$ yarn sequelize db:migrate
.
- Repeat 7-10 as necessary
Known Gotchas
- Renaming a column will turn into a pair of
removeColumn
and addColumn
. This will lose data in production. You will need to modify the up and down actions to use renameColumn
instead.
For those who confused how to use renameColumn
, the snippet would look like this. (switch "column_name_before" and "column_name_after" for the rollbackCommands
)
{
fn: "renameColumn",
params: [
"table_name",
"column_name_before",
"column_name_after",
{
transaction: transaction
}
]
}
If you have a lot of migrations, the down action may not perfectly remove items in an order consistent way.
The maintainer of this library does not actively check it. So if it doesn't work for you out of the box, you will need to find a different community fork or another solution.
Convert array to JSON
If you have only 1 object like the one you asked, the following will work.
var x = [{'a':'b'}];
var b= JSON.stringify(x);
var c = b.substring(1,b.length-1);
JSON.parse(c);
Displaying standard DataTables in MVC
Here is the answer in Razor syntax
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
how to have two headings on the same line in html
You should only need to do one of:
- Make them both
inline
(or inline-block
)
- Set them to
float
left or right
You should be able to adjust the height
, padding
, or margin
properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height
.
See this live jsFiddle for an example.
(code of the jsFiddle):
CSS
h2 {
font-size: 50px;
}
h3 {
font-size: 30px;
}
h2, h3 {
width: 50%;
height: 60px;
margin: 0;
padding: 0;
display: inline;
}?
HTML
<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?
What is the `data-target` attribute in Bootstrap 3?
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
Modal Example Code from BS3:
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Regex - Does not contain certain Characters
^[^<>]+$
The caret in the character class ([^
) means match anything but, so this means, beginning of string, then one or more of anything except <
and >
, then the end of the string.