How to get a json string from url?
Use the WebClient
class in System.Net
:
var json = new WebClient().DownloadString("url");
Keep in mind that WebClient
is IDisposable
, so you would probably add a using
statement to this in production code. This would look like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("url");
}
Retrieving Android API version programmatically
Build.VERSION.RELEASE;
That will give you the actual numbers of your version; aka 2.3.3 or 2.2.
The problem with using Build.VERSION.SDK_INT is if you have a rooted phone or custom rom, you could have a non standard OS (aka my android is running 2.3.5) and that will return a null when using Build.VERSION.SDK_INT so Build.VERSION.RELEASE will work no matter using standard Android version or not !
To use it, you could just do this;
String androidOS = Build.VERSION.RELEASE;
Convert True/False value read from file to boolean
The cleanest solution that I've seen is:
from distutils.util import strtobool
def string_to_bool(string):
return bool(strtobool(str(string)))
Sure, it requires an import, but it has proper error handling and requires very little code to be written (and tested).
How to reset the use/password of jenkins on windows?
1 ) Copy the initialAdminPassword in Specified path.
2 ) Login with following Credentials
User Name : admin
Password : <da12906084fd405090a9fabfd66342f0>
3 ) Once you login into the jenkins application you can click on admin profile and reset the password.
How do I create an abstract base class in JavaScript?
Animal = function () { throw "abstract class!" }
Animal.prototype.name = "This animal";
Animal.prototype.sound = "...";
Animal.prototype.say = function() {
console.log( this.name + " says: " + this.sound );
}
Cat = function () {
this.name = "Cat";
this.sound = "meow";
}
Dog = function() {
this.name = "Dog";
this.sound = "woof";
}
Cat.prototype = Object.create(Animal.prototype);
Dog.prototype = Object.create(Animal.prototype);
new Cat().say(); //Cat says: meow
new Dog().say(); //Dog says: woof
new Animal().say(); //Uncaught abstract class!
Validate email with a regex in jQuery
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
How can I submit form on button click when using preventDefault()?
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
FIDDLE
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
How can I loop through enum values for display in radio buttons?
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
(code in playground)
Edit
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
matplotlib: colorbars and its text labels
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
Pythonically add header to a csv file
You just add one additional row before you execute the loop. This row contains
your CSV file header name.
schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
writer.writerow([g for g in schema])
#Data add in csv file
for x in xrange(rows):
writer.writerow([g() for g in generators])
IDENTITY_INSERT is set to OFF - How to turn it ON?
Should you instead be setting the identity insert to on within the stored procedure? It looks like you're setting it to on only when changing the stored procedure, not when actually calling it. Try:
ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int,
SET IDENTITY_INSERT tbl_content ON
...insert command...
SET IDENTITY_INSERT tbl_content OFF
GO
Why does background-color have no effect on this DIV?
Floats don't have a height so the containing div has a height of zero.
<div style="background-color:black; overflow:hidden;zoom:1" onmouseover="this.bgColor='white'">
<div style="float:left">hello</div>
<div style="float:right">world</div>
</div>
overflow:hidden clears the float for most browsers.
zoom:1 clears the float for IE.
Merge two array of objects based on a key
You could use an arbitrary count of arrays and map on the same index new objects.
_x000D_
_x000D_
var array1 = [{ id: "abdc4051", date: "2017-01-24" }, { id: "abdc4052", date: "2017-01-22" }],_x000D_
array2 = [{ id: "abdc4051", name: "ab" }, { id: "abdc4052", name: "abc" }],_x000D_
result = [array1, array2].reduce((a, b) => a.map((c, i) => Object.assign({}, c, b[i])));_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_
boolean in an if statement
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the ===
comparison. I think that there are three reasons for that:
- It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
- Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected
undefined
or null
value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
- JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.
Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput()
returns undefined
, null
, or an empty string. Due to the two boolean evaluations submitInput()
is only called if the given input is a string that contains non-whitespace characters.
In JavaScript &&
returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized
will be undefined
if someString
was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null
or undefined
values, which would clutter up the code. In JavaScript that is not needed.
Parse HTML table to Python list?
Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:
from xml.etree import ElementTree as ET
s = """<table>
<tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>d</td><td>e</td><td>f</td></tr>
<tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
values = [col.text for col in row]
print(dict(zip(headers, values)))
same output as Sven Marnach's answer...
What is Java Servlet?
A servlet at its very core is a java class; which can handle HTTP requests.
Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).
Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).
Assuming you have a container, your servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you. You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc. Look at Resource 3.
Here is a fun exercise for you. Create a simple servlet like in Resource 3 and write a few System.out.println() statements in it's constructor method (Yes you can have a constructor of a servlet), init(), doGet(), doPost() methods and run the servlet in tomcat. See the console logs and tomcat logs.
Hope this helps, happy learning.
Resources
Look how the HTTP servlet looks here(Tomcat example).
Servlet Specification.
Simple Servlet example.
Start reading the book online/PDF
It also provides you download of the whole book. May be this will help.
if you are just starting servlets may be it's a good idea to read the material along with the servlet API. it's a slower process of learning, but is way more helpful in getting the basics clear.
Return only string message from Spring MVC 3 Controller
This is just a note for those who might find this question later, but you don't have to pull in the response to change the content type. Here's an example below to do just that:
@RequestMapping(method = RequestMethod.GET, value="/controller")
public ResponseEntity<byte[]> displayUploadedFile()
{
HttpHeaders headers = new HttpHeaders();
String disposition = INLINE;
String fileName = "";
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//Load your attachment here
if (Arrays.equals(Constants.HEADER_BYTES_PDF, contentBytes)) {
headers.setContentType(MediaType.valueOf("application/pdf"));
fileName += ".pdf";
}
if (Arrays.equals(Constants.HEADER_BYTES_TIFF_BIG_ENDIAN, contentBytes)
|| Arrays.equals(Constantsr.HEADER_BYTES_TIFF_LITTLE_ENDIAN, contentBytes)) {
headers.setContentType(MediaType.valueOf("image/tiff"));
fileName += ".tif";
}
if (Arrays.equals(Constants.HEADER_BYTES_JPEG, contentBytes)) {
headers.setContentType(MediaType.IMAGE_JPEG);
fileName += ".jpg";
}
//Handle other types if necessary
headers.add("Content-Disposition", , disposition + ";filename=" + fileName);
return new ResponseEntity<byte[]>(uploadedBytes, headers, HttpStatus.OK);
}
How to tune Tomcat 5.5 JVM Memory settings without using the configuration program
If you'd start Tomcat manually (not as service), then the CATALINA_OPTS environment variable is the way to go. If you'd start it as a service, then the settings are probably stored somewhere in the registry. I have Tomcat 6 installed in my machine and I found the settings at the HKLM\SOFTWARE\Apache Software Foundation\Procrun 2.0\Tomcat6\Parameters\Java
key.
How to run a shell script on a Unix console or Mac terminal?
First, give permission for execution:-
chmod +x script_name
- If script is not executable:-
For running sh script file:-
sh script_name
For running bash script file:-
bash script_name
- If script is executable:-
./script_name
NOTE:-you can check if the file is executable or not by using 'ls -a'
Python open() gives FileNotFoundError/IOError: Errno 2 No such file or directory
- Make sure the file exists: use
os.listdir()
to see the list of files in the current working directory
- Make sure you're in the directory you think you're in with
os.getcwd()
(if you launch your code from an IDE, you may well be in a different directory)
- You can then either:
- Call
os.chdir(dir)
, dir
being the folder where the file is
located, then open the file with just its name like you were doing.
- Specify an absolute path to the file in your
open
call.
- Remember to use a raw string if your path uses backslashes, like
so:
dir = r'C:\Python32'
- If you don't use raw-string, you have to escape every backslash:
'C:\\User\\Bob\\...'
- Forward-slashes also work on Windows
'C:/Python32'
and do not need to be escaped.
Let me clarify how Python finds files:
- An absolute path is a path that starts with your computer's root directory, for example 'C:\Python\scripts..' if you're on Windows.
- A relative path is a path that does not start with your computer's root directory, and is instead relative to something called the
working directory
. You can view Python's current working directory by calling os.getcwd()
.
If you try to do open('sortedLists.yaml')
, Python will see that you are passing it a relative path, so it will search for the file inside the current working directory. Calling os.chdir
will change the current working directory.
Example: Let's say file.txt
is found in C:\Folder
.
To open it, you can do:
os.chdir(r'C:\Folder')
open('file.txt') #relative path, looks inside the current working directory
or
open(r'C:\Folder\file.txt') #full path
XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode
The <Comment>
tag contains two text nodes and two <br>
nodes as children.
Your xpath expression was
//*[contains(text(),'ABC')]
To break this down,
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.
- The
[]
are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
contains
is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment>
element -- namely BLAH BLAH BLAH
. Since that doesn't match, you don't get a <Comment>
in your results.
You need to change this to
//*[text()[contains(.,'ABC')]]
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.
- The outer
[]
are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
- The inner
[]
are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as .
within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
contains
is a function that operates on a string. Here it is passed an individual text node (.
). Since it is passed the second text node in the <Comment>
tag individually, it will see the 'ABC'
string and be able to match it.
Using Position Relative/Absolute within a TD?
This is because according to CSS 2.1, the effect of position: relative
on table elements is undefined. Illustrative of this, position: relative
has the desired effect on Chrome 13, but not on Firefox 4. Your solution here is to add a div
around your content and put the position: relative
on that div
instead of the td
. The following illustrates the results you get with the position: relative
(1) on a div
good), (2) on a td
(no good), and finally (3) on a div
inside a td
(good again).
_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="position:relative;">_x000D_
<span style="position:absolute; left:150px;">_x000D_
Absolute span_x000D_
</span>_x000D_
Relative div_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_
What does this square bracket and parenthesis bracket notation mean [first1,last1)?
A bracket - [
or ]
- means that end of the range is inclusive -- it includes the element listed. A parenthesis - (
or )
- means that end is exclusive and doesn't contain the listed element. So for [first1, last1)
, the range starts with first1
(and includes it), but ends just before last1
.
Assuming integers:
- (0, 5) = 1, 2, 3, 4
- (0, 5] = 1, 2, 3, 4, 5
- [0, 5) = 0, 1, 2, 3, 4
- [0, 5] = 0, 1, 2, 3, 4, 5
How do I create a MongoDB dump of my database?
Use -v to see progress of backup data
mongodump -v --db dbname --out /pathforbackup/NewFolderforBackupData
you can use it for restore also
mongorestore -v --db dbname --drop /pathforbackup/NewFolderforBackupData/dbname
with multile v like -vvvv you will get more information
Asynchronous shell exec in PHP
If it "doesn't care about the output", couldn't the exec to the script be called with the &
to background the process?
EDIT - incorporating what @AdamTheHut commented to this post, you can add this to a call to exec
:
" > /dev/null 2>/dev/null &"
That will redirect both stdio
(first >
) and stderr
(2>
) to /dev/null
and run in the background.
There are other ways to do the same thing, but this is the simplest to read.
An alternative to the above double-redirect:
" &> /dev/null &"
Drawing Circle with OpenGL
glBegin(GL_POLYGON); // Middle circle
double radius = 0.2;
double ori_x = 0.0; // the origin or center of circle
double ori_y = 0.0;
for (int i = 0; i <= 300; i++) {
double angle = 2 * PI * i / 300;
double x = cos(angle) * radius;
double y = sin(angle) * radius;
glVertex2d(ori_x + x, ori_y + y);
}
glEnd();
Validating an XML against referenced XSD in C#
I had do this kind of automatic validation in VB and this is how I did it (converted to C#):
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);
Then I subscribed to the settings.ValidationEventHandler
event while reading the file.
How to fix "Headers already sent" error in PHP
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed)
line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
Recover sa password
best answer written by Dmitri Korotkevitch:
Speaking of the installation, SQL Server 2008 allows you to set
authentication mode (Windows or SQL Server) during the installation
process. You will be forced to choose the strong password for sa user
in the case if you choose sql server authentication mode during setup.
If you install SQL Server with Windows Authentication mode and want to
change it, you need to do 2 different things:
Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode
Go to security/logins, open SA login properties
a. Uncheck "Enforce password policy" and "Enforce password expiration"
check box there if you decide to use weak password
b. Assign password to SA user
c. Open "Status" tab and enable login.
I don't need to mention that every action from above would violate
security best practices that recommend to use windows authentication
mode, have sa login disabled and use strong passwords especially for
sa login.
SQL Server : SUM() of multiple rows including where clauses
The WHERE
clause is always conceptually applied (the execution plan can do what it wants, obviously) prior to the GROUP BY
. It must come before the GROUP BY
in the query, and acts as a filter before things are SUM
med, which is how most of the answers here work.
You should also be aware of the optional HAVING
clause which must come after the GROUP BY
. This can be used to filter on the resulting properties of groups after GROUP
ing - for instance HAVING SUM(Amount) > 0
System.web.mvc missing
Had this problem in vs2017, I already got MVC via nuget but System.Web.Mvc didn't appear in the "Assemblies" list under "Add Reference".
The solution was to select "Extensions" under "Assemblies" in the "Add Reference" dialog.
Converting Java objects to JSON with Jackson
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
How to trigger a build only if changes happen on particular set of files
The Git plugin has an option (excluded region) to use regexes to determine whether to skip building based on whether files in the commit match the excluded region regex.
Unfortunately, the stock Git plugin does not have a "included region" feature at this time (1.15). However, someone posted patches on GitHub that work on Jenkins and Hudson that implement the feature you want.
It is a little work to build, but it works as advertised and has been extremely useful since one of my Git trees has multiple independent projects.
https://github.com/jenkinsci/git-plugin/pull/49
Update: The Git plugin (1.16) now has the 'included' region feature.
Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
Short ES6 code
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
How to find most common elements of a list?
The answer from @Mark Byers is best, but if you are on a version of Python < 2.7 (but at least 2.5, which is pretty old these days), you can replicate the Counter class functionality very simply via defaultdict (otherwise, for python < 2.5, three extra lines of code are needed before d[i] +=1, as in @Johnnysweb's answer).
from collections import defaultdict
class Counter():
ITEMS = []
def __init__(self, items):
d = defaultdict(int)
for i in items:
d[i] += 1
self.ITEMS = sorted(d.iteritems(), reverse=True, key=lambda i: i[1])
def most_common(self, n):
return self.ITEMS[:n]
Then, you use the class exactly as in Mark Byers's answer, i.e.:
words_to_count = (word for word in word_list if word[:1].isupper())
c = Counter(words_to_count)
print c.most_common(3)
Execute a batch file on a remote PC using a batch file on local PC
If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name>
should be enough shutdown /?
for more, otherwise you need software to connect and control the target server.
UPDATE:
Seems shutdown.bat here is for shutting down apache-tomcat.
So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client
As native solution could be wmic
Example:
wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"
In your example should be:
wmic /node:inidsoasrv01 process call create ^
"cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"
wmic /?
and wmic /node /?
for more
Use Expect in a Bash script to provide a password to an SSH command
After looking for an answer for the question for months, I finally find a really best solution: writing a simple script.
#!/usr/bin/expect
set timeout 20
set cmd [lrange $argv 1 end]
set password [lindex $argv 0]
eval spawn $cmd
expect "assword:" # matches both 'Password' and 'password'
send "$password\r";
interact
Put it to /usr/bin/exp
, then you can use:
exp <password> ssh <anything>
exp <password> scp <anysrc> <anydst>
Done!
Textarea to resize based on content length
You may also try contenteditable
attribute onto a normal p
or div
. Not really a textarea
but it will auto-resize without script.
_x000D_
_x000D_
.divtext {
border: ridge 2px;
padding: 5px;
width: 20em;
min-height: 5em;
overflow: auto;
}
_x000D_
<div class="divtext" contentEditable>Hello World</div>
_x000D_
_x000D_
_x000D_
How to change value of process.env.PORT in node.js?
EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?
Original Answer:
If you want to do this to run on port 80 (or want to set the env variable more permanently),
- Open up your bash profile
vim ~/.bash_profile
- Add the environment variable to the file
export PORT=80
- Open up the sudoers config file
sudo visudo
- Add the following line to the file exactly as so
Defaults env_keep +="PORT"
Now when you run sudo node app.js
it should work as desired.
Simulate Keypress With jQuery
This works:
var event = jQuery.Event('keypress');
event.which = 13;
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event);
Java Singleton and Synchronization
Yes, you need to make getInstance()
synchronized. If it's not there might arise a situation where multiple instances of the class can be made.
Consider the case where you have two threads that call getInstance()
at the same time. Now imagine T1 executes just past the instance == null
check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance()
synchronized prevents this problem.
There a few ways to make singletons thread-safe, but making getInstance()
synchronized is probably the simplest.
Pure JavaScript Send POST Data Without a Form
The [new-ish at the time of writing in 2017] Fetch API is intended to make GET requests easy, but it is able to POST as well.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
If you are as lazy as me (or just prefer a shortcut/helper):
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
Visual Studio: Relative Assembly References Paths
In VS 2017 it is automatic. So just Add Reference
as usually.
Note that in Reference Properties
absolute path is shown, but in .vbproj/.csproj
relative is used.
<Reference Include="NETnetworkmanager">
<HintPath>..\..\libs\NETnetworkmanager.dll</HintPath>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
Python idiom to return first item or None
Several people have suggested doing something like this:
list = get_list()
return list and list[0] or None
That works in many cases, but it will only work if list[0] is not equal to 0, False, or an empty string. If list[0] is 0, False, or an empty string, the method will incorrectly return None.
I've created this bug in my own code one too many times !
How to completely uninstall Android Studio on Mac?
I was also facing same kind of problem on my Macbook Pro. I took these very simple steps and freshly installed Android Studio.
** Link Contains Images, look if facing any problem.
These Very Simple Steps Can Solve Your Problem.
- Type "Command+option+Space Bar"
- Type "Android Studio"
- Click '+' button just below search box.
- A new bar will come up "Kind" is "any" click on "kind" --> Others --> search for "system file" and select that by putting a tick mark.! And click on Ok.
- Then select "are included" from the drop down menu !
- Then you get a lot of system file that need to be deleted to complete the fully un-installation of any app.
- Click "command+A" to select all files and take a look on the file remove is some video files are also included. And click "command + Delete"
- Empty your trash. Done
Converting HTML to Excel?
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
How to decide when to use Node.js?
Node best for concurrent request handling -
So, Let’s start with a story. From last 2 years I am working on JavaScript and developing web front end and I am enjoying it. Back end guys provide’s us some API’s written in Java,python (we don’t care) and we simply write a AJAX call, get our data and guess what ! we are done. But in real it is not that easy, If data we are getting is not correct or there is some server error then we stuck and we have to contact our back end guys over the mail or chat(sometimes on whatsApp too :).) This is not cool. What if we wrote our API’s in JavaScript and call those API’s from our front end ? Yes that’s pretty cool because if we face any problem in API we can look into it. Guess what ! you can do this now , How ? – Node is there for you.
Ok agreed that you can write your API in JavaScript but what if I am ok with above problem. Do you have any other reason to use node for rest API ?
so here is the magic begins. Yes I do have other reasons to use node for our API’s.
Let’s go back to our traditional rest API system which is based on either blocking operation or threading. Suppose two concurrent request occurs( r1 and r2) , each of them require database operation. So In traditional system what will happens :
1. Waiting Way : Our server starts serving r1
request and waits for query response. after completion of r1
, server starts to serve r2
and does it in same way. So waiting is not a good idea because we don’t have that much time.
2. Threading Way : Our server will creates two threads for both requests r1
and r2
and serve their purpose after querying database so cool its fast.But it is memory consuming because you can see we started two threads also problem increases when both request is querying same data then you have to deal with deadlock kind of issues . So its better than waiting way but still issues are there.
Now here is , how node will do it:
3. Nodeway : When same concurrent request comes in node then it will register an event with its callback and move ahead it will not wait for query response for a particular request.So when r1
request comes then node’s event loop (yes there is an event loop in node which serves this purpose.) register an event with its callback function and move ahead for serving r2
request and similarly register its event with its callback. Whenever any query finishes it triggers its corresponding event and execute its callback to completion without being interrupted.
So no waiting, no threading , no memory consumption – yes this is nodeway for serving rest API.
moment.js 24h format
Try: moment({ // Options here }).format('HHmm')
. That should give you the time in a 24 hour format.
Are there any style options for the HTML5 Date picker?
I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...
I am using styled-components to render a transparent date picker input as shown in the image below:
const StyledInput = styled.input`
appearance: none;
box-sizing: border-box;
border: 1px solid black;
background: transparent;
font-size: 1.5rem;
padding: 8px;
::-webkit-datetime-edit-text { padding: 0 2rem; }
::-webkit-datetime-edit-month-field { text-transform: uppercase; }
::-webkit-datetime-edit-day-field { text-transform: uppercase; }
::-webkit-datetime-edit-year-field { text-transform: uppercase; }
::-webkit-inner-spin-button { display: none; }
::-webkit-calendar-picker-indicator { background: transparent;}
`
Writing a dictionary to a csv file with one line for every 'key: value'
#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
m=int(input("Enter the number of data you want to insert: "))
mydict={}
list=[]
for i in range(m):
keys=int(input("Enter id :"))
list.append(keys)
values=input("Enter Name :")
mydict[keys]=values
with open('File1.csv',"w") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=list)
writer.writeheader()
writer.writerow(mydict)
print("Data Inserted")
else:
keys=input("Enter Id to Search :")
Id=str(keys)
with open('File1.csv',"r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row[Id]) #print(row) to display all data
How to print the value of a Tensor object in TensorFlow?
The easiest[A] way to evaluate the actual value of a Tensor
object is to pass it to the Session.run()
method, or call Tensor.eval()
when you have a default session (i.e. in a with tf.Session():
block, or see below). In general[B], you cannot print the value of a tensor without running some code in a session.
If you are experimenting with the programming model, and want an easy way to evaluate tensors, the tf.InteractiveSession
lets you open a session at the start of your program, and then use that session for all Tensor.eval()
(and Operation.run()
) calls. This can be easier in an interactive setting, such as the shell or an IPython notebook, when it's tedious to pass around a Session
object everywhere. For example, the following works in a Jupyter notebook:
with tf.Session() as sess: print(product.eval())
This might seem silly for such a small expression, but one of the key ideas in Tensorflow 1.x is deferred execution: it's very cheap to build a large and complex expression, and when you want to evaluate it, the back-end (to which you connect with a Session
) is able to schedule its execution more efficiently (e.g. executing independent parts in parallel and using GPUs).
[A]: To print the value of a tensor without returning it to your Python program, you can use the tf.print()
operator, as Andrzej suggests in another answer. According to the official documentation:
To make sure the operator runs, users need to pass the produced op to tf.compat.v1.Session
's run method, or to use the op as a control dependency for executed ops by specifying with tf.compat.v1.control_dependencies([print_op]
), which is printed to standard output.
Also note that:
In Jupyter notebooks and colabs, tf.print
prints to the notebook cell outputs. It will not write to the notebook kernel's console logs.
[B]: You might be able to use the tf.get_static_value()
function to get the constant value of the given tensor if its value is efficiently calculable.
Changing the selected option of an HTML Select element
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
The target principal name is incorrect. Cannot generate SSPI context
My issue turned out to be so strange and simple:
- SQL Server Windows Service on ServerA (configured to run using DOMAIN\svcAccountA)
- SQL Server Windows Service on ServerB (configured to run using DOMAIN\svcAccountB)
Both DOMAIN\svcAccountA and DOMAIN\svcAccountB are service accounts in our Active Directory domain.
Even though all permissions were setup properly for DOMAIN\svcAccountA to connect to ServerB, a C# CLR (running as DOMAIN\svcAccountA) on ServerA could no longer connect to ServerB using a SqlConnection (same strange uninformative error message: The target principal name is incorrect. Cannot generate SSPI context).
The simple part? After rebooting ServerA, the SQL Server Windows Service would no longer start automatically! That was the clue to discovering that someone had changed the password for DOMAIN\svcAccountA and I had to correct the SQL Server Windows Service configuration here:
After correcting the password, the SQL Server Windows Service on ServerA started fine, and the C# CLR (running as DOMAIN\svcAccountA) on ServerA could now connect to ServerB using a SqlConnection.
In Go's http package, how do I get the query string on a POST request?
Below words come from the official document.
Form contains the parsed form data, including both the URL field's query parameters and the POST or PUT form data. This field is only available after ParseForm is called.
So, sample codes as below would work.
func parseRequest(req *http.Request) error {
var err error
if err = req.ParseForm(); err != nil {
log.Error("Error parsing form: %s", err)
return err
}
_ = req.Form.Get("xxx")
return nil
}
Node JS Error: ENOENT
To expand a bit on why the error happened: A forward slash at the beginning of a path means "start from the root of the filesystem, and look for the given path". No forward slash means "start from the current working directory, and look for the given path".
The path
/tmp/test.jpg
thus translates to looking for the file test.jpg in the tmp folder at the root of the filesystem (e.g. c:\ on windows, / on *nix), instead of the webapp folder. Adding a period (.) in front of the path explicitly changes this to read "start from the current working directory", but is basically the same as leaving the forward slash out completely.
./tmp/test.jpg = tmp/test.jpg
Regular expression - starting and ending with a letter, accepting only letters, numbers and _
Here's a solution using a negative lookahead (not supported in all regex engines):
^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$
Test that it works as expected:
import re
tests = [
('a', True),
('_', False),
('zz', True),
('a0', True),
('A_', False),
('a0_b', True),
('a__b', False),
('a_1_c', True),
]
regex = '^[a-zA-Z](((?!__)[a-zA-Z0-9_])*[a-zA-Z0-9])?$'
for test in tests:
is_match = re.match(regex, test[0]) is not None
if is_match != test[1]:
print "fail: " + test[0]
What is the javascript filename naming convention?
There is no official, universal, convention for naming JavaScript files.
There are some various options:
scriptName.js
script-name.js
script_name.js
are all valid naming conventions, however I prefer the jQuery suggested naming convention (for jQuery plugins, although it works for any JS)
The beauty to this naming convention is that it explicitly describes the global namespace pollution being added.
foo.js
adds window.foo
foo.bar.js
adds window.foo.bar
Because I left out versioning: it should come after the full name, preferably separated by a hyphen, with periods between major and minor versions:
foo-1.2.1.js
foo-1.2.2.js
- ...
foo-2.1.24.js
JBoss AS 7: How to clean up tmp?
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
Nginx upstream prematurely closed connection while reading response header from upstream, for large requests
Problem
The upstream server is timing out and I don't what is happening.
Where to Look first before increasing read or write timeout if your server is connecting to a database
Server is connecting to a database and that connection is working just fine and within sane response time, and its not the one causing this delay in server response time.
make sure that connection state is not causing a cascading failure on your upstream
Then you can move to look at the read and write timeout configurations of the server and proxy.
How to allow <input type="file"> to accept only image files?
Simple and powerful way(dynamic accept)
place formats in array like "image/*"
_x000D_
_x000D_
var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{
console.log(upload.value)
})
_x000D_
<input type="file" id="upload" >
_x000D_
_x000D_
_x000D_
Count lines in large files
On a multi-core server, use GNU parallel to count file lines in parallel. After each files line count is printed, bc sums all line counts.
find . -name '*.txt' | parallel 'wc -l {}' 2>/dev/null | paste -sd+ - | bc
To save space, you can even keep all files compressed. The following line uncompresses each file and counts its lines in parallel, then sums all counts.
find . -name '*.xz' | parallel 'xzcat {} | wc -l' 2>/dev/null | paste -sd+ - | bc
Please run `npm cache clean`
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
Adding a splash screen to Flutter apps
SplashScreen(
seconds: 3,
navigateAfterSeconds: new MyApp(),
// title: new Text(
// 'Welcome In SplashScreen',
// style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
// ),
image: new Image.network('https://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Tesla_Motors.svg/1200px-Tesla_Motors.svg.png'),
backgroundColor: Colors.white,
styleTextUnderTheLoader: new TextStyle(),
photoSize: 150.0,
loaderColor: Colors.black),
),
);
Get Return Value from Stored procedure in asp.net
Procedure never returns a value.You have to use a output parameter in store procedure.
ALTER PROC TESTLOGIN
@UserName varchar(50),
@password varchar(50)
@retvalue int output
as
Begin
declare @return int
set @return = (Select COUNT(*)
FROM CPUser
WHERE UserName = @UserName AND Password = @password)
set @retvalue=@return
End
Then you have to add a sqlparameter from c# whose parameter direction is out.
Hope this make sense.
Best way to show a loading/progress indicator?
Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".
Currently the recommended method is to use a DialogFragment :
public class MySpinnerDialog extends DialogFragment {
public MySpinnerDialog() {
// use empty constructors. If something is needed use onCreate's
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
_dialog.setMessage("Spinning.."); // set your messages if not inflated from XML
_dialog.setCancelable(false);
return _dialog;
}
}
Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:
FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");
Once your server has responded complete you will dismiss it:
myInstance.dismiss()
Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide
How to parse a JSON and turn its values into an Array?
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/)
- quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
Convert an integer to a float number
Just for the sake of completeness, here is a link to the golang documentation which describes all types. In your case it is numeric types:
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
complex64 the set of all complex numbers with float32 real and imaginary parts
complex128 the set of all complex numbers with float64 real and imaginary parts
byte alias for uint8
rune alias for int32
Which means that you need to use float64(integer_value)
.
Valid values for android:fontFamily and what they map to?
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Added in Android Jelly Bean (4.1) - API 16 :
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Added in Android Lollipop (v5.0) - API 21 :
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
In Node.js, how do I "include" functions from my other files?
This is the best way i have created so far.
var fs = require('fs'),
includedFiles_ = {};
global.include = function (fileName) {
var sys = require('sys');
sys.puts('Loading file: ' + fileName);
var ev = require(fileName);
for (var prop in ev) {
global[prop] = ev[prop];
}
includedFiles_[fileName] = true;
};
global.includeOnce = function (fileName) {
if (!includedFiles_[fileName]) {
include(fileName);
}
};
global.includeFolderOnce = function (folder) {
var file, fileName,
sys = require('sys'),
files = fs.readdirSync(folder);
var getFileName = function(str) {
var splited = str.split('.');
splited.pop();
return splited.join('.');
},
getExtension = function(str) {
var splited = str.split('.');
return splited[splited.length - 1];
};
for (var i = 0; i < files.length; i++) {
file = files[i];
if (getExtension(file) === 'js') {
fileName = getFileName(file);
try {
includeOnce(folder + '/' + file);
} catch (err) {
// if (ext.vars) {
// console.log(ext.vars.dump(err));
// } else {
sys.puts(err);
// }
}
}
}
};
includeFolderOnce('./extensions');
includeOnce('./bin/Lara.js');
var lara = new Lara();
You still need to inform what you want to export
includeOnce('./bin/WebServer.js');
function Lara() {
this.webServer = new WebServer();
this.webServer.start();
}
Lara.prototype.webServer = null;
module.exports.Lara = Lara;
Why is my toFixed() function not working?
document.getElementById("EDTVALOR").addEventListener("change", function() {
this.value = this.value.replace(",", ".");
this.value = parseFloat(this.value).toFixed(2);
if (this.value < 0) {
this.value = 0;
}
this.value = this.value.replace(".", ",");
this.value = this.value.replace("NaN", "0");
});
HTML5 Canvas: Zooming
Just try this out:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type =
"button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();
context.restore();
}
window.onload = function(){
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function(){
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt){
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt){
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt){
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt){
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function(){
$("#wrapper").mouseover(function(e){
$('#status').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down
Njoy!!!
Here is fiddle for this Fiddle
How to set the thumbnail image on HTML5 video?
That seems to be an extra image being shown there.
You can try using this
<img src="/images/image_of_video.png" alt="image" />
/* write your code for the video here */
Now using jQuery play the video and hide the image as
$('img').click(function () {
$(this).hide();
// use the parameters to play the video now..
})
Methods vs Constructors in Java
The important difference between constructors and methods is that constructors initialize objects that are being created with the new
operator, while methods perform operations on objects that already exist.
Constructors can't be called directly; they are called implicitly when the new
keyword creates an object. Methods can be called directly on an object that has already been created with new
.
The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public
), and they have method bodies in braces.
Constructors must be named with the same name as the class name. They can't return anything, even void
(the object itself is the implicit return).
Methods must be declared to return something, although it can be void
.
How to write data with FileOutputStream without losing old data?
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
How to get value from form field in django framework?
Take your pick:
def my_view(request):
if request.method == 'POST':
print request.POST.get('my_field')
form = MyForm(request.POST)
print form['my_field'].value()
print form.data['my_field']
if form.is_valid():
print form.cleaned_data['my_field']
print form.instance.my_field
form.save()
print form.instance.id # now this one can access id/pk
Note: the field is accessed as soon as it's available.
How to detect if a string contains special characters?
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
How do you delete an ActiveRecord object?
It's destroy
and destroy_all
methods, like
user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)
Alternatively you can use delete
and delete_all
which won't enforce :before_destroy
and :after_destroy
callbacks or any dependent association options.
User.delete_all(condition: 'value')
will allow you to delete records
without a primary key
Note: from @hammady's comment, user.destroy
won't work if User model has no primary key.
Note 2: From @pavel-chuchuva's comment, destroy_all
with conditions and delete_all
with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html
Should CSS always preceed Javascript?
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
What's the simplest way to list conflicted files in Git?
Maybe this has been added to Git, but the files that have yet to be resolved are listed in the status message (git status) like this:
#
# Unmerged paths:
# (use "git add/rm <file>..." as appropriate to mark resolution)
#
# both modified: syssw/target/libs/makefile
#
Note that this is the Unmerged paths section.
git: Switch branch and ignore any changes without committing
Move uncommited changes to a new branch
I created a .gitconfig
alias for this:
[alias]
spcosp = !"git stash push && git checkout \"$@\" && git stash pop --index #"
To change to new-branch-name
, use:
git spcosp new-branch-name
And any non-commited file and index changes will be kept.
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
How to tell git to use the correct identity (name and email) for a given project?
Edit the config file with in ".git" folder to maintain the different username and email depends upon the repository
- Go to Your repository
- Show the hidden files and go to ".git" folder
- Find the "config" file
- Add the below lines at EOF
[user]
name = Bob
email = [email protected]
This below command show you which username and email set for this repository.
git config --get user.name
git config --get user.email
Example: for mine that config file in D:\workspace\eclipse\ipchat\.git\config
Here ipchat is my repo name
XAMPP Start automatically on Windows 7 startup
I am using XAMPP on Win 7 and 8.1 too...it start normally.
Did you try to check the services on Start > RUN > services.msc
Find the service: Apache 2.x. (right click) choose Properties. At form "Startup type" choose "Automatically" and Start the service on.
you should reset the PC and check out again.
Do the same with mySQL.
If you can not solve the problem, use XAMPP Panel to start it manually.
How do I get bootstrap-datepicker to work with Bootstrap 3?
I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.
You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.
Here is my solution:
<div class="form-group row">
<div class="col-xs-8">
<label class="control-label">My Label</label>
<div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
<input class="form-control" type="text" readonly="" value="12-02-2012">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
CSS changes in datepicker.css on lines 176-177:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 34:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;
UPDATE
Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:
CSS changes in datepicker.css on lines 446-447:
.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {
Javascript change in datepicker-bootstrap.js on line 46:
this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;
Finally, the JavaScript to enable the datepicker (with some options):
$(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });
Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.
anchor jumping by using javascript
Not enough rep for a comment.
The getElementById()
based method in the selected answer won't work if the anchor has name
but not id
set (which is not recommended, but does happen in the wild).
Something to bare in mind if you don't have control of the document markup (e.g. webextension).
The location
based method in the selected answer can also be simplified with location.replace
:
function jump(hash) { location.replace("#" + hash) }
Convert file: Uri to File in Android
Android + Kotlin
Add dependency for Kotlin Android extensions:
implementation 'androidx.core:core-ktx:{latestVersion}'
Get file from uri:
uri.toFile()
Android + Java
Just move to top ;)
Create view with primary key?
I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.
CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM dbo.MyTable
Recyclerview and handling different type of row inflation
It is quite tricky but that much hard, just copy the below code and you are done
package com.yuvi.sample.main;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.yuvi.sample.R;
import java.util.List;
/**
* Created by yubraj on 6/17/15.
*/
public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
List<MainOption> mainOptionlist;
Context context;
private static final int TYPE_PROFILE = 1;
private static final int TYPE_OPTION_MENU = 2;
private int selectedPos = 0;
public NavDrawerAdapter(Context context){
this.mainOptionlist = MainOption.getDrawableDataList();
this.context = context;
}
@Override
public int getItemViewType(int position) {
return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
}
@Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case TYPE_PROFILE:
return new ProfileViewHolder(LayoutInflater.from(context).inflate(R.layout.row_profile, parent, false));
case TYPE_OPTION_MENU:
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row_nav_drawer, parent, false));
}
return null;
}
@Override
public void onBindViewHolder(MainViewHolder holder, int position) {
if(holder.getItemViewType() == TYPE_PROFILE){
ProfileViewHolder mholder = (ProfileViewHolder) holder;
setUpProfileView(mholder);
}
else {
MyViewHolder mHolder = (MyViewHolder) holder;
MainOption mo = mainOptionlist.get(position);
mHolder.tv_title.setText(mo.title);
mHolder.iv_icon.setImageResource(mo.icon);
mHolder.itemView.setSelected(selectedPos == position);
}
}
private void setUpProfileView(ProfileViewHolder mholder) {
}
@Override
public int getItemCount() {
return mainOptionlist.size();
}
public class MyViewHolder extends MainViewHolder{
TextView tv_title;
ImageView iv_icon;
public MyViewHolder(View v){
super(v);
this.tv_title = (TextView) v.findViewById(R.id.tv_title);
this.iv_icon = (ImageView) v.findViewById(R.id.iv_icon);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Redraw the old selection and the new
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
});
}
}
public class ProfileViewHolder extends MainViewHolder{
TextView tv_name, login;
ImageView iv_profile;
public ProfileViewHolder(View v){
super(v);
this.tv_name = (TextView) v.findViewById(R.id.tv_profile);
this.iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
this.login = (TextView) v.findViewById(R.id.tv_login);
}
}
public void trace(String tag, String message){
Log.d(tag , message);
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View v) {
super(v);
}
}
}
enjoy !!!!
Convert String to Calendar Object in Java
tl;dr
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
Avoid legacy date-time classes
The modern way is with java.time classes. The old date-time classes such as Calendar
have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth
class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString
method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
Live code
See this code running in IdeOne.com.
Conversion
If you must have a Calendar
object, you can convert to a GregorianCalendar
using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Why dict.get(key) instead of dict[key]?
One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:
print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'
Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.
So instead of doing this (or something similar):
score = None
try:
score = dictionary["score"]
except KeyError:
score = 0
We can do this:
score = dictionary.get("score", 0)
# score = 0
What is lexical scope?
I normally learn by example, and here's a little something:
const lives = 0;
function catCircus () {
this.lives = 1;
const lives = 2;
const cat1 = {
lives: 5,
jumps: () => {
console.log(this.lives);
}
};
cat1.jumps(); // 1
console.log(cat1); // { lives: 5, jumps: [Function: jumps] }
const cat2 = {
lives: 5,
jumps: () => {
console.log(lives);
}
};
cat2.jumps(); // 2
console.log(cat2); // { lives: 5, jumps: [Function: jumps] }
const cat3 = {
lives: 5,
jumps: () => {
const lives = 3;
console.log(lives);
}
};
cat3.jumps(); // 3
console.log(cat3); // { lives: 5, jumps: [Function: jumps] }
const cat4 = {
lives: 5,
jumps: function () {
console.log(lives);
}
};
cat4.jumps(); // 2
console.log(cat4); // { lives: 5, jumps: [Function: jumps] }
const cat5 = {
lives: 5,
jumps: function () {
var lives = 4;
console.log(lives);
}
};
cat5.jumps(); // 4
console.log(cat5); // { lives: 5, jumps: [Function: jumps] }
const cat6 = {
lives: 5,
jumps: function () {
console.log(this.lives);
}
};
cat6.jumps(); // 5
console.log(cat6); // { lives: 5, jumps: [Function: jumps] }
const cat7 = {
lives: 5,
jumps: function thrownOutOfWindow () {
console.log(this.lives);
}
};
cat7.jumps(); // 5
console.log(cat7); // { lives: 5, jumps: [Function: thrownOutOfWindow] }
}
catCircus();
Check if a div exists with jquery
If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:
if(document.getElementById("yourid") !== null)
{
}
getElementById
returns null
if it can't be found.
Reference.
If however you plan to use the jQuery object later i'd suggest:
$(document).ready(function() {
var $myDiv = $('#DivID');
if ( $myDiv.length){
//you can now reuse $myDiv here, without having to select it again.
}
});
A selector always returns a jQuery object, so there shouldn't be a need to check against null
(I'd be interested if there is an edge case where you need to check for null
- but I don't think there is).
If the selector doesn't find anything then length === 0
which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"
Eclipse Intellisense?
Tony is a pure genius. However to achieve even better auto-completion try setting the triggers to this:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz =.(!+-*/~,[{@#$%^&
(specifically aranged in order of usage for faster performance :)
How to call loading function with React useEffect only once
function useOnceCall(cb, condition = true) {
const isCalledRef = React.useRef(false);
React.useEffect(() => {
if (condition && !isCalledRef.current) {
isCalledRef.current = true;
cb();
}
}, [cb, condition]);
}
and use it.
useOnceCall(()=>{
console.log('called');
})
or
useOnceCall(()=>{
console.log('isLoading');
},isLoading);
Determine file creation date in Java
This is a basic example of how to get the creation date of a file in Java
, using BasicFileAttributes
class:
Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt");
BasicFileAttributes attr;
try {
attr = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("Creation date: " + attr.creationTime());
//System.out.println("Last access date: " + attr.lastAccessTime());
//System.out.println("Last modified date: " + attr.lastModifiedTime());
} catch (IOException e) {
System.out.println("oops error! " + e.getMessage());
}
Access Google's Traffic Data through a Web Service
You might want to take a look at HERE MAP SERVICE. They have direct traffic data you can use, which is exactly what you need: https://developer.here.com/api-explorer/rest/traffic/traffic-flow-bounding-box
For example, by querying an area of interest, you might get something like this:
{
"RWS": [
{
"RW": [
{
"FIS": [
{
"FI": [
{
"TMC": {
"PC": 32483,
"DE": "SOHO",
"QD": "+",
"LE": 0.71682
},
"CF": [
{
"TY": "TR",
"SP": 9.1,
"SU": 9.1,
"FF": 17,
"JF": 3.2911,
"CN": 0.9
}
]
}
]
}
],
....
This example shows a current average speed SU
of 9.1, where the free flow speed FF
would be 17. The Jam factor JF
is 3.3, which is still considered free flow but getting sluggish.
The units used (miles/km) can be defined in the API call.
To avoid dealing with TMC locations, you can ask for geocoordinates of the road segments by adding responseattributes=sh
in the request.
The abbreviations used can be found here Interpreting HERE Maps real-time traffic tags:
- "RWS" - A list of Roadway (RW) items
- "RW" = This is the composite item for flow across an entire roadway. A roadway item will be present for each roadway with
traffic flow information available
- "FIS" = A list of Flow Item (FI) elements
- "FI" = A single flow item
- "TMC" = An ordered collection of TMC locations
- "PC" = Point TMC Location Code
- "DE" = Text description of the road
- "QD" = Queuing direction. '+' or '-'. Note this is the opposite of the travel direction in the fully qualified ID, For example for
location 107+03021 the QD would be '-'
- "LE" = Length of the stretch of road. The units are defined in the file header
- "CF" = Current Flow. This element contains details about speed and Jam Factor information for the given flow item.
- "CN" = Confidence, an indication of how the speed was determined. -1.0 road closed. 1.0=100% 0.7-100% Historical Usually
a value between .7 and 1.0 "FF" = The free flow speed on this
stretch of road.
- "JF" = The number between 0.0 and 10.0 indicating the expected quality of travel. When there is a road closure, the Jam Factor
will be 10. As the number approaches 10.0 the quality of travel is
getting worse. -1.0 indicates that a Jam Factor could not be
calculated
- "SP" = Speed (based on UNITS) capped by speed limit
- "SU" = Speed (based on UNITS) not capped by speed limit
- "TY" = Type information for the given Location Referencing container. This may be freely defined string
Also the source comes from
https://developer.here.com/rest-apis/documentation/traffic/topics/additional-parameters.html
using "if" and "else" Stored Procedures MySQL
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
Simple check for SELECT query empty result
SELECT count(*) as count FROM service s WHERE s.service_id = ?;
test if count == 0 .
More baroquely:
select case when (SELECT count(*) as count FROM service s WHERE s.service_id = ?) = 0
then 'No rows, bro!' else 'You got data!" end as stupid_message;
How to specify multiple conditions in an if statement in javascript
I am currently checking a large number of conditions, which becomes unwieldy using the if statement method beyond say 4 conditions. Just to share a clean looking alternative for future viewers... which scales nicely, I use:
var a = 0;
var b = 0;
a += ("condition 1")? 1 : 0; b += 1;
a += ("condition 2")? 1 : 0; b += 1;
a += ("condition 3")? 1 : 0; b += 1;
a += ("condition 4")? 1 : 0; b += 1;
a += ("condition 5")? 1 : 0; b += 1;
a += ("condition 6")? 1 : 0; b += 1;
// etc etc
if(a == b) {
//do stuff
}
MySQL and GROUP_CONCAT() maximum length
CREATE TABLE some_table (
field1 int(11) NOT NULL AUTO_INCREMENT,
field2 varchar(10) NOT NULL,
field3 varchar(10) NOT NULL,
PRIMARY KEY (`field1`)
);
INSERT INTO `some_table` (field1, field2, field3) VALUES
(1, 'text one', 'foo'),
(2, 'text two', 'bar'),
(3, 'text three', 'data'),
(4, 'text four', 'magic');
This query is a bit strange but it does not need another query to initialize the variable; and it can be embedded in a more complex query.
It returns all the 'field2's separated by a semicolon.
SELECT result
FROM (SELECT @result := '',
(SELECT result
FROM (SELECT @result := CONCAT_WS(';', @result, field2) AS result,
LENGTH(@result) AS blength
FROM some_table
ORDER BY blength DESC
LIMIT 1) AS sub1) AS result) AS sub2;
Find the version of an installed npm package
Combining some of the above answers and produces a super simple and super quick lookup.
Run from project root. No need to cd
into any folder, just 1 line:
node -p "require('SOMEPACKAGE/package.json').version"
Close a MessageBox after several seconds
DMitryG's code "get the return value of the underlying MessageBox
" has a bug so the timerResult is never actually correctly returned (MessageBox.Show
call returns AFTER OnTimerElapsed
completes). My fix is below:
public class TimedMessageBox {
System.Threading.Timer _timeoutTimer;
string _caption;
DialogResult _result;
DialogResult _timerResult;
bool timedOut = false;
TimedMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
{
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
_timerResult = timerResult;
using(_timeoutTimer)
_result = MessageBox.Show(text, caption, buttons);
if (timedOut) _result = _timerResult;
}
public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
return new TimedMessageBox(text, caption, timeout, buttons, timerResult)._result;
}
void OnTimerElapsed(object state) {
IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
if(mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
timedOut = true;
}
const int WM_CLOSE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
Apache shutdown unexpectedly
Your XAMPP restarting with following error at Multi-Processing Module
mpm
[mpm_winnt:notice] [pid 4200:tid 228] AH00428:
`Parent: child process 248 exited with status 1073807364 -- Restarting.`
Add the following in the httpd.conf file of xampp to resolve this.
<IfModule mpm_winnt_module>
ThreadStackSize 8388608
</IfModule>
Stacking DIVs on top of each other?
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
How to check ASP.NET Version loaded on a system?
Here is some code that will return the installed .NET details:
<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<%
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String
winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)
For filndx As Integer = 0 To 2
aspNETfil(0) = "ngen.exe"
aspNETfil(1) = "clr.dll"
aspNETfil(2) = "KernelBase.dll"
If filndx = 2
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
Else
aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
End If
If File.Exists(aspNETpth(filndx)) Then
aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
aspNETtxt(filndx) = aspNETver.FileVersion.ToString
aspNETdiv = aspNETtxt(filndx).Split(" ")
aspNETfix(filndx) = aspNETdiv(0)
Else
aspNETfix(filndx) = "Path not found... No version found..."
End If
Next
Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>
Here is the new output, cleaner code, more output:
Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715
jsPDF multi page PDF with HTML renderer
html2canvas(element[0], {
onrendered: function (canvas) {
pages = Math.ceil(element[0].clientHeight / 1450);
for (i = 0; i <= pages; i += 1) {
if (i > 0) {
pdf.addPage();
}
srcImg = canvas;
sX = 0;
sY = 1450 * i;
sWidth = 1100;
sHeight = 1450;
dX = 0;
dY = 0;
dWidth = 1100;
dHeight = 1450;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 1100);
onePageCanvas.setAttribute('height', 1450);
ctx = onePageCanvas.getContext('2d');
ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
canvasDataURL = onePageCanvas.toDataURL("image/png");
width = onePageCanvas.width;
height = onePageCanvas.clientHeight;
pdf.setPage(i + 1);
pdf.addImage(canvasDataURL, 'PNG', 35, 30, (width * 0.5), (height * 0.5));
}
pdf.save('testfilename.pdf');
}
});
How to create a directory and give permission in single command
Don't do: mkdir -m 777 -p a/b/c
since that will only set permission 777
on the last directory, c; a and b will be created with the default permission from your umask.
Instead to create any new directories with permission 777
, run mkdir -p
in a subshell where you override the umask:
(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)
Note that this won't change the permissions if any of a, b and c already exist though.
What is the difference between Scrum and Agile Development?
Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.
As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful
ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach.
Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.
The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.
What's the difference between Git Revert, Checkout and Reset?
Reset -
On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
Revert -
Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history.
Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.
You can have a look on this link-
Reset, Checkout and Revert
Mysql select distinct
Are you looking for "SELECT * FROM temp_tickets GROUP BY ticket_id ORDER BY ticket_id
?
UPDATE
SELECT t.*
FROM
(SELECT ticket_id, MAX(id) as id FROM temp_tickets GROUP BY ticket_id) a
INNER JOIN temp_tickets t ON (t.id = a.id)
The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
- On the Project menu, turn off "Build Automatically"
- Quit and restart Eclipse
- On the Project menu, choose "Clean…" and clean all projects
- Turn "Build Automatically" back on and let it rebuild everything.
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
Get Android API level of phone currently running my application
Integer.valueOf(android.os.Build.VERSION.SDK);
Values are:
Platform Version API Level
Android 9.0 28
Android 8.1 27
Android 8.0 26
Android 7.1 25
Android 7.0 24
Android 6.0 23
Android 5.1 22
Android 5.0 21
Android 4.4W 20
Android 4.4 19
Android 4.3 18
Android 4.2 17
Android 4.1 16
Android 4.0.3 15
Android 4.0 14
Android 3.2 13
Android 3.1 12
Android 3.0 11
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
CAUTION: don't use android.os.Build.VERSION.SDK_INT
if <uses-sdk android:minSdkVersion="3" />
.
You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT
is since SDK 4 (Donut 1.6).
How do I format axis number format to thousands with a comma in matplotlib?
I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.
Here's a simple solution if you have an axes named ax
:
ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])
python dataframe pandas drop column using int
Since there can be multiple columns with same name , we should first rename the columns.
Here is code for the solution.
df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns
How to make a button redirect to another page using jQuery or just Javascript
In your html, you can add data attribute to your button:
<button type="submit" class="mybtn" data-target="/search.html">Search</button>
Then you can use jQuery to change the url:
$('.mybtn').on('click', function(event) {
event.preventDefault();
var url = $(this).data('target');
location.replace(url);
});
Hope this helps
How to send a “multipart/form-data” POST in Android with Volley
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
HttpPost req = new HttpPost(composeTargetUrl());
MultipartEntity entity = new MultipartEntity();
entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
try {
entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
req.setEntity(entity);
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
Truncating long strings with CSS: feasible yet?
2014 March: Truncating long strings with CSS: a new answer with focus on browser support
Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).
<style type="text/css">
span {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
-o-text-overflow: ellipsis; /** Opera 9 & 10 **/
width: 370px; /* note that this width will have to be smaller to see the effect */
}
</style>
<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>
The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.
Successfully tested (on Browserstack.com) on Windows OS, for web browsers:
- IE6 to IE11
- Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
- Chrome 14, Chrome 20, Chrome 25
- Safari 4.0, Safari 5.0, Safari 5.1
- Firefox 7.0, Firefox 15
Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).
I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).
Some further testing on a Mac OS web browsers would be needed.
Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated
Resources:
Make just one slide different size in Powerpoint
if you want to shrink one slide for instance, add shapes to hide the unwanted background margins. you can set the shape color filling as the background (gray or black).
It's "ugly" but it works
Save matplotlib file to a directory
Here is a simple example for saving to a directory(external usb drive) using Python version 2.7.10 with Sublime Text 2 editor:
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint = True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C, color = "blue", linewidth = 1.0, linestyle = "-")
plt.plot(X, S, color = "red", linewidth = 1.0, linestyle = "-")
plt.savefig("/Volumes/seagate/temp_swap/sin_cos_2.png", dpi = 72)
Installing MySQL-python
Python or Python3 with MySQL, you will need these. These libraries use MySQL's connector for C and Python (you need the C libraries installed as well), which overcome some of the limitations of the mysqldb libraries.
sudo apt-get install libmysqlclient-dev
sudo apt-get install python-mysql.connector
sudo apt-get install python3-mysql.connector
How do I make an HTTP request in Swift?
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject) {
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Success: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
// You can add your own sets of parameter here.