Convert pandas.Series from dtype object to float, and errors to nans
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows
integers to coexist with NaNs. If you have integers in your column,
you can use
pd.__version__
# '0.24.1'
pd.to_numeric(s, errors='coerce').astype('Int32')
0 1
1 2
2 3
3 4
4 NaN
dtype: Int32
There are other options to choose from as well, read the docs for more.
Extension for DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
Understanding React-Redux and mapStateToProps()
import React from 'react';
import {connect} from 'react-redux';
import Userlist from './Userlist';
class Userdetails extends React.Component{
render(){
return(
<div>
<p>Name : <span>{this.props.user.name}</span></p>
<p>ID : <span>{this.props.user.id}</span></p>
<p>Working : <span>{this.props.user.Working}</span></p>
<p>Age : <span>{this.props.user.age}</span></p>
</div>
);
}
}
function mapStateToProps(state){
return {
user:state.activeUser
}
}
export default connect(mapStateToProps, null)(Userdetails);
How to start http-server locally
When you're running npm install
in the project's root, it installs all of the npm dependencies into the project's node_modules
directory.
If you take a look at the project's node_modules
directory, you should see a directory called http-server
, which holds the http-server
package, and a .bin
folder, which holds the executable binaries from the installed dependencies. The .bin
directory should have the http-server
binary (or a link to it).
So in your case, you should be able to start the http-server
by running the following from your project's root directory (instead of npm start
):
./node_modules/.bin/http-server -a localhost -p 8000 -c-1
This should have the same effect as running npm start
.
If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin
folder to your $PATH
environment variable:
export PATH=./node_modules/.bin:$PATH
This will put this folder on your path, and you should be able to simply run
http-server -a localhost -p 8000 -c-1
Visual Studio Code always asking for git credentials
This has been working for me:
1. Set credential hepler to store
$ git config --global credential.helper store
2. then verify if you want:
$ git config --global credential.helper
store
Simple example when using git bash quoted from Here (works for current repo only, use --global
for all repos)
$ git config credential.helper store
$ git push http://example.com/repo.git
Username: < type your username >
Password: < type your password >
[several days later]
$ git push http://example.com/repo.git
[your credentials are used automatically]
Will work for VS Code too.
More detailed example and advanced usage here.
Note: Username & Passwords are not encrypted and stored in plain text format so use it on your personal computer only.
How to add a button dynamically in Android?
public void add_btn() {
lin_btn.setWeightSum(3f);
for (int j = 0; j < 3; j++) {
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.setMargins(10, 0, 0, 10);
params1.weight = 1.0f;
LinearLayout ll;
ll = new LinearLayout(this);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(params1);
final Button btn;
btn = new Button(DynamicActivity.this);
btn.setText("A"+(j+1));
btn.setTextSize(15);
btn.setId(j);
btn.setPadding(10, 8, 10, 10);
ll.addView(btn);
lin_btn.addView(ll);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(v.getId()==0)
{
txt_text.setText("Hii");
}else if(v.getId()==1)
{
txt_text.setText("hello");
}else if(v.getId()==2)
{
txt_text.setText("how r u");
}
}
});
}
}
How do you cache an image in Javascript
I have a similar answer for asynchronous preloading images via JS. Loading them dynamically is the same as loading them normally. they will cache.
as for caching, you can't control the browser but you can set it via server. if you need to load a really fresh resource on demand, you can use the cache buster technique to force load a fresh resource.
difference between new String[]{} and new String[] in java
{}
defines the contents of the array, in this case it is empty. These would both have an array of three String
s
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while []
on the expression side (right side of =
) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place String
s
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]
), then defining an array of length 0 ({}
), and trying to set them to the same array reference (array
) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array
. String array = /* array value*/
is saying, set an array value to a String
, not to an array of String
s.
How do I get the day of week given a date?
If you're not solely reliant on the datetime
module, calendar
might be a better alternative. This, for example, will provide you with the day codes:
calendar.weekday(2017,12,22);
And this will give you the day itself:
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
days[calendar.weekday(2017,12,22)]
Or in the style of python, as a one liner:
["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][calendar.weekday(2017,12,22)]
How should the ViewModel close the form?
There are a lot of comments arguing the pros and cons of MVVM here. For me, I agree with Nir; it's a matter of using the pattern appropriately and MVVM doesn't always fit. People seems to have become willing to sacrifice all of the most important principles of software design JUST to get it to fit MVVM.
That said,..i think your case could be a good fit with a bit of refactoring.
In most cases I've come across, WPF enables you to get by WITHOUT multiple Window
s. Maybe you could try using Frame
s and Page
s instead of Windows with DialogResult
s.
In your case my suggestion would be have LoginFormViewModel
handle the LoginCommand
and if the login is invalid, set a property on LoginFormViewModel
to an appropriate value (false
or some enum value like UserAuthenticationStates.FailedAuthentication
). You'd do the same for a successful login (true
or some other enum value). You'd then use a DataTrigger
which responds to the various user authentication states and could use a simple Setter
to change the Source
property of the Frame
.
Having your login Window return a DialogResult
i think is where you're getting confused; that DialogResult
is really a property of your ViewModel. In my, admittedly limited experience with WPF, when something doesn't feel right it usually because I'm thinking in terms of how i would've done the same thing in WinForms.
Hope that helps.
Have nginx access_log and error_log log to STDOUT and STDERR of master process
When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.
In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).
How to get the text of the selected value of a dropdown list?
Hi if you are having dropdownlist like this
<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">
after giving id to dropdownlist you just need to add jquery code like this
function getHTML()
{
var display=$('#testID option:selected').html();
alert(display);
}
Writing binary number system in C code
Standard C doesn't define binary constants. There's a GNU (I believe) extension though (among popular compilers, clang adapts it as well): the 0b
prefix:
int foo = 0b1010;
If you want to stick with standard C, then there's an option: you can combine a macro and a function to create an almost readable "binary constant" feature:
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
And then you can use it like this:
int foo = B(1010);
If you turn on heavy compiler optimizations, the compiler will most likely eliminate the function call completely (constant folding) or will at least inline it, so this won't even be a performance issue.
Proof:
The following code:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#define B(x) S_to_binary_(#x)
static inline unsigned long long S_to_binary_(const char *s)
{
unsigned long long i = 0;
while (*s) {
i <<= 1;
i += *s++ - '0';
}
return i;
}
int main()
{
int foo = B(001100101);
printf("%d\n", foo);
return 0;
}
has been compiled using clang -o baz.S baz.c -Wall -O3 -S
, and it produced the following assembly:
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main: ## @main
.cfi_startproc
## BB#0:
pushq %rbp
Ltmp2:
.cfi_def_cfa_offset 16
Ltmp3:
.cfi_offset %rbp, -16
movq %rsp, %rbp
Ltmp4:
.cfi_def_cfa_register %rbp
leaq L_.str1(%rip), %rdi
movl $101, %esi ## <= This line!
xorb %al, %al
callq _printf
xorl %eax, %eax
popq %rbp
ret
.cfi_endproc
.section __TEXT,__cstring,cstring_literals
L_.str1: ## @.str1
.asciz "%d\n"
.subsections_via_symbols
So clang
completely eliminated the call to the function, and replaced its return value with 101
. Neat, huh?
How do I crop an image in Java?
This is a method which will work:
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;
public BufferedImage crop(BufferedImage src, Rectangle rect)
{
BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_ARGB_PRE);
Graphics g = dest.getGraphics();
g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null);
g.dispose();
return dest;
}
Of course you have to make your own JComponent:
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.Rectangle;
import java.awt.Graphics;
import javax.swing.JComponent;
public class JImageCropComponent extends JComponent implements MouseListener, MouseMotionListener
{
private BufferedImage img;
private int x1, y1, x2, y2;
public JImageCropComponent(BufferedImage img)
{
this.img = img;
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void setImage(BufferedImage img)
{
this.img = img;
}
public BufferedImage getImage()
{
return this;
}
@Override
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, this);
if (cropping)
{
// Paint the area we are going to crop.
g.setColor(Color.RED);
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
}
}
@Override
public void mousePressed(MouseEvent evt)
{
this.x1 = evt.getX();
this.y1 = evt.getY();
}
@Override
public void mouseReleased(MouseEvent evt)
{
this.cropping = false;
// Now we crop the image;
// This is the method a wrote in the other snipped
BufferedImage cropped = crop(new Rectangle(Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2));
// Now you have the cropped image;
// You have to choose what you want to do with it
this.img = cropped;
}
@Override
public void mouseDragged(MouseEvent evt)
{
cropping = true;
this.x2 = evt.getX();
this.y2 = evt.getY();
}
//TODO: Implement the other unused methods from Mouse(Motion)Listener
}
I didn't test it. Maybe there are some mistakes (I'm not sure about all the imports).
You can put the crop(img, rect)
method in this class.
Hope this helps.
How to use PHP with Visual Studio
Maybe we should help you with a big misunderstanding on your side first: PHP is (like ASP.NET or whatever you used to far) a server side language while javascript is client side.
This means that PHP will run on your webserver and create a HTML page dynamically which is then sent to the browser. Javascript in turn is embedded (either directly or as a referenced file) into this HTML page and runs in the browser.
Maybe you can now understand why your approach so far could never work out.
How to use the COLLATE in a JOIN in SQL Server?
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
Reading a binary file with python
In general, I would recommend that you look into using Python's struct module for this. It's standard with Python, and it should be easy to translate your question's specification into a formatting string suitable for struct.unpack()
.
Do note that if there's "invisible" padding between/around the fields, you will need to figure that out and include it in the unpack()
call, or you will read the wrong bits.
Reading the contents of the file in order to have something to unpack is pretty trivial:
import struct
data = open("from_fortran.bin", "rb").read()
(eight, N) = struct.unpack("@II", data)
This unpacks the first two fields, assuming they start at the very beginning of the file (no padding or extraneous data), and also assuming native byte-order (the @
symbol). The I
s in the formatting string mean "unsigned integer, 32 bits".
How to git ignore subfolders / subdirectories?
All the above answers are valid, but something that I don't think is mentioned is that once you add a file from that directory into the repo, you can't ignore that directory/subdirectory that contains that file (git will ignore that directive).
To ignore already added files run
$ git rm --cached
Otherwise you'll have to remove all files from the repo's target directory first - and then you can ignore that folder.
Android: How to change CheckBox size?
You just need to set the related drawables and set them in the checkbox:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new checkbox"
android:background="@drawable/my_checkbox_background"
android:button="@drawable/my_checkbox" />
The trick is on how to set the drawables. Here's a good tutorial about this.
Bootstrap 4 - Responsive cards in card-columns
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
Setting the default page for ASP.NET (Visual Studio) server configuration
The built-in webserver is hardwired to use Default.aspx as the default page.
The project must have atleast an empty Default.aspx
file to overcome the Directory Listing problem for Global.asax
.
:)
Once you add that empty file all requests can be handled in one location.
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Write("hi@ " + this.Request.Path + "?" + this.Request.QueryString);
this.Response.StatusCode = 200;
this.Response.ContentType = "text/plain";
this.Response.End();
}
}
Moment.js - two dates difference in number of days
Here's how you can get the comprehensive full fledge difference of two dates.
function diffYMDHMS(date1, date2) {
let years = date1.diff(date2, 'year');
date2.add(years, 'years');
let months = date1.diff(date2, 'months');
date2.add(months, 'months');
let days = date1.diff(date2, 'days');
date2.add(days, 'days');
let hours = date1.diff(date2, 'hours');
date2.add(hours, 'hours');
let minutes = date1.diff(date2, 'minutes');
date2.add(minutes, 'minutes');
let seconds = date1.diff(date2, 'seconds');
console.log(years + ' years ' + months + ' months ' + days + ' days ' + hours + '
hours ' + minutes + ' minutes ' + seconds + ' seconds');
return { years, months, days, hours, minutes, seconds};
}
Can't update: no tracked branch
Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".
In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".
Fatal error: iostream: No such file or directory in compiling C program using GCC
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
How to store a datetime in MySQL with timezone info
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
Create Excel file in Java
I've created an API to create an Excel file more easier.
Create Excel - Creating Excel from Template
Just set the required values upon instantiation then invoke execute(), it will be created based on your desired output directory.
But before you use this, you must have an Excel Template which will be use as a template of the newly created Excel file.
Also, you need Apache POI in your project's class path.
MySQL case sensitive query
To improve James' excellent answer:
It's better to put BINARY
in front of the constant instead:
SELECT * FROM `table` WHERE `column` = BINARY 'value'
Putting BINARY
in front of column
will prevent the use of any index on that column.
SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns
I would change the query in the following ways:
- Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the
group by
.
- Combine the second and third subqueries. They are aggregating on the same column. This requires using a
left outer join
to ensure that all data is available.
- By using
count(<fieldname>)
you can eliminate the comparisons to is null
. This is important for the second and third calculated values.
- To combine the second and third queries, it needs to count an id from the
mde
table. These use mde.mdeid
.
The following version follows your example by using union all
:
SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
SUM(TOTALMAILED) as TotalMailed,
SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
from MailDataExtract
where SentDate is not null
group by SentDate
) union all
(select MDE.ReturnMailDate AS ReceiptDate, 0,
COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by MDE.ReturnMailDate;
)
) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;
The following does something similar using full outer join
:
SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
from MailDataExtract
where SentDate is not null
group by cast(SentDate as date)
) sd full outer join
(select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
from MailDataExtract MDE left outer join
DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
group by cast(MDE.ReturnMailDate as date)
) mde
on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;
How can I position my jQuery dialog to center?
Another thing that can give you hell with JQuery Dialog positioning, especially for documents larger than the browser view port - you must add the declaration
<!DOCTYPE html>
At the top of your document.
Without it, jquery tends to put the dialog on the bottom of the page and errors may occur when trying to drag it.
powershell mouse move does not prevent idle mode
I tried a mouse move solution too, and it likewise didn't work. This was my solution, to quickly toggle Scroll Lock every 4 minutes:
Clear-Host
Echo "Keep-alive with Scroll Lock..."
$WShell = New-Object -com "Wscript.Shell"
while ($true)
{
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Milliseconds 100
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Seconds 240
}
I used Scroll Lock because that's one of the most useless keys on the keyboard. Also could be nice to see it briefly blink every now and then. This solution should work for just about everyone, I think.
See also:
How can I pad a String in Java?
Use this function.
private String leftPadding(String word, int length, char ch) {
return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}
how to use?
leftPadding(month, 2, '0');
output:
01 02 03 04 .. 11 12
What's a standard way to do a no-op in python?
If you need a function that behaves as a nop, try
nop = lambda *a, **k: None
nop()
Sometimes I do stuff like this when I'm making dependencies optional:
try:
import foo
bar=foo.bar
baz=foo.baz
except:
bar=nop
baz=nop
# Doesn't break when foo is missing:
bar()
baz()
Check if item is in an array / list
I'm also going to assume that you mean "list" when you say "array." Sven Marnach's solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects
:
subject_set = frozenset(subjects)
if query in subject_set:
# whatever
Use VBA to Clear Immediate Window?
Sub ClearImmediateWindow()
SendKeys "^{g}", False
DoEvents
SendKeys "^{Home}", False
SendKeys "^+{End}", False
SendKeys "{Del}", False
SendKeys "{F7}", False
End Sub
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
This has happened to me as well. The problem is with the mysql repo that comes already with the linux distro. So when you simply do:
$ sudo apt install mysql-server
it installs mysql from their default repo which gives this problem. So to overcome that you need to uninstall that installed mysql
$ sudo apt remove mysql* --purge --auto-remove
Then download mysql repo from official mysql website MySQL APT Repo
Follow their documentation on how to add repo and install it.
This gives no issue.
Also as answered by @zetacu, you can verify that mysql root now indeed uses mysql_native_password plugin
How to pass data between fragments
That depends on how the fragment is structured. If you can have some of the methods on the Fragment Class B static and also the target TextView object static, you can call the method directly on Fragment Class A. This is better than a listener as the method is performed instantaneously, and we don't need to have an additional task that performs listening throughout the activity. See example below:
Fragment_class_B.setmyText(String yourstring);
On Fragment B you can have the method defined as:
public static void setmyText(final String string) {
myTextView.setText(string);
}
Just don't forget to have myTextView set as static on Fragment B, and properly import the Fragment B class on Fragment A.
Just did the procedure on my project recently and it worked. Hope that helped.
An unhandled exception occurred during the execution of the current web request. ASP.NET
Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.
Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.
Solution:
- Find the line that is throwing the exception from the exception details
- In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)
Good luck.
How to Delete a topic in apache kafka
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
- Stop Kafka server
- Delete the topic directory, on each broker (as defined in the
logs.dirs
and log.dir
properties) with rm -rf
command
- Connect to Zookeeper instance:
zookeeper-shell.sh host:port
- From within the Zookeeper instance:
- List the topics using:
ls /brokers/topics
- Remove the topic folder from ZooKeeper using:
rmr /brokers/topics/yourtopic
- Exit the Zookeeper instance (Ctrl+C)
- Restart Kafka server
- Confirm if it was deleted or not by using this command
kafka-topics.sh --list --zookeeper host:port
psql: could not connect to server: No such file or directory (Mac OS X)
I just got the same issue as I have put my machine(ubuntu
) for update and got below error:
could not connect to server: No such file or directory Is the server
running locally and accepting connections on Unix domain socket
"/var/run/postgresql/.s.PGSQL.5432"?
After completing the updating process when I restart my system error gone. And its work like charm as before.. I guess this was happened as pg was updating and another process started.
Android Studio drawable folders
Just to make complete all answers, 'drawable' is, literally, a drawable image, not a complete and ready set of pixels, as .png
In other word words, drawable is only for vectorial images, just try right-click on 'drawable' and go New > Vector Asset, it will accept it, while Image Asset won't be added.
The data for 'drawing', generating the image is recorded on a XML file like this:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M6,18c0,0.55 0.45,1 1,1h1v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,
-0.67 1.5,-1.5L11,19h2v3.5c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5L16,
19h1c0.55,0 1,-0.45 1,-1L18,8L6,8v10zM3.5,8C2.67,8 2,8.67 2,9.5v7c0,0.83 0.67,
1.5 1.5,1.5S5,17.33 5,16.5v-7C5,8.67 4.33,8 3.5,8zM20.5,8c-0.83,0 -1.5,0.67 -1.5,
1.5v7c0,0.83 0.67,1.5 1.5,1.5s1.5,-0.67 1.5,-1.5v-7c0,-0.83 -0.67,-1.5 -1.5,-1.5zM15.53,
2.16l1.3,-1.3c0.2,-0.2 0.2,-0.51 0,-0.71 -0.2,-0.2 -0.51,-0.2 -0.71,0l-1.48,1.48C13.85,
1.23 12.95,1 12,1c-0.96,0 -1.86,0.23 -2.66,0.63L7.85,0.15c-0.2,-0.2 -0.51,-0.2 -0.71,0 -0.2,
0.2 -0.2,0.51 0,0.71l1.31,1.31C6.97,3.26 6,5.01 6,7h12c0,-1.99 -0.97,-3.75 -2.47,-4.84zM10,
5L9,5L9,4h1v1zM15,5h-1L14,4h1v1z"/>
</vector>
That's the code for ic_android_black_24dp
Ellipsis for overflow text in dropdown boxes
You can use this jQuery function instead of plus Bootstrap tooltip
function DDLSToolTipping(ddlsArray) {
$(ddlsArray).each(function (index, ddl) {
DDLToolTipping(ddl)
});
}
function DDLToolTipping(ddlID, maxLength, allowDots) {
if (maxLength == null) { maxLength = 12 }
if (allowDots == null) { allowDots = true }
var selectedOption = $(ddlID).find('option:selected').text();
if (selectedOption.length > maxLength) {
$(ddlID).attr('data-toggle', "tooltip")
.attr('title', selectedOption);
if (allowDots) {
$(ddlID).prev('sup').remove();
$(ddlID).before(
"<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
)
}
}
else if ($(ddlID).attr('title') != null) {
$(ddlID).removeAttr('data-toggle')
.removeAttr('title');
}
}
org.hibernate.QueryException: could not resolve property: filename
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Using python map and other functional tools
How about this:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, [bars]*len(foos))
Android background music service
Create a foreground service with the START_STICKY
flag.
@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
if (startIntent != null) {
String action = startIntent.getAction();
String command = startIntent.getStringExtra(CMD_NAME);
if (ACTION_CMD.equals(action)) {
if (CMD_PAUSE.equals(command)) {
if (mPlayback != null && mPlayback.isPlaying()) {
handlePauseRequest();
}
} else if (CMD_PLAY.equals(command)) {
ArrayList<Track> queue = new ArrayList<>();
for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
queue.add((Track) Parcels.unwrap(input));
}
int index = startIntent.getIntExtra(ARG_INDEX, 0);
playWithQueue(queue, index);
}
}
}
return START_STICKY;
}
This can then be called from any activity to play some music
Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)
You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.
Here's a good tutorial about Playing music in the background on Android
Is there an easy way to attach source in Eclipse?
Just click on attach source and select folder path ... name will be same as folder name (in my case). Remember one thing you need to select path upto project folder base location with "\" at suffix ex D:\MyProject\
Couldn't connect to server 127.0.0.1:27017
This it's because the mongod process it's down, you must to run the commands bellow in order to get up the mongod process:
~$ sudo service mongodb stop
~$ sudo rm /var/lib/mongodb/mongod.lock
~$ sudo mongod --repair --dbpath /var/lib/mongodb
~$ sudo mongod --fork --logpath /var/lib/mongodb/mongodb.log --dbpath /var/lib/mongodb
~$ sudo service mongodb start
Hope this helps you.
Comment out HTML and PHP together
Instead of using HTML comments (which have no effect on PHP code -- which will still be executed), you should use PHP comments:
<?php /*
<tr>
<td><?php echo $entry_keyword; ?></td>
<td><input type="text" name="keyword" value="<?php echo $keyword; ?>" /></td>
</tr>
<tr>
<td><?php echo $entry_sort_order; ?></td>
<td><input name="sort_order" value="<?php echo $sort_order; ?>" size="1" /></td>
</tr>
*/ ?>
With that, the PHP code inside the HTML will not be executed; and nothing (not the HTML, not the PHP, not the result of its non-execution) will be displayed.
Just one note: you cannot nest C-style comments... which means the comment will end at the first */
encountered.
Finding duplicate values in a SQL table
By Using CTE also we can find duplicate value like this
with MyCTE
as
(
select Name,EmailId,ROW_NUMBER() over(PARTITION BY EmailId order by id) as Duplicate from [Employees]
)
select * from MyCTE where Duplicate>1
Regex that accepts only numbers (0-9) and NO characters
Your regex ^[0-9]
matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $
to the end:
^[0-9]*$
This accepts any number of digits, including none. To accept one or more digits, change the *
to +
. To accept exactly one digit, just remove the *
.
UPDATE: You mixed up the arguments to IsMatch
. The pattern should be the second argument, not the first:
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))
CAUTION: In JavaScript, \d
is equivalent to [0-9]
, but in .NET, \d
by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9]
(or supply the RegexOptions.ECMAScript flag).
exception in thread 'main' java.lang.NoClassDefFoundError:
I found one another common reason. If you create the java file inside a package using IDE like eclipse, you will find the package name on the top of your java file like "package pkgName". If you try to run this file from command prompt, you will get the NoClassDefFoundError error. Remove the package name from the java file and use the commands in the command prompt. Wasted 3 hours for this. -- Abhi
Convert audio files to mp3 using ffmpeg
I had to purge my ffmpeg and then install another one from a ppa:
sudo apt-get purge ffmpeg
sudo apt-add-repository -y ppa:jon-severinsson/ffmpeg
sudo apt-get update
sudo apt-get install ffmpeg
Then convert:
ffmpeg -i audio.ogg -f mp3 newfile.mp3
Eclipse: How to build an executable jar with external jar?
As a good practice you can use an Ant Script (Eclipse comes with it) to generate your JAR file. Inside this JAR you can have all dependent libs.
You can even set the MANIFEST's Class-path header to point to files in your filesystem, it's not a good practice though.
Ant build.xml script example:
<project name="jar with libs" default="compile and build" basedir=".">
<!-- this is used at compile time -->
<path id="example-classpath">
<pathelement location="${root-dir}" />
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</path>
<target name="compile and build">
<!-- deletes previously created jar -->
<delete file="test.jar" />
<!-- compile your code and drop .class into "bin" directory -->
<javac srcdir="${basedir}" destdir="bin" debug="true" deprecation="on">
<!-- this is telling the compiler where are the dependencies -->
<classpath refid="example-classpath" />
</javac>
<!-- copy the JARs that you need to "bin" directory -->
<copy todir="bin">
<fileset dir="D:/LIC/xalan-j_2_7_1" includes="*.jar" />
</copy>
<!-- creates your jar with the contents inside "bin" (now with your .class and .jar dependencies) -->
<jar destfile="test.jar" basedir="bin" duplicate="preserve">
<manifest>
<!-- Who is building this jar? -->
<attribute name="Built-By" value="${user.name}" />
<!-- Information about the program itself -->
<attribute name="Implementation-Vendor" value="ACME inc." />
<attribute name="Implementation-Title" value="GreatProduct" />
<attribute name="Implementation-Version" value="1.0.0beta2" />
<!-- this tells which class should run when executing your jar -->
<attribute name="Main-class" value="ApplyXPath" />
</manifest>
</jar>
</target>
Resize UIImage by keeping Aspect ratio and width
Well, we have few good answers here for resizing image, but I just modify as per my need. hope this help someone like me.
My Requirement was
- If image width is more than 1920, resize it with 1920 width and maintaining height with original aspect ratio.
- If image height is more than 1080, resize it with 1080 height and maintaining width with original aspect ratio.
if (originalImage.size.width > 1920)
{
CGSize newSize;
newSize.width = 1920;
newSize.height = (1920 * originalImage.size.height) / originalImage.size.width;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
if (originalImage.size.height > 1080)
{
CGSize newSize;
newSize.width = (1080 * originalImage.size.width) / originalImage.size.height;
newSize.height = 1080;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Thanks to @Srikar Appal , for resizing I have used his method.
You may like to check this as well for resize calculation.
Skip over a value in the range function in python
It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:
import itertools
m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i) # skips m = 5
As an aside, you woudn't want to use (*range(m), *range(m + 1, n))
even though it works because it will expand the iterables into a tuple and this is memory inefficient.
Credit: comment by njzk2, answer by Locke
Cookie blocked/not saved in IFRAME in Internet Explorer
I've spend a large part of my day looking into this P3P thing and I feel the need to share what I've found out.
I've noticed that the P3P concept is very outdated and seems only to be really used/enforced by Internet Explorer (IE).
The simplest explanation is: IE wants you to define a P3P header if you are using cookies.
This is a nice idea, and luckily most of the time not providing this header won't cause any issues (read browser warnings). Unless your website/web application is loaded into an other website using an (i)Frame. This is where IE becomes a massive pain in the ***. It will not allow you to set a cookie unless the P3P header is set.
Knowing this I wanted to find an answer to the following two questions:
- Who cares? In other words, can I be sued if I put the word "Potato" in the header?
- What do other companies do?
My findings are:
- No one cares. I'm unable to find a single document that suggests this technology has any legal weight. During my research I didn't find a single country around the world that has adopted a law that prevents you from putting the word "Potato" in the P3P header
- Both Google and Facebook put a link in their P3P header field referring to a page describing why they don't have a P3P header.
The concept was born in 2002 and it baffles me that this outdated and legally unimplemented concept is still forced upon developers within IE.
If this header doesn't have have any legal ramifications this header should be ignored (or alternatively, generate a warning or notification in the console). Not enforced! I'm now forced to put a line in my code (and send a header to the client) that does absolutely nothing.
In short - to keep IE happy - add the following line to your PHP code (Other languages should look similar)
header('P3P: CP="Potato"');
Problem solved, and IE is happy with this potato.
Java function for arrays like PHP's join()?
java.util.Arrays has an 'asList' method. Together with the java.util.List/ArrayList API this gives you all you need:;
private static String[] join(String[] array1, String[] array2) {
List<String> list = new ArrayList<String>(Arrays.asList(array1));
list.addAll(Arrays.asList(array2));
return list.toArray(new String[0]);
}
Increase heap size in Java
Can I increase the heap memory to 75%
of physical memory(6GB Heap).
Yes you can. In fact, you can increase to more than the amount of physical memory, if you want to.
Whether it is a good idea to do this depends on how much else is running on your system. In particular, if the "working set" of the applications and services that are currently running significantly exceeds the available physical memory, your system is liable to "thrash", spending a lot of time moving virtual memory pages to and from disk. The net effect is that the system gets horribly slow.
How do I run a file on localhost?
Localhost is the computer you're using right now. You run things by typing commands at the command prompt and pressing Enter. If you're asking how to run things from your programming environment, then the answer depends on which environment you're using. Most languages have commands with names like system
or exec
for running external programs. You need to be more specific about what you're actually looking to do, and what obstacles you've encountered while trying to achieve it.
How would I get everything before a : in a string Python
You don't need regex
for this
>>> s = "Username: How are you today?"
You can use the split
method to split the string on the ':'
character
>>> s.split(':')
['Username', ' How are you today?']
And slice out element [0]
to get the first part of the string
>>> s.split(':')[0]
'Username'
Compare if BigDecimal is greater than zero
it is safer to use the method compareTo()
BigDecimal a = new BigDecimal(10);
BigDecimal b = BigDecimal.ZERO;
System.out.println(" result ==> " + a.compareTo(b));
console print
result ==> 1
compareTo()
returns
- 1 if a is greater than b
- -1 if b is less than b
- 0 if a is equal to b
now for your problem you can use
if (value.compareTo(BigDecimal.ZERO) > 0)
or
if (value.compareTo(new BigDecimal(0)) > 0)
I hope it helped you.
Recommended way to insert elements into map
To quote:
Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.
So insert will not change the value if the key already exists, the [] operator
will.
EDIT:
This reminds me of another recent question - why use at()
instead of the [] operator
to retrieve values from a vector. Apparently at()
throws an exception if the index is out of bounds whereas [] operator
doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.
My guess is that, internally, insert()
will first check for the entry and afterwards itself use the [] operator
.
Getting attributes of Enum's value
Alternatively, you could do the following:
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in typeof(PaymentTerm).GetEnumValues())
{
var type = item.GetType();
var name = type.GetField(item.ToString()).GetCustomAttributesData().FirstOrDefault()?.NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
selectListItems.Add(new SelectListItem(name, type.Name));
}
Java: Detect duplicates in ArrayList?
If you want the set of duplicate values:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FindDuplicateInArrayList {
public static void main(String[] args) {
Set<String> uniqueSet = new HashSet<String>();
List<String> dupesList = new ArrayList<String>();
for (String a : args) {
if (uniqueSet.contains(a))
dupesList.add(a);
else
uniqueSet.add(a);
}
System.out.println(uniqueSet.size() + " distinct words: " + uniqueSet);
System.out.println(dupesList.size() + " dupesList words: " + dupesList);
}
}
And probably also think about trimming values or using lowercase ... depending on your case.
Return value from exec(@sql)
On the one hand you could use sp_executesql:
exec sp_executesql N'select @rowcount=count(*) from anytable',
N'@rowcount int output', @rowcount output;
On the other hand you could use a temporary table:
declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);
How to split() a delimited string to a List<String>
Include using namespace System.Linq
List<string> stringList = line.Split(',').ToList();
you can make use of it with ease for iterating through each item.
foreach(string str in stringList)
{
}
String.Split()
returns an array, hence convert it to a list using ToList()
PHP: Possible to automatically get all POSTed data?
No one mentioned Raw Post Data, but it's good to know, if posted data has no key, but only value, use Raw Post Data:
$postdata = file_get_contents("php://input");
PHP Man:
php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".
Jquery each - Stop loop and return object
Try this ...
someArray = new Array();
someArray[0] = 't5';
someArray[1] = 'z12';
someArray[2] = 'b88';
someArray[3] = 's55';
someArray[4] = 'e51';
someArray[5] = 'o322';
someArray[6] = 'i22';
someArray[7] = 'k954';
var test = findXX('o322');
console.log(test);
function findXX(word)
{
for(var i in someArray){
if(someArray[i] == word)
{
return someArray[i]; //<--- stop the loop!
}
}
}
Change header text of columns in a GridView
On your asp.net page add the gridview
<asp:GridView ID="GridView1" onrowdatabound="GridView1_RowDataBound" >
</asp:GridView>
Create a method protected void method in your c# class called GridView1_RowDataBound
as
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "HeaderText";
}
}
Everything should be working fine.
How to turn NaN from parseInt into 0 for an empty string?
For people who are not restricted to parseInt
, you can use the bitwise OR operator (which implicitly calls ToInt32
to its operands).
var value = s | 0;
// NaN | 0 ==>> 0
// '' | 0 ==>> 0
// '5' | 0 ==>> 5
// '33Ab' | 0 ==>> 0
// '0x23' | 0 ==>> 35
// 113 | 0 ==>> 113
// -12 | 0 ==>> -12
// 3.9 | 0 ==>> 3
Note: ToInt32
is different from parseInt
. (i.e. parseInt('33Ab') === 33
)
Rotate image with javascript
You use a combination of CSS's transform
(with vendor prefixes as necessary) and transform-origin
, like this: (also on jsFiddle)
_x000D_
_x000D_
var angle = 0,_x000D_
img = document.getElementById('container');_x000D_
document.getElementById('button').onclick = function() {_x000D_
angle = (angle + 90) % 360;_x000D_
img.className = "rotate" + angle;_x000D_
}
_x000D_
#container {_x000D_
width: 820px;_x000D_
height: 100px;_x000D_
overflow: hidden;_x000D_
}_x000D_
#container.rotate90,_x000D_
#container.rotate270 {_x000D_
width: 100px;_x000D_
height: 820px_x000D_
}_x000D_
#image {_x000D_
transform-origin: top left;_x000D_
/* IE 10+, Firefox, etc. */_x000D_
-webkit-transform-origin: top left;_x000D_
/* Chrome */_x000D_
-ms-transform-origin: top left;_x000D_
/* IE 9 */_x000D_
}_x000D_
#container.rotate90 #image {_x000D_
transform: rotate(90deg) translateY(-100%);_x000D_
-webkit-transform: rotate(90deg) translateY(-100%);_x000D_
-ms-transform: rotate(90deg) translateY(-100%);_x000D_
}_x000D_
#container.rotate180 #image {_x000D_
transform: rotate(180deg) translate(-100%, -100%);_x000D_
-webkit-transform: rotate(180deg) translate(-100%, -100%);_x000D_
-ms-transform: rotate(180deg) translateX(-100%, -100%);_x000D_
}_x000D_
#container.rotate270 #image {_x000D_
transform: rotate(270deg) translateX(-100%);_x000D_
-webkit-transform: rotate(270deg) translateX(-100%);_x000D_
-ms-transform: rotate(270deg) translateX(-100%);_x000D_
}
_x000D_
<button id="button">Click me!</button>_x000D_
<div id="container">_x000D_
<img src="http://i.stack.imgur.com/zbLrE.png" id="image" />_x000D_
</div>
_x000D_
_x000D_
_x000D_
How to give a pattern for new line in grep?
try pcregrep
instead of regular grep
:
pcregrep -M "pattern1.*\n.*pattern2" filename
the -M
option allows it to match across multiple lines, so you can search for newlines as \n
.
Convert YYYYMMDD string date to a datetime value
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
Very simple log4j2 XML configuration file using Console and File appender
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
printing a two dimensional array in python
In addition to the simple print answer, you can actually customise the print output through the use of the numpy.set_printoptions function.
Prerequisites:
>>> import numpy as np
>>> inf = np.float('inf')
>>> A = np.array([[0,1,4,inf,3],[1,0,2,inf,4],[4,2,0,1,5],[inf,inf,1,0,3],[3,4,5,3,0]])
The following option:
>>> np.set_printoptions(infstr="(infinity)")
Results in:
>>> print(A)
[[ 0. 1. 4. (infinity) 3.]
[ 1. 0. 2. (infinity) 4.]
[ 4. 2. 0. 1. 5.]
[(infinity) (infinity) 1. 0. 3.]
[ 3. 4. 5. 3. 0.]]
The following option:
>>> np.set_printoptions(formatter={'float': "\t{: 0.0f}\t".format})
Results in:
>>> print(A)
[[ 0 1 4 inf 3 ]
[ 1 0 2 inf 4 ]
[ 4 2 0 1 5 ]
[ inf inf 1 0 3 ]
[ 3 4 5 3 0 ]]
If you just want to have a specific string output for a specific array, the function numpy.array2string is also available.
Is there a developers api for craigslist.org
The closest I have been able to find is called 3taps. 3taps was sued by Craigslist with the result that "access to public data on a public website can be selectively censored by blacklisting certain viewers (i.e. competitors)", and thus states that "3taps will therefore access the very same data exclusively from public sources that retain open and equal access rights to public data".
What is HTTP "Host" header?
The Host
Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host
header does not match any of the configured virtual hosts.
That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).
Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.
This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.
Although the webserver would know the hostname from Server Name Indication, the Host
header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host
header is still valid (and necessary).
Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host
header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD
RESOURCE
and PROTOCOL VERSION
and at least the Host
header, like this:
GET /someresource.html HTTP/1.1
Host: www.example.com
In the MDN Documentation on the "Host" header they actually phrase it like this:
A Host header field must be sent in all HTTP/1.1 request messages. A
400 (Bad Request) status code will be sent to any HTTP/1.1 request
message that lacks a Host header field or contains more than one.
As mentioned by Darrel Miller, the complete specs can be found in RFC7230.
How to display a Yes/No dialog box on Android?
AlertDialog.Builder altBx = new AlertDialog.Builder(this);
altBx.setTitle("My dialog box");
altBx.setMessage("Welcome, Please Enter your name");
altBx.setIcon(R.drawable.logo);
altBx.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
if(edt.getText().toString().length()!=0)
{
// Show any message
}
else
{
}
}
});
altBx.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
//show any message
}
});
altBx.show();
PHP Excel Header
The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.
I know i came in late but it can help future readers of this post.
MongoDB not equal to
If there is a null
in an array and you want to avoid it:
db.test.find({"contain" : {$ne :[] }}).pretty()
sql like operator to get the numbers only
You can try this
ISNUMERIC (Transact-SQL)
ISNUMERIC returns 1 when the input
expression evaluates to a valid
numeric data type; otherwise it
returns 0.
DECLARE @Table TABLE(
Col VARCHAR(50)
)
INSERT INTO @Table SELECT 'ABC'
INSERT INTO @Table SELECT 'Italy'
INSERT INTO @Table SELECT 'Apple'
INSERT INTO @Table SELECT '234.62'
INSERT INTO @Table SELECT '2:234:43:22'
INSERT INTO @Table SELECT 'France'
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2'
INSERT INTO @Table SELECT 'Lions'
SELECT *
FROM @Table
WHERE ISNUMERIC(Col) = 1
Change drawable color programmatically
This worked for me. Make sure to put "ff" between 0x and color code. Like this 0xff2196F3
Drawable mDrawable = ContextCompat.getDrawable(MainActivity.this,R.drawable.ic_vector_home);
mDrawable.setColorFilter(new
PorterDuffColorFilter(0xff2196F3,PorterDuff.Mode.SRC_IN));
Escape invalid XML characters in C#
string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.EncodeName(UnfilteredString);
}
string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.DecodeName(UnfilteredString);
}
This simple method replace the invalid characters with the same value but accepted in the XML context.
To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).
Document directory path of Xcode Device Simulator
Where is the Documents Directory for the iOS 8 Simulator
You may have noticed that the iPhone Simulator has changed with Xcode 6, and with it – of course – the path to your simulated apps’ Documents Directory. At times we may need to take a look at it.
Finding that path is not as easy as it was once, namely Library/Application Support/iPhone Simulator/7.1/Applications/ followed by a cryptic number representing your app.
As of Xcode 6 and iOS 8 you’ll find it here:
Library/Developer/CoreSimulator/Devices/cryptic number/data/Containers/Data/Application/cryptic number
http://pinkstone.co.uk/where-is-the-documents-directory-for-the-ios-8-simulator/
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... }
-- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.
As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are
- define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
- use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
- define a function on the parent scope, and call it from the child (not always possible)
New AngularJS developers often do not realize that ng-repeat
, ng-switch
, ng-view
, ng-include
and ng-if
all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch
.
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1">
<!--rather than
<input type="text" ng-model="prop1">`
-->
L-o-n-g answer:
JavaScript Prototypal Inheritance
Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes
It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.
Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:
(Note that to save space, I show the anArray
object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)
If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:
childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'
Suppose we then do this:
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.
Suppose we then do this:
childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)
Suppose we then do this:
childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }
The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.
Takeaways:
- If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
- If we set childScope.propertyX, the prototype chain is not consulted.
One last scenario:
delete childScope.anArray
childScope.anArray[1] === 22 // true
We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.
Angular Scope Inheritance
The contenders:
- The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with
scope: true
, directive with transclude: true
.
- The following creates a new scope which does not inherit prototypically: directive with
scope: { ... }
. This creates an "isolate" scope instead.
Note, by default, directives do not create new scope -- i.e., the default is scope: false
.
ng-include
Suppose we have in our controller:
$scope.myPrimitive = 50;
$scope.myObject = {aNumber: 11};
And in our HTML:
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
Each ng-include generates a new child scope, which prototypically inherits from the parent scope.
Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive
scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.
Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.
We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:
<input ng-model="$parent.myPrimitive">
Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).
For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.
For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,
// in the parent scope
$scope.setMyPrimitive = function(value) {
$scope.myPrimitive = value;
}
Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)
See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.
ng-switch
ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.
See also AngularJS, bind scope of a switch-case?
ng-repeat
Ng-repeat works a little differently. Suppose we have in our controller:
$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects = [{num: 101}, {num: 202}]
And in our HTML:
<ul><li ng-repeat="num in myArrayOfPrimitives">
<input ng-model="num">
</li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
<input ng-model="obj.num">
</li>
<ul>
For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:
childScope = scope.$new(); // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value; // creates a new childScope property
If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num
) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num
property that is independent of the myArrayOfPrimitives array:
This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.
So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num
) does change the object the parent scope references. So in the second ng-repeat above, we have:
(I colored one line gray just so that it is clear where it is going.)
This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.
See also Difficulty with ng-model, ng-repeat, and inputs and
https://stackoverflow.com/a/13782671/215945
ng-controller
Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply.
However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/
A service should be used to share data between controllers instead.
(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties.
See also Controller load order differs when loading or navigating)
directives
- default (
scope: false
) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope.
Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp
in the isolated scope: <div my-directive>
and scope: { localProp: '@parentProp' }
. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp>
and scope: { localProp: '@theParentProp' }
.
Isolate scope's __proto__
references Object.
Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
For the picture below we have
<my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2">
and
scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
For the picture below, assume the same directive as above with this addition: transclude: true
This fiddle has a showScope()
function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.
Summary
There are four types of scopes:
- normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with
scope: true
- normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
- isolate scope -- directive with
scope: {...}
. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
- transcluded scope -- directive with
transclude: true
. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.
For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.
Diagrams were generated with graphviz "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.
How do I write a compareTo method which compares objects?
if (s.compareTo(t) > 0)
will compare string s to string t and return the int value you want.
public int Compare(Object obj) // creating a method to compare {
Student s = (Student) obj; //creating a student object
// compare last names
return this.lastName.compareTo(s.getLastName());
}
Now just test for a positive negative return from the method as you would have normally.
Cheers
How do I put all required JAR files in a library folder inside the final JAR file with Maven?
The simplest and the most efficient way is to use an uber plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>uber-${project.artifactId}-${project.version}</finalName>
</configuration>
</plugin>
You will have de-normalized all in one JAR file.
How do I set up Vim autoindentation properly for editing Python files?
Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.
In vim type
:help vimrc
and check your path to the _vimrc/.vimrc file with
:echo $HOME
:echo $VIM
Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.
:help source
JNI and Gradle in Android Studio
gradle supports ndk compilation by generating another Android.mk file with absolute paths to your sources.
NDK supports absolute paths since r9 on OSX, r9c on Windows, so you need to upgrade your NDK to r9+.
You may run into other troubles as NDK support by gradle is preliminary. If so you can deactivate the ndk compilation from gradle by setting:
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDir 'src/main/libs'
}
to be able to call ndk-build yourself and integrate libs from libs/.
btw, you have any issue compiling for x86 ? I see you haven't included it in your APP_ABI.
state provider and route provider in angularJS
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
How to convert JSON object to JavaScript array?
You can insert object items to an array as this
_x000D_
_x000D_
let obj = {_x000D_
'1st': {_x000D_
name: 'stackoverflow'_x000D_
},_x000D_
'2nd': {_x000D_
name: 'stackexchange'_x000D_
}_x000D_
};_x000D_
_x000D_
let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
_x000D_
console.log(wholeArray);
_x000D_
_x000D_
_x000D_
Resizing an image in an HTML5 canvas
So something interesting that I found a while ago while working with canvas that might be helpful:
To resize the canvas control on its own, you need to use the height=""
and width=""
attributes (or canvas.width
/canvas.height
elements). If you use CSS to resize the canvas, it will actually stretch (i.e.: resize) the content of the canvas to fit the full canvas (rather than simply increasing or decreasing the area of the canvas.
It'd be worth a shot to try drawing the image into a canvas control with the height and width attributes set to the size of the image and then using CSS to resize the canvas to the size you're looking for. Perhaps this would use a different resizing algorithm.
It should also be noted that canvas has different effects in different browsers (and even different versions of different browsers). The algorithms and techniques used in the browsers is likely to change over time (especially with Firefox 4 and Chrome 6 coming out so soon, which will place heavy emphasis on canvas rendering performance).
In addition, you may want to give SVG a shot, too, as it likely uses a different algorithm as well.
Best of luck!
Wordpress plugin install: Could not create directory
For me the problem was FTP server that WP is using to upload update. It had writting disabled in configuration, so just enabling it fixed the problem.
Shame on WordPress for providing such misleading error message.
How to return a string value from a Bash function
To illustrate my comment on Andy's answer, with additional file descriptor manipulation to avoid use of /dev/tty
:
#!/bin/bash
exec 3>&1
returnString() {
exec 4>&1 >&3
local s=$1
s=${s:="some default string"}
echo "writing to stdout"
echo "writing to stderr" >&2
exec >&4-
echo "$s"
}
my_string=$(returnString "$*")
echo "my_string: [$my_string]"
Still nasty, though.
exceeds the list view threshold 5000 items in Sharepoint 2010
I had the same problem.please do the following it may help you:
By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.
To Change the LVT:
- Click SharePoint Central Administration,
- Go to Application Management
- Manage Web Applications
- Select your application
- Click General Settings at the ribbon
- Select Resource Throttling
- List View Threshold limit --> change the value to your need.
- Also change the List View Threshold for Auditors and Administrators.if you are a administrator.
Click OK to save it.
Converting between datetime and Pandas Timestamp objects
To answer the question of going from an existing python datetime to a pandas Timestamp do the following:
import time, calendar, pandas as pd
from datetime import datetime
def to_posix_ts(d: datetime, utc:bool=True) -> float:
tt=d.timetuple()
return (calendar.timegm(tt) if utc else time.mktime(tt)) + round(d.microsecond/1000000, 0)
def pd_timestamp_from_datetime(d: datetime) -> pd.Timestamp:
return pd.to_datetime(to_posix_ts(d), unit='s')
dt = pd_timestamp_from_datetime(datetime.now())
print('({}) {}'.format(type(dt), dt))
Output:
(<class 'pandas._libs.tslibs.timestamps.Timestamp'>) 2020-09-05 23:38:55
I was hoping for a more elegant way to do this but the to_posix_ts
is already in my standard tool chain so I'm moving on.
How does `scp` differ from `rsync`?
scp is best for one file.
OR a combination of tar
& compression for smaller data sets
like source code trees with small resources (ie: images, sqlite etc).
Yet, when you begin dealing with
larger volumes say:
- media folders (40 GB)
- database backups (28 GB)
- mp3 libraries (100 GB)
It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.
As an exercise, you can do some gymnastics like piping tar
into ssh
and redirecting the results into a remote file. (saving the need to build
a swap or temporary clone aka zip or tar.gz)
However,
rsync simplify's this process and allows you to transfer data without consuming any additional disc space.
Also,
Continuous (cron?) updates use minimal changes vs full cloned copies speed
up large data migrations over time.
tl;dr
scp
== small scale (with room to build compressed files on the same drive)
rsync
== large scale (with the necessity to backup large data and no room left)
Static variable inside of a function in C
6 and 7
Because static variable intialise only once,
So 5++ becomes 6 at 1st call
6++ becomes 7 at 2nd call
Note-when 2nd call occurs it takes x value is 6 instead of 5 because x is static variable.
Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-
This is happening because you have not configured your mapping.xml file correctly for id fields as below:-
<id name="id">
<column name="id" sql-type="bigint" not-null="true"/>
<generator class="hibernateGeneratorClass"</generator>
</id>
Overload the getsession method to accept a Parameter like isSessionClear,
and clear the session before returning the current session like below
public static Session getSession(boolean isSessionClear) {
if (session.isOpen() && isSessionClear) {
session.clear();
return session;
} else if (session.isOpen()) {
return session;
} else {
return sessionFactory.openSession();
}
}
This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.
How to determine if a list of polygon points are in clockwise order?
find the center of mass of these points.
suppose there are lines from this point to your points.
find the angle between two lines for line0 line1
than do it for line1 and line2
...
...
if this angle is monotonically increasing than it is counterclockwise ,
else if monotonically decreasing it is clockwise
else (it is not monotonical)
you cant decide, so it is not wise
How can I get the Windows last reboot reason
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type eventvwr.msc
, and press Enter.
If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on
System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the USER32
box.
B) In the All Event IDs field, type 1074
, then click/tap on OK.
C) This will give you a list of power off (shutdown) and restart
Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events
with power off as the Shutdown Type. You will notice the date and
time, and what user was responsible for shutting down the computer per
power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type 6008
, then click/tap on OK.
B) This will give you a list of unexpected shutdown events at the
top of the middle pane in Event Viewer. You can scroll through these
listed events to see the date and time of each one.
Write a function that returns the longest palindrome in a given string
I was asked this question recently. Here's the solution I [eventually] came up with. I did it in JavaScript because it's pretty straightforward in that language.
The basic concept is that you walk the string looking for the smallest multi-character palindrome possible (either a two or three character one). Once you have that, expand the borders on both sides until it stops being a palindrome. If that length is longer than current longest one, store it and move along.
// This does the expanding bit.
function getsize(s, start, end) {
var count = 0, i, j;
for (i = start, j = end; i >= 0 && j < s.length; i--, j++) {
if (s[i] !== s[j]) {
return count;
}
count = j - i + 1; // keeps track of how big the palindrome is
}
return count;
}
function getBiggestPalindrome(s) {
// test for simple cases
if (s === null || s === '') { return 0; }
if (s.length === 1) { return 1; }
var longest = 1;
for (var i = 0; i < s.length - 1; i++) {
var c = s[i]; // the current letter
var l; // length of the palindrome
if (s[i] === s[i+1]) { // this is a 2 letter palindrome
l = getsize(s, i, i+1);
}
if (i+2 < s.length && s[i] === s[i+2]) { // 3 letter palindrome
l = getsize(s, i+1, i+1);
}
if (l > longest) { longest = l; }
}
return longest;
}
This could definitely be cleaned up and optimized a little more, but it should have pretty good performance in all but the worst case scenario (a string of the same letter).
Checking if form has been submitted - PHP
Try this
<form action="" method="POST" id="formaddtask">
Add Task: <input type="text"name="newtaskname" />
<input type="submit" value="Submit"/>
</form>
//Check if the form is submitted
if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['newtaskname'])){
}
Pandas timeseries plot setting x-axis major and minor ticks and labels
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
How to call javascript function from code-behind
This is a way to invoke one or more JavaScript methods from the code behind.
By using Script Manager we can call the methods in sequence. Consider the below code for example.
ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",
"$(document).ready(function(){EnableControls();
alert('Overrides successfully Updated.');
DisableControls();});",
true);
In this first method EnableControls() is invoked.
Next the alert will be displayed.
Next the DisableControls() method will be invoked.
How to extract multiple JSON objects from one file?
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
How can apply multiple background color to one div
The A div can actually be made without :before
or :after
selector but using linear gradient as your first try. The only difference is that you must specify 4 positions. Dark grey from 0 to 50% and ligth grey from 50% to 100% like this:
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%);
As you know, B div is made from a linear gradient having 2 positions like this:
background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%);
For the C div, i use the same kind of gradient as div A ike this:
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%);
But this time i used the :after
selector with a white background like if the second part of your div was smaller. * Please note that I added a better alternative below.
Check this jsfiddle or the snippet below for complete cross-browser code.
_x000D_
_x000D_
div{_x000D_
position:relative;_x000D_
width:80%;_x000D_
height:100px;_x000D_
color:red;_x000D_
text-align:center;_x000D_
line-height:100px;_x000D_
margin-bottom:10px;_x000D_
}_x000D_
_x000D_
.a{_x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#f6f6f6), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.b{_x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.c{ _x000D_
background: #9c9e9f; /* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%); /* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#33ccff), color-stop(100%,#33ccff)); /* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#33ccff',GradientType=1 ); /* IE6-9 */_x000D_
}_x000D_
.c:after{_x000D_
content:"";_x000D_
position:absolute;_x000D_
right:0;_x000D_
bottom:0;_x000D_
width:50%;_x000D_
height:20%;_x000D_
background-color:white;_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
_x000D_
_x000D_
There is also an alternative for the C div without using a white background to hide the a part of the second section.
Instead, we make the second part transparent and we use the :after
selector to act as a colored background with the desired position and size.
See this jsfiddle or the snippet below for this updated solution.
_x000D_
_x000D_
div {_x000D_
position: relative;_x000D_
width: 80%;_x000D_
height: 100px;_x000D_
color: red;_x000D_
text-align: center;_x000D_
line-height: 100px;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.a {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, #f6f6f6), color-stop(100%, #f6f6f6));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.b {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(100%, #f6f6f6));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #f6f6f6 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.c {_x000D_
background: #9c9e9f;_x000D_
/* Old browsers */_x000D_
background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* FF3.6+ */_x000D_
background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0)));_x000D_
/* Chrome,Safari4+ */_x000D_
background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* Chrome10+,Safari5.1+ */_x000D_
background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* Opera 11.10+ */_x000D_
background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* IE10+ */_x000D_
background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%);_x000D_
/* W3C */_x000D_
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#ffffff00', GradientType=1);_x000D_
/* IE6-9 */_x000D_
}_x000D_
_x000D_
.c:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
right: 0;_x000D_
top: 0;_x000D_
width: 50%;_x000D_
height: 80%;_x000D_
background-color: #33ccff;_x000D_
z-index: -1_x000D_
}
_x000D_
<div class="a">A</div>_x000D_
<div class="b">B</div>_x000D_
<div class="c">C</div>
_x000D_
_x000D_
_x000D_
WampServer orange icon
I ran into this same problem this morning but none of the answers above provided me with the solution.
I realised eventually that my issue was because I had changed the DocumentRoot to a subfolder of the www directory, as I had previously been running a Symfony2 project inside www.
With the new project I am working on inside www, that old DocumentRoot dir did not exist any more so Apache failed to start.
wampserver -> Apache -> httpd.conf, then look for "DocumentRoot" and make sure the directory it points to exists or else change it to one that does.
Thank you to RiggsFolly, it was because of your hint about the Event Viewer above that I found the issue.
How do synchronized static methods work in Java and can I use it for loading Hibernate entities?
static synchronized
means holding lock on the the class's Class
object
where as
synchronized
means holding lock on that class's object itself. That means, if you are accessing a non-static synchronized method in a thread (of execution) you still can access a static synchronized method using another thread.
So, accessing two same kind of methods(either two static or two non-static methods) at any point of time by more than a thread is not possible.
CALL command vs. START with /WAIT option
This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.
In the end, piping the command through more did the trick.
setup.exe {arguments} | more
What's the best way to do a backwards loop in C/C#/C++?
I would always prefer clear code against 'typographically pleasing' code.
Thus, I would always use :
for (int i = myArray.Length - 1; i >= 0; i--)
{
// Do something ...
}
You can consider it as the standard way to loop backwards.
Just my two cents...
Javascript: console.log to html
Slight improvement on @arun-p-johny answer:
In html,
<pre id="log"></pre>
In js,
(function () {
var old = console.log;
var logger = document.getElementById('log');
console.log = function () {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'object') {
logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
} else {
logger.innerHTML += arguments[i] + '<br />';
}
}
}
})();
Start using:
console.log('How', true, new Date());
Access iframe elements in JavaScript
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
not working for me but I found another solution. Use:
window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')
I checked it on Firefox and Chrome.
JComboBox Selection Change Listener?
It should respond to ActionListeners, like this:
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
doSomething();
}
});
@John Calsbeek rightly points out that addItemListener()
will work, too. You may get 2 ItemEvents
, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!
Get the time difference between two datetimes
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
Adjust width of input field to its input
You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.
An input could dynamically adjust it's size by listening for key events.
For example
$("input[type='text']").bind('keyup', function () {
$(this).attr("size", $(this).val().length );
});
JsFiddle here
How to escape single quotes in MySQL
If you want to keep (')
apostrophe in the database use this below code:
$new_value = str_replace("'","\'", $value);
$new_value
can store in database.
Link vs compile vs controller
I wanted to add also what the O'Reily AngularJS book by the Google Team has to say:
Controller - Create a controller which publishes an API for communicating across directives. A good example is Directive to Directive Communication
Link - Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.
Compile - Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.
How to do a newline in output
I would like to share my experience with \n
I came to notice that "\n" works as-
puts "\n\n" // to provide 2 new lines
but not
p "\n\n"
also
puts '\n\n'
Doesn't works.
Hope will work for you!!
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):
app.get('somethingelse', function(req, res, next) {
//..set headers etc.
next();
});
In terms of organising the CORS stuff, I put it in a middleware which is working well for me:
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'cool beans' }));
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
If you have a lot of relation attribute fields to use in list_display
and do not want create a function (and it's attributes) for each one, a dirt but simple solution would be override the ModelAdmin
instace __getattr__
method, creating the callables on the fly:
class DynamicLookupMixin(object):
'''
a mixin to add dynamic callable attributes like 'book__author' which
return a function that return the instance.book.author value
'''
def __getattr__(self, attr):
if ('__' in attr
and not attr.startswith('_')
and not attr.endswith('_boolean')
and not attr.endswith('_short_description')):
def dyn_lookup(instance):
# traverse all __ lookups
return reduce(lambda parent, child: getattr(parent, child),
attr.split('__'),
instance)
# get admin_order_field, boolean and short_description
dyn_lookup.admin_order_field = attr
dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False)
dyn_lookup.short_description = getattr(
self, '{}_short_description'.format(attr),
attr.replace('_', ' ').capitalize())
return dyn_lookup
# not dynamic lookup, default behaviour
return self.__getattribute__(attr)
# use examples
@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin, DynamicLookupMixin):
list_display = ['book__author', 'book__publisher__name',
'book__publisher__country']
# custom short description
book__publisher__country_short_description = 'Publisher Country'
@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin, DynamicLookupMixin):
list_display = ('name', 'category__is_new')
# to show as boolean field
category__is_new_boolean = True
As gist here
Callable especial attributes like boolean
and short_description
must be defined as ModelAdmin
attributes, eg book__author_verbose_name = 'Author name'
and category__is_new_boolean = True
.
The callable admin_order_field
attribute is defined automatically.
Don't forget to use the list_select_related attribute in your ModelAdmin
to make Django avoid aditional queries.
How to set default value for form field in Symfony2?
If you need to set default value and your form relates to the entity, then you should use following approach:
// buildForm() method
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
...
->add(
'myField',
'text',
array(
'data' => isset($options['data']) ? $options['data']->getMyField() : 'my default value'
)
);
}
Otherwise, myField
always will be set to default value, instead of getting value from entity.
Sorting using Comparator- Descending order (User defined classes)
String[] s = {"a", "x", "y"};
Arrays.sort(s, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(Arrays.toString(s));
-> [y, x, a]
Now you have to implement the Comparator for your Person class.
Something like (for ascending order): compare(Person a, Person b) = a.id < b.id ? -1 : (a.id == b.id) ? 0 : 1
or Integer.valueOf(a.id).compareTo(Integer.valueOf(b.id))
.
To minimize confusion you should implement an ascending Comparator and convert it to a descending one with a wrapper (like this) new ReverseComparator<Person>(new PersonComparator())
.
How to symbolicate crash log Xcode?
Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:
- Inside Organizer, locate the archive where the app is based on.
- Click on the Download Debug Symbols button. Nothing will appear in your Downloads folder, but that's OK.
- Connect the build machine to an iOS device.
- Select the device in Devices and Simulators.
- Click on the View Devices Logs button.
- Drag-and-drop the crash file to the left panel. The file must end with a .crash extension, otherwise the drag fails.
- Switch to the All Logs tab.
- Select the added crash file.
- The file should automatically symbolicate, otherwise use the right-click context menu item Re-Symbolicate Log.
Getting View's coordinates relative to the root layout
This is one solution, though since APIs change over time and there may be other ways of doing it, make sure to check the other answers. One claims to be faster, and another claims to be easier.
private int getRelativeLeft(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}
private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
Let me know if that works.
It should recursively just add the top and left positions from each parent container.
You could also implement it with a Point
if you wanted.
How to delete columns in a CSV file?
you can use the csv
package to iterate over your csv file and output the columns that you want to another csv file.
The example below is not tested and should illustrate a solution:
import csv
file_name = 'C:\Temp\my_file.csv'
output_file = 'C:\Temp\new_file.csv'
csv_file = open(file_name, 'r')
## note that the index of the year column is excluded
column_indices = [0,1,3,4]
with open(output_file, 'w') as fh:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
tmp_row = []
for col_inx in column_indices:
tmp_row.append(row[col_inx])
fh.write(','.join(tmp_row))
Center content vertically on Vuetify
In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:
<v-container fill-height>
<v-row justify="center" align="center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
- align="center" will center the content vertically inside the row
- justify="center" will center the content horizontally inside the row
- fill-height will center the whole content compared to the page.
OpenCV in Android Studio
This worked for me and was as easy as adding a gradle dependancy:
https://bintray.com/seesaa/maven/opencv#
https://github.com/seesaa/opencv-android
The one caveat being that I had to use a hardware debugging device as arm emulators were running too slow for me (as AVD Manager says they will), and, as described at the repo README, this version does not include x86 or x86_64 support.
It seems to build and the suggested test:
static {
OpenCVLoader.initDebug();
}
spits out a bunch of output that looks about right to me.
JQuery - File attributes
<form id = "uploadForm" name = "uploadForm" enctype="multipart/form-data">
<label for="uploadFile">Upload Your File</label>
<input type="file" name="uploadFile" id="uploadFile">
</form>
<script>
$('#uploadFile').change(function(){
var fileName = this.files[0].name;
var fileSize = this.files[0].size;
var fileType = this.files[0].type;
alert('FileName : ' + fileName + '\nFileSize : ' + fileSize + ' bytes');
});
</script>
Note:
To get the uploading file name means then use jquery val() method.
For Ex:
var fileName = $('#uploadFile').val();
I checked this above code before post, it works perfectly.!
Entity Framework Timeouts
For Entity framework 6 I use this annotation and works fine.
public partial class MyDbContext : DbContext
{
private const int TimeoutDuration = 300;
public MyDbContext ()
: base("name=Model1")
{
this.Database.CommandTimeout = TimeoutDuration;
}
// Some other codes
}
The CommandTimeout parameter is a nullable integer that set timeout
values as seconds, if you set null or don't set it will use default
value of provider you use.
How to prevent custom views from losing state across screen orientation changes
I had the problem that onRestoreInstanceState restored all my custom views with the state of the last view. I solved it by adding these two methods to my custom view:
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
dispatchFreezeSelfOnly(container);
}
@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
dispatchThawSelfOnly(container);
}
How can I select all options of multi-select select box on click?
If you are using JQuery 1.9+ then above answers will not work in Firefox.
So here is a code for latest jquery which will work in all browsers.
See live demo
Here is the code
var select_ids = [];
$(document).ready(function(e) {
$('select#myselect option').each(function(index, element) {
select_ids.push($(this).val());
})
});
function selectAll()
{
$('select#myselect').val(select_ids);
}
function deSelectAll()
{
$('select#myselect').val('');
}
Hope this will help you... :)
Can you explain the HttpURLConnection connection process?
I went through the exercise to capture low level packet exchange, and found that network connection is only triggered by operations like getInputStream, getOutputStream, getResponseCode, getResponseMessage etc.
Here is the packet exchange captured when I try to write a small program to upload file to Dropbox.
Below is my toy program and annotation
/* Create a connection LOCAL object,
* the openConnection() function DOES NOT initiate
* any packet exchange with the remote server.
*
* The configurations only setup the LOCAL
* connection object properties.
*/
HttpURLConnection connection = (HttpURLConnection) dst.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
...//headers setup
byte[] testContent = {0x32, 0x32};
/**
* This triggers packet exchange with the remote
* server to create a link. But writing/flushing
* to a output stream does not send out any data.
*
* Payload are buffered locally.
*/
try (BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream())) {
outputStream.write(testContent);
outputStream.flush();
}
/**
* Trigger payload sending to the server.
* Client get ALL responses (including response code,
* message, and content payload)
*/
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
/* Here no further exchange happens with remote server, since
* the input stream content has already been buffered
* in previous step
*/
try (InputStream is = connection.getInputStream()) {
Scanner scanner = new Scanner(is);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNextLine()) {
stringBuilder.append(scanner.nextLine()).append(System.lineSeparator());
}
}
/**
* Trigger the disconnection from the server.
*/
String responsemsg = connection.getResponseMessage();
System.out.println(responsemsg);
connection.disconnect();
Official way to ask jQuery wait for all images to load before executing something
My solution is similar to molokoloco. Written as jQuery function:
$.fn.waitForImages = function (callback) {
var $img = $('img', this),
totalImg = $img.length;
var waitImgLoad = function () {
totalImg--;
if (!totalImg) {
callback();
}
};
$img.each(function () {
if (this.complete) {
waitImgLoad();
}
})
$img.load(waitImgLoad)
.error(waitImgLoad);
};
example:
<div>
<img src="img1.png"/>
<img src="img2.png"/>
</div>
<script>
$('div').waitForImages(function () {
console.log('img loaded');
});
</script>
T-SQL Substring - Last 3 Characters
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT()
in the same way.
Bear in mind if you are using this in a WHERE
clause that the RIGHT()
can't use any indexes.
Display Two <div>s Side-by-Side
Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/
<div id="row1">
<div id="column1">I am column one</div>
<div id="column2">I am column two</div>
</div>
#row1{
display:flex;
flex-direction:row;
justify-content: space-around;
}
#column1{
display:flex;
flex-direction:column;
}
#column2{
display:flex;
flex-direction:column;
}
Comparing Dates in Oracle SQL
You can use trunc and to_date as follows:
select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.*
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;
jquery animate background position
function getBackgroundPositionX(sel) {
pos = $(sel).css('backgroundPosition').split(' ');
return parseFloat(pos[0].substring(0, pos[0].length-2));
}
This returns [x] value.
Length of number has no matter. Could be e.g. 9999 or 0.