Parsing XML with namespace in Python via 'ElementTree'
ElementTree is not too smart about namespaces. You need to give the .find()
, findall()
and iterfind()
methods an explicit namespace dictionary. This is not documented very well:
namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed
root.findall('owl:Class', namespaces)
Prefixes are only looked up in the namespaces
parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl:
part, looks up the corresponding namespace URL in the namespaces
dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class
instead. You can use the same syntax yourself too of course:
root.findall('{http://www.w3.org/2002/07/owl#}Class')
If you can switch to the lxml
library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap
attribute on elements.
Why there is no ConcurrentHashSet against ConcurrentHashMap
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>{
private final ConcurrentMap<E, Object> theMap;
private static final Object dummy = new Object();
public ConcurrentHashSet(){
theMap = new ConcurrentHashMap<E, Object>();
}
@Override
public int size() {
return theMap.size();
}
@Override
public Iterator<E> iterator(){
return theMap.keySet().iterator();
}
@Override
public boolean isEmpty(){
return theMap.isEmpty();
}
@Override
public boolean add(final E o){
return theMap.put(o, ConcurrentHashSet.dummy) == null;
}
@Override
public boolean contains(final Object o){
return theMap.containsKey(o);
}
@Override
public void clear(){
theMap.clear();
}
@Override
public boolean remove(final Object o){
return theMap.remove(o) == ConcurrentHashSet.dummy;
}
public boolean addIfAbsent(final E o){
Object obj = theMap.putIfAbsent(o, ConcurrentHashSet.dummy);
return obj == null;
}
}
SQL: How to to SUM two values from different tables
you can also try this in sql-server !!
select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city
demo
or try using sum,union
select sum(total) as mytotal,city
from
(
select * from cash union
select * from cheque
) as vij
group by city
How can I populate a select dropdown list from a JSON feed with AngularJS?
The proper way to do it is using the ng-options
directive. The HTML would look like this.
<select ng-model="selectedTestAccount"
ng-options="item.Id as item.Name for item in testAccounts">
<option value="">Select Account</option>
</select>
JavaScript:
angular.module('test', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/Admin/GetTestAccounts',
data: { applicationId: 3 }
}).success(function (result) {
$scope.testAccounts = result;
});
});
You'll also need to ensure angular is run on your html and that your module is loaded.
<html ng-app="test">
<body ng-controller="DemoCtrl">
....
</body>
</html>
Comparing Java enum members: == or equals()?
The reason enums work easily with == is because each defined instance is also a singleton. So identity comparison using == will always work.
But using == because it works with enums means all your code is tightly coupled with usage of that enum.
For example: Enums can implement an interface. Suppose you are currently using an enum which implements Interface1. If later on, someone changes it or introduces a new class Impl1 as an implementation of same interface. Then, if you start using instances of Impl1, you'll have a lot of code to change and test because of previous usage of ==.
Hence, it's best to follow what is deemed a good practice unless there is any justifiable gain.
Angular - ui-router get previous state
I keep track of previous states in $rootScope, so whenever in need I will just call the below line of code.
$state.go($rootScope.previousState);
In App.js:
$rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) {
$rootScope.previousState = from.name;
});
Docker how to change repository name or rename image?
docker image tag server:latest myname/server:latest
or
docker image tag d583c3ac45fd myname/server:latest
Tags are just human-readable aliases for the full image name (d583c3ac45fd...
).
So you can have as many of them associated with the same image as you like. If you don't like the old name you can remove it after you've retagged it:
docker rmi server
That will just remove the alias/tag
. Since d583c3ac45fd
has other names, the actual image won't be deleted.
Pandas "Can only compare identically-labeled DataFrame objects" error
When you compare two DataFrames, you must ensure that the number of records in the first DataFrame matches with the number of records in the second DataFrame. In our example, each of the two DataFrames had 4 records, with 4 products and 4 prices.
If, for example, one of the DataFrames had 5 products, while the other DataFrame had 4 products, and you tried to run the comparison, you would get the following error:
ValueError: Can only compare identically-labeled Series objects
this should work
import pandas as pd
import numpy as np
firstProductSet = {'Product1': ['Computer','Phone','Printer','Desk'],
'Price1': [1200,800,200,350]
}
df1 = pd.DataFrame(firstProductSet,columns= ['Product1', 'Price1'])
secondProductSet = {'Product2': ['Computer','Phone','Printer','Desk'],
'Price2': [900,800,300,350]
}
df2 = pd.DataFrame(secondProductSet,columns= ['Product2', 'Price2'])
df1['Price2'] = df2['Price2'] #add the Price2 column from df2 to df1
df1['pricesMatch?'] = np.where(df1['Price1'] == df2['Price2'], 'True', 'False') #create new column in df1 to check if prices match
df1['priceDiff?'] = np.where(df1['Price1'] == df2['Price2'], 0, df1['Price1'] - df2['Price2']) #create new column in df1 for price diff
print (df1)
example from https://datatofish.com/compare-values-dataframes/
How to ignore the first line of data when processing CSV data?
Because this is related to something I was doing, I'll share here.
What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?
If your task is basic, such as printing or appending to a list or array, you could just use an if statement:
# Let's say there's 4 columns
with open('file.csv') as csvfile:
csvreader = csv.reader(csvfile)
# read first line
first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
if len(first_line) == 4:
array.append(first_line)
# Now we'll just iterate over everything else as usual:
for row in csvreader:
array.append(row)
Initialize a string variable in Python: "" or None?
Either way is okay in python. I would personally prefer "". but again, either way is okay
>>>x = None
>>>print(x)
None
>>>type(x)
<class 'NoneType'>
>>>x = "hello there"
>>>print(x)
hello there
>>>type(x)
<class 'str'>
>>>
>>>x = ""
>>>print(x)
>>>type(x)
<class 'str'>
>>>x = "hello there"
>>>type(x)
<class 'str'>
>>>print(x)
hello there
How to show validation message below each textbox using jquery?
The way I would do it is to create paragraph tags where you want your error messages with the same class and show them when the data is invalid. Here is my fiddle
if ($('#email').val() == '' || !$('#password').val() == '') {
$('.loginError').show();
return false;
}
I also added the paragraph tags below the email and password inputs
<p class="loginError" style="display:none;">please enter your email address or password.</p>
Can't connect to MySQL server on 'localhost' (10061) after Installation
The solution that fixed the issue was using the following steps:
In Start Menu, search for "mysql". Among the results, you should see the "MySQL Installer - Community". Run it.
MySQL Installer window will show up as shown below. Find "MySQL Server" under Product and click on "Reconfigure" link.
MySQL Installer Community
The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.
After the MySQL Installer was finished, I started the MySQL service again.
Pass arguments into C program from command line
You could use getopt.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (int argc, char **argv)
{
int bflag = 0;
int sflag = 0;
int index;
int c;
opterr = 0;
while ((c = getopt (argc, argv, "bs")) != -1)
switch (c)
{
case 'b':
bflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
printf ("bflag = %d, sflag = %d\n", bflag, sflag);
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Ruby sleep or delay less than a second?
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
- Use a timer which fires 24 times a second with the drawing code.
- Create as many frames as possible, create the motion based on the time passed, not per frame.
How to strip HTML tags from string in JavaScript?
I know this question has an accepted answer, but I feel that it doesn't work in all cases.
For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):
http://phpjs.org/functions/strip_tags:535
It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script />
tag above.
Detect if user is scrolling
If you want detect when user scroll over certain div, you can do something like this:
window.onscroll = function() {
var distanceScrolled = document.documentElement.scrollTop;
console.log('Scrolled: ' + distanceScrolled);
}
For example, if your div appear after scroll until the position 112:
window.onscroll = function() {
var distanceScrolled = document.documentElement.scrollTop;
if (distanceScrolled > 112) {
do something...
}
}
But as you can see you don't need a div, just the offset distance you want something to happen.
How to check type of object in Python?
What type() means:
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
For comparisons:
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Using "label for" on radio buttons
Either structure is valid and accessible, but the for
attribute should be equal to the id
of the input element:
<input type="radio" ... id="r1" /><label for="r1">button text</label>
or
<label for="r1"><input type="radio" ... id="r1" />button text</label>
The for
attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +
:
input[type="radio"]:checked+label {font-weight:bold;}
Python Requests and persistent sessions
the other answers help to understand how to maintain such a session. Additionally, I want to provide a class which keeps the session maintained over different runs of a script (with a cache file). This means a proper "login" is only performed when required (timout or no session exists in cache). Also it supports proxy settings over subsequent calls to 'get' or 'post'.
It is tested with Python3.
Use it as a basis for your own code. The following snippets are release with GPL v3
import pickle
import datetime
import os
from urllib.parse import urlparse
import requests
class MyLoginSession:
"""
a class which handles and saves login sessions. It also keeps track of proxy settings.
It does also maintine a cache-file for restoring session data from earlier
script executions.
"""
def __init__(self,
loginUrl,
loginData,
loginTestUrl,
loginTestString,
sessionFileAppendix = '_session.dat',
maxSessionTimeSeconds = 30 * 60,
proxies = None,
userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1',
debug = True,
forceLogin = False,
**kwargs):
"""
save some information needed to login the session
you'll have to provide 'loginTestString' which will be looked for in the
responses html to make sure, you've properly been logged in
'proxies' is of format { 'https' : 'https://user:pass@server:port', 'http' : ...
'loginData' will be sent as post data (dictionary of id : value).
'maxSessionTimeSeconds' will be used to determine when to re-login.
"""
urlData = urlparse(loginUrl)
self.proxies = proxies
self.loginData = loginData
self.loginUrl = loginUrl
self.loginTestUrl = loginTestUrl
self.maxSessionTime = maxSessionTimeSeconds
self.sessionFile = urlData.netloc + sessionFileAppendix
self.userAgent = userAgent
self.loginTestString = loginTestString
self.debug = debug
self.login(forceLogin, **kwargs)
def modification_date(self, filename):
"""
return last file modification date as datetime object
"""
t = os.path.getmtime(filename)
return datetime.datetime.fromtimestamp(t)
def login(self, forceLogin = False, **kwargs):
"""
login to a session. Try to read last saved session from cache file. If this fails
do proper login. If the last cache access was too old, also perform a proper login.
Always updates session cache file.
"""
wasReadFromCache = False
if self.debug:
print('loading or generating session...')
if os.path.exists(self.sessionFile) and not forceLogin:
time = self.modification_date(self.sessionFile)
# only load if file less than 30 minutes old
lastModification = (datetime.datetime.now() - time).seconds
if lastModification < self.maxSessionTime:
with open(self.sessionFile, "rb") as f:
self.session = pickle.load(f)
wasReadFromCache = True
if self.debug:
print("loaded session from cache (last access %ds ago) "
% lastModification)
if not wasReadFromCache:
self.session = requests.Session()
self.session.headers.update({'user-agent' : self.userAgent})
res = self.session.post(self.loginUrl, data = self.loginData,
proxies = self.proxies, **kwargs)
if self.debug:
print('created new session with login' )
self.saveSessionToCache()
# test login
res = self.session.get(self.loginTestUrl)
if res.text.lower().find(self.loginTestString.lower()) < 0:
raise Exception("could not log into provided site '%s'"
" (did not find successful login string)"
% self.loginUrl)
def saveSessionToCache(self):
"""
save session to a cache file
"""
# always save (to update timeout)
with open(self.sessionFile, "wb") as f:
pickle.dump(self.session, f)
if self.debug:
print('updated session cache-file %s' % self.sessionFile)
def retrieveContent(self, url, method = "get", postData = None, **kwargs):
"""
return the content of the url with respect to the session.
If 'method' is not 'get', the url will be called with 'postData'
as a post request.
"""
if method == 'get':
res = self.session.get(url , proxies = self.proxies, **kwargs)
else:
res = self.session.post(url , data = postData, proxies = self.proxies, **kwargs)
# the session has been updated on the server, so also update in cache
self.saveSessionToCache()
return res
A code snippet for using the above class may look like this:
if __name__ == "__main__":
# proxies = {'https' : 'https://user:pass@server:port',
# 'http' : 'http://user:pass@server:port'}
loginData = {'user' : 'usr',
'password' : 'pwd'}
loginUrl = 'https://...'
loginTestUrl = 'https://...'
successStr = 'Hello Tom'
s = MyLoginSession(loginUrl, loginData, loginTestUrl, successStr,
#proxies = proxies
)
res = s.retrieveContent('https://....')
print(res.text)
# if, for instance, login via JSON values required try this:
s = MyLoginSession(loginUrl, None, loginTestUrl, successStr,
#proxies = proxies,
json = loginData)
What do all of Scala's symbolic operators mean?
I divide the operators, for the purpose of teaching, into four categories:
- Keywords/reserved symbols
- Automatically imported methods
- Common methods
- Syntactic sugars/composition
It is fortunate, then, that most categories are represented in the question:
-> // Automatically imported method
||= // Syntactic sugar
++= // Syntactic sugar/composition or common method
<= // Common method
_._ // Typo, though it's probably based on Keyword/composition
:: // Common method
:+= // Common method
The exact meaning of most of these methods depend on the class that is defining them. For example, <=
on Int
means "less than or equal to". The first one, ->
, I'll give as example below. ::
is probably the method defined on List
(though it could be the object of the same name), and :+=
is probably the method defined on various Buffer
classes.
So, let's see them.
Keywords/reserved symbols
There are some symbols in Scala that are special. Two of them are considered proper keywords, while others are just "reserved". They are:
// Keywords
<- // Used on for-comprehensions, to separate pattern from generator
=> // Used for function types, function literals and import renaming
// Reserved
( ) // Delimit expressions and parameters
[ ] // Delimit type parameters
{ } // Delimit blocks
. // Method call and path separator
// /* */ // Comments
# // Used in type notations
: // Type ascription or context bounds
<: >: <% // Upper, lower and view bounds
<? <! // Start token for various XML elements
" """ // Strings
' // Indicate symbols and characters
@ // Annotations and variable binding on pattern matching
` // Denote constant or enable arbitrary identifiers
, // Parameter separator
; // Statement separator
_* // vararg expansion
_ // Many different meanings
These are all part of the language, and, as such, can be found in any text that properly describe the language, such as Scala Specification(PDF) itself.
The last one, the underscore, deserve a special description, because it is so widely used, and has so many different meanings. Here's a sample:
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
I probably forgot some other meaning, though.
Automatically imported methods
So, if you did not find the symbol you are looking for in the list above, then it must be a method, or part of one. But, often, you'll see some symbol and the documentation for the class will not have that method. When this happens, either you are looking at a composition of one or more methods with something else, or the method has been imported into scope, or is available through an imported implicit conversion.
These can still be found on ScalaDoc: you just have to know where to look for them. Or, failing that, look at the index (presently broken on 2.9.1, but available on nightly).
Every Scala code has three automatic imports:
// Not necessarily in this order
import _root_.java.lang._ // _root_ denotes an absolute path
import _root_.scala._
import _root_.scala.Predef._
The first two only make classes and singleton objects available. The third one contains all implicit conversions and imported methods, since Predef
is an object itself.
Looking inside Predef
quickly show some symbols:
class <:<
class =:=
object <%<
object =:=
Any other symbol will be made available through an implicit conversion. Just look at the methods tagged with implicit
that receive, as parameter, an object of type that is receiving the method. For example:
"a" -> 1 // Look for an implicit from String, AnyRef, Any or type parameter
In the above case, ->
is defined in the class ArrowAssoc
through the method any2ArrowAssoc
that takes an object of type A
, where A
is an unbounded type parameter to the same method.
Common methods
So, many symbols are simply methods on a class. For instance, if you do
List(1, 2) ++ List(3, 4)
You'll find the method ++
right on the ScalaDoc for List. However, there's one convention that you must be aware when searching for methods. Methods ending in colon (:
) bind to the right instead of the left. In other words, while the above method call is equivalent to:
List(1, 2).++(List(3, 4))
If I had, instead 1 :: List(2, 3)
, that would be equivalent to:
List(2, 3).::(1)
So you need to look at the type found on the right when looking for methods ending in colon. Consider, for instance:
1 +: List(2, 3) :+ 4
The first method (+:
) binds to the right, and is found on List
. The second method (:+
) is just a normal method, and binds to the left -- again, on List
.
Syntactic sugars/composition
So, here's a few syntactic sugars that may hide a method:
class Example(arr: Array[Int] = Array.fill(5)(0)) {
def apply(n: Int) = arr(n)
def update(n: Int, v: Int) = arr(n) = v
def a = arr(0); def a_=(v: Int) = arr(0) = v
def b = arr(1); def b_=(v: Int) = arr(1) = v
def c = arr(2); def c_=(v: Int) = arr(2) = v
def d = arr(3); def d_=(v: Int) = arr(3) = v
def e = arr(4); def e_=(v: Int) = arr(4) = v
def +(v: Int) = new Example(arr map (_ + v))
def unapply(n: Int) = if (arr.indices contains n) Some(arr(n)) else None
}
val Ex = new Example // or var for the last example
println(Ex(0)) // calls apply(0)
Ex(0) = 2 // calls update(0, 2)
Ex.b = 3 // calls b_=(3)
// This requires Ex to be a "val"
val Ex(c) = 2 // calls unapply(2) and assigns result to c
// This requires Ex to be a "var"
Ex += 1 // substituted for Ex = Ex + 1
The last one is interesting, because any symbolic method can be combined to form an assignment-like method that way.
And, of course, there's various combinations that can appear in code:
(_+_) // An expression, or parameter, that is an anonymous function with
// two parameters, used exactly where the underscores appear, and
// which calls the "+" method on the first parameter passing the
// second parameter as argument.
Bootstrap: change background color
You could hard code it.
<div class="col-md-6" style="background-color:blue;">
</div>
<div class="col-md-6" style="background-color:white;">
</div>
How do I change the figure size with subplots?
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
How can you get the first digit in an int (C#)?
Very simple (and probably quite fast because it only involves comparisons and one division):
if(i<10)
firstdigit = i;
else if (i<100)
firstdigit = i/10;
else if (i<1000)
firstdigit = i/100;
else if (i<10000)
firstdigit = i/1000;
else if (i<100000)
firstdigit = i/10000;
else (etc... all the way up to 1000000000)
How to npm install to a specified directory?
In the documentation it's stated:
Use the prefix option together with the global option:
The prefix config defaults to the location where node is installed. On
most systems, this is /usr/local. On windows, this is the exact
location of the node.exe binary. On Unix systems, it's one level up,
since node is typically installed at {prefix}/bin/node rather than
{prefix}/node.exe.
When the global flag is set, npm installs things into this prefix.
When it is not set, it uses the root of the current package, or the
current working directory if not in a package already.
(Emphasis by them)
So in your root directory you could install with
npm install --prefix <path/to/prefix_folder> -g
and it will install the node_modules
folder into the folder
<path/to/prefix_folder>/lib/node_modules
Styling a disabled input with css only
A space in a CSS selector selects child elements.
.btn input
This is basically what you wrote and it would select <input>
elements within any element that has the btn
class.
I think you're looking for
input[disabled].btn:hover, input[disabled].btn:active, input[disabled].btn:focus
This would select <input>
elements with the disabled
attribute and the btn
class in the three different states of hover
, active
and focus
.
How does one make random number between range for arc4random_uniform()?
I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:
extension Int
{
static func random(range: Range<Int> ) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
use like
var aRandomInt = Int.random(-500...100) // returns a random number within the given range.
or define it as a Range extension as property like this:
extension Range
{
var randomInt: Int
{
get
{
var offset = 0
if (startIndex as Int) < 0 // allow negative ranges
{
offset = abs(startIndex as Int)
}
let mini = UInt32(startIndex as Int + offset)
let maxi = UInt32(endIndex as Int + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
}
// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt
Multiple conditions in a C 'for' loop
The comma operator evaluates all its operands and yields the value of the last one. So basically whichever condition you write first, it will be disregarded, and the second one will be significant only.
for (i = 0; j >= 0, i <= 5; i++)
is thus equivalent with
for (i = 0; i <= 5; i++)
which may or may not be what the author of the code intended, depending on his intents - I hope this is not production code, because if the programmer having written this wanted to express an AND relation between the conditions, then this is incorrect and the &&
operator should have been used instead.
How to find if an array contains a string
Using the code from my answer to a very similar question:
Sub DoSomething()
Dim Mainfram(4) As String
Dim cell As Excel.Range
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
For Each cell In Selection
If IsInArray(cell.Value, MainFram) Then
Row(cell.Row).Style = "Accent1"
End If
Next cell
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
How do I get the height of a div's full content with jQuery?
Element.scrollHeight
is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow
and height
to auto
, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.
how to call a onclick function in <a> tag?
Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.
Example:
function newwin() {
myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}
See how to call it from your anchor tag
<a onclick='newwin()'>Anchor</a>
Update
Visit this jsbin
http://jsbin.com/icUTUjI/1/edit
May be this will help you a lot to understand your problem.
std::string to char*
For completeness' sake, don't forget std::string::copy()
.
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
str.copy(chrs, MAX);
std::string::copy()
doesn't NUL terminate. If you need to ensure a NUL terminator for use in C string functions:
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
memset(chrs, '\0', MAX);
str.copy(chrs, MAX-1);
Convert Json string to Json object in Swift 4
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
How does facebook, gmail send the real time notification?
The way Facebook does this is pretty interesting.
A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.
The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.
Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.
In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.
Implementing:
Server Side:
There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:
while(!has_event_happened()) {
sleep(5);
}
echo json_encode(get_events());
The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.
Don't forget to change your PHP max execution time, otherwise it will timeout early!
Client Side:
Take a look at the jQuery plugin for doing Comet interaction:
That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:
function doPoll() {
$.get("events.php", {}, function(result) {
$.each(result.events, function(event) { //iterate over the events
//do something with your event
});
doPoll();
//this effectively causes the poll to run again as
//soon as the response comes back
}, 'json');
}
$(document).ready(function() {
$.ajaxSetup({
timeout: 1000*60//set a global AJAX timeout of a minute
});
doPoll(); // do the first poll
});
The whole thing depends a lot on how your existing architecture is put together.
How do I use NSTimer?
Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer
, the documentation lists two companion guides:
For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:
For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management". From the article, creating a scheduled, non-repeating timer can be done something like this:
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:NO];
This will create a timer that is fired after 2.0 seconds and calls targetMethod:
on self
with one argument, which is a pointer to the NSTimer
instance.
If you then want to look in more detail at the method you can refer back to the docs for more information, but there is explanation around the code too.
If you want to stop a timer that is one which repeats, (or stop a non-repeating timer before it fires) then you need to keep a pointer to the NSTimer
instance that was created; often this will need to be an instance variable so that you can refer to it in another method. You can then call invalidate
on the NSTimer
instance:
[myTimer invalidate];
myTimer = nil;
It's also good practice to nil
out the instance variable (for example if your method that invalidates the timer is called more than once and the instance variable hasn't been set to nil
and the NSTimer
instance has been deallocated, it will throw an exception).
Note also the point on Memory Management at the bottom of the article:
Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.
Convert all strings in a list to int
You can do it simply in one line when taking input.
[int(i) for i in input().split("")]
Split it where you want.
If you want to convert a list not list simply put your list name in the place of input().split("")
.
Onclick CSS button effect
Push down the whole button. I suggest this it is looking nice in button.
#button:active {
position: relative;
top: 1px;
}
if you only want to push text increase top-padding and decrease bottom padding.
You can also use line-height.
Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)
While developing the application we need to define the PORT in the following way:
const port = process.env.PORT || 4000; // PORT must be in caps
And while deploying the app to server add the following method:
app.listen(port, () => {
console.info("Server started listening.");
});
We can pass hostname as second parameter while running it in local. But while deploying it to server the hostname parameter should be removed.
app.listen(port, hostName, () => {
console.info(`Server listening at http://${hostName}:${port}`);
});
Regular Expressions and negating a whole character group
Use negative lookahead:
^(?!.*ab).*$
UPDATE: In the comments below, I stated that this approach is slower than the one given in Peter's answer. I've run some tests since then, and found that it's really slightly faster. However, the reason to prefer this technique over the other is not speed, but simplicity.
The other technique, described here as a tempered greedy token, is suitable for more complex problems, like matching delimited text where the delimiters consist of multiple characters (like HTML, as Luke commented below). For the problem described in the question, it's overkill.
For anyone who's interested, I tested with a large chunk of Lorem Ipsum text, counting the number of lines that don't contain the word "quo". These are the regexes I used:
(?m)^(?!.*\bquo\b).+$
(?m)^(?:(?!\bquo\b).)+$
Whether I search for matches in the whole text, or break it up into lines and match them individually, the anchored lookahead consistently outperforms the floating one.
jQuery: get parent tr for selected radio button
Try this.
You don't need to prefix attribute name by @
in jQuery selector. Use closest()
method to get the closest parent element matching the selector.
$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');
You can simplify your method like this
function getSelectedRowGuid() {
return GetRowGuid(
$("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}
closest()
- Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.
How to disable the ability to select in a DataGridView?
Enabled
property to false
or
this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;
Using "word-wrap: break-word" within a table
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
http://jsfiddle.net/LLyH3/3/
Also, if this doesn't solve your problem, there's a similar thread here.
fork: retry: Resource temporarily unavailable
This is commonly caused by running out of file descriptors.
There is the systems total file descriptor limit, what do you get from the command:
sysctl fs.file-nr
This returns counts of file descriptors:
<in_use> <unused_but_allocated> <maximum>
To find out what a users file descriptor limit is run the commands:
sudo su - <username>
ulimit -Hn
To find out how many file descriptors are in use by a user run the command:
sudo lsof -u <username> 2>/dev/null | wc -l
So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.
fs.file-max = 204708
Convert integer to hex and hex to integer
Maksym Kozlenko has a nice solution, and others come close to unlocking it's full potential but then miss completely to realized that you can define any sequence of characters, and use it's length as the Base. Which is why I like this slightly modified version of his solution, because it can work for base 16, or base 17, and etc.
For example, what if you wanted letters and numbers, but don't like I's for looking like 1's and O's for looking like 0's. You can define any sequence this way. Below is a form of a "Base 36" that skips the I and O to create a "modified base 34". Un-comment the hex line instead to run as hex.
declare @value int = 1234567890
DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result varchar(50)
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue int = @value
SET @result = SUBSTRING(@seq, (@workingValue%@baseSize)+1, 1)
WHILE @workingValue > 0
BEGIN
SET @digit = SUBSTRING(@seq, ((@workingValue/@baseSize)%@baseSize)+1, 1)
SET @workingValue = @workingValue/@baseSize
IF @workingValue <> 0 SET @result = @digit + @result
END
select @value as Value, @baseSize as BaseSize, @result as Result
Value, BaseSize, Result
1234567890, 34, T5URAA
I also moved value over to a working value, and then work from the working value copy, as a personal preference.
Below is additional for reversing the transformation, for any sequence, with the base defined as the length of the sequence.
declare @value varchar(50) = 'T5URAA'
DECLARE @seq varchar(100) = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ' -- modified base 34
--DECLARE @seq varchar(100) = '0123456789ABCDEF' -- hex
DECLARE @result int = 0
DECLARE @digit char(1)
DECLARE @baseSize int = len(@seq)
DECLARE @workingValue varchar(50) = @value
DECLARE @PositionMultiplier int = 1
DECLARE @digitPositionInSequence int = 0
WHILE len(@workingValue) > 0
BEGIN
SET @digit = right(@workingValue,1)
SET @digitPositionInSequence = CHARINDEX(@digit,@seq)
SET @result = @result + ( (@digitPositionInSequence -1) * @PositionMultiplier)
--select @digit, @digitPositionInSequence, @PositionMultiplier, @result
SET @workingValue = left(@workingValue,len(@workingValue)-1)
SET @PositionMultiplier = @PositionMultiplier * @baseSize
END
select @value as Value, @baseSize as BaseSize, @result as Result
Create, read, and erase cookies with jQuery
As I know, there is no direct support, but you can use plain-ol' javascript for that:
// Cookies
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
MongoDB running but can't connect using shell
If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Then you mongo client will be able to connect your remove mongodb
How to use a dot "." to access members of dictionary?
To build upon epool's answer, this version allows you to access any dict inside via the dot operator:
foo = {
"bar" : {
"baz" : [ {"boo" : "hoo"} , {"baba" : "loo"} ]
}
}
For instance, foo.bar.baz[1].baba
returns "loo"
.
class Map(dict):
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.items():
if isinstance(v, dict):
v = Map(v)
if isinstance(v, list):
self.__convert(v)
self[k] = v
if kwargs:
for k, v in kwargs.items():
if isinstance(v, dict):
v = Map(v)
elif isinstance(v, list):
self.__convert(v)
self[k] = v
def __convert(self, v):
for elem in range(0, len(v)):
if isinstance(v[elem], dict):
v[elem] = Map(v[elem])
elif isinstance(v[elem], list):
self.__convert(v[elem])
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
How to remove spaces from a string using JavaScript?
var output = '/var/www/site/Brand new document.docx'.replace(/ /g, "");
or
var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");
Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.
If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.
for reference click here.
Git: How to remove file from index without deleting files from any repository
The above solutions work fine for most cases.
However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.
Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.
https://help.github.com/articles/remove-sensitive-data/
You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.
To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.
It looked intimidating at first, but really, was easy and worked like a charm ! :-)
Threading pool similar to the multiprocessing Pool?
If you don't mind executing other's code, here's mine:
Note: There is lot of extra code you may want to remove [added for better clarificaiton and demonstration how it works]
Note: Python naming conventions were used for method names and variable names instead of camelCase.
Working procedure:
- MultiThread class will initiate with no of instances of threads by sharing lock, work queue, exit flag and results.
- SingleThread will be started by MultiThread once it creates all instances.
- We can add works using MultiThread (It will take care of locking).
- SingleThreads will process work queue using a lock in middle.
- Once your work is done, you can destroy all threads with shared boolean value.
- Here, work can be anything. It can automatically import (uncomment import line) and process module using given arguments.
- Results will be added to results and we can get using get_results
Code:
import threading
import queue
class SingleThread(threading.Thread):
def __init__(self, name, work_queue, lock, exit_flag, results):
threading.Thread.__init__(self)
self.name = name
self.work_queue = work_queue
self.lock = lock
self.exit_flag = exit_flag
self.results = results
def run(self):
# print("Coming %s with parameters %s", self.name, self.exit_flag)
while not self.exit_flag:
# print(self.exit_flag)
self.lock.acquire()
if not self.work_queue.empty():
work = self.work_queue.get()
module, operation, args, kwargs = work.module, work.operation, work.args, work.kwargs
self.lock.release()
print("Processing : " + operation + " with parameters " + str(args) + " and " + str(kwargs) + " by " + self.name + "\n")
# module = __import__(module_name)
result = str(getattr(module, operation)(*args, **kwargs))
print("Result : " + result + " for operation " + operation + " and input " + str(args) + " " + str(kwargs))
self.results.append(result)
else:
self.lock.release()
# process_work_queue(self.work_queue)
class MultiThread:
def __init__(self, no_of_threads):
self.exit_flag = bool_instance()
self.queue_lock = threading.Lock()
self.threads = []
self.work_queue = queue.Queue()
self.results = []
for index in range(0, no_of_threads):
thread = SingleThread("Thread" + str(index+1), self.work_queue, self.queue_lock, self.exit_flag, self.results)
thread.start()
self.threads.append(thread)
def add_work(self, work):
self.queue_lock.acquire()
self.work_queue._put(work)
self.queue_lock.release()
def destroy(self):
self.exit_flag.value = True
for thread in self.threads:
thread.join()
def get_results(self):
return self.results
class Work:
def __init__(self, module, operation, args, kwargs={}):
self.module = module
self.operation = operation
self.args = args
self.kwargs = kwargs
class SimpleOperations:
def sum(self, *args):
return sum([int(arg) for arg in args])
@staticmethod
def mul(a, b, c=0):
return int(a) * int(b) + int(c)
class bool_instance:
def __init__(self, value=False):
self.value = value
def __setattr__(self, key, value):
if key != "value":
raise AttributeError("Only value can be set!")
if not isinstance(value, bool):
raise AttributeError("Only True/False can be set!")
self.__dict__[key] = value
# super.__setattr__(key, bool(value))
def __bool__(self):
return self.value
if __name__ == "__main__":
multi_thread = MultiThread(5)
multi_thread.add_work(Work(SimpleOperations(), "mul", [2, 3], {"c":4}))
while True:
data_input = input()
if data_input == "":
pass
elif data_input == "break":
break
else:
work = data_input.split()
multi_thread.add_work(Work(SimpleOperations(), work[0], work[1:], {}))
multi_thread.destroy()
print(multi_thread.get_results())
java.net.URL read stream to byte[]
Use commons-io IOUtils.toByteArray(URL):
String url = "http://localhost:8080/images/anImage.jpg";
byte[] fileContent = IOUtils.toByteArray(new URL(url));
Maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
C# - Multiple generic types in one list
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
Return array in a function
to return an array from a function , let us define that array in a structure;
So it looks something like this
struct Marks{
int list[5];
}
Now let us create variables of the type structure.
typedef struct Marks marks;
marks marks_list;
We can pass array to a function in the following way and assign value to it:
void setMarks(int marks_array[]){
for(int i=0;i<sizeof(marks_array)/sizeof(int);i++)
marks_list.list[i]=marks_array[i];
}
We can also return the array. To return the array , the return type of the function should be of structure type ie marks. This is because in reality we are passing the structure that contains the array. So the final code may look like this.
marks getMarks(){
return marks_list;
}
Is there a destructor for Java?
First, note that since Java is garbage-collected, it is rare to need to do anything about object destruction. Firstly because you don't usually have any managed resources to free, and secondly because you can't predict when or if it will happen, so it's inappropriate for things that you need to occur "as soon as nobody is using my object any more".
You can be notified after an object has been destroyed using java.lang.ref.PhantomReference (actually, saying it has been destroyed may be slightly inaccurate, but if a phantom reference to it is queued then it's no longer recoverable, which usually amounts to the same thing). A common use is:
- Separate out the resource(s) in your class that need to be destructed into another helper object (note that if all you're doing is closing a connection, which is a common case, you don't need to write a new class: the connection to be closed would be the "helper object" in that case).
- When you create your main object, create also a PhantomReference to it. Either have this refer to the new helper object, or set up a map from PhantomReference objects to their corresponding helper objects.
- After the main object is collected, the PhantomReference is queued (or rather it may be queued - like finalizers there is no guarantee it ever will be, for example if the VM exits then it won't wait). Make sure you're processing its queue (either in a special thread or from time to time). Because of the hard reference to the helper object, the helper object has not yet been collected. So do whatever cleanup you like on the helper object, then discard the PhantomReference and the helper will eventually be collected too.
There is also finalize(), which looks like a destructor but doesn't behave like one. It's usually not a good option.
Rollback transaction after @Test
You can disable the Rollback:
@TransactionConfiguration(defaultRollback = false)
Example:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@Transactional
@TransactionConfiguration(defaultRollback = false)
public class Test {
@PersistenceContext
private EntityManager em;
@org.junit.Test
public void menge() {
PersistentObject object = new PersistentObject();
em.persist(object);
em.flush();
}
}
How to send json data in POST request using C#
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
Placeholder Mixin SCSS/CSS
Why not something like this?
It uses a combination of lists, iteration, and interpolation.
@mixin placeholder ($rules) {
@each $rule in $rules {
::-webkit-input-placeholder,
:-moz-placeholder,
::-moz-placeholder,
:-ms-input-placeholder {
#{nth($rule, 1)}: #{nth($rule, 2)};
}
}
}
$rules: (('border', '1px solid red'),
('color', 'green'));
@include placeholder( $rules );
How to open a website when a Button is clicked in Android application?
If you are talking about an RCP app, then what you need is the SWT link
widget.
Here is the official link event handler snippet.
Update
Here is minimalist android application to connect to either superuser or stackoverflow with 2 buttons.
package ap.android;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class LinkButtons extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void goToSo (View view) {
goToUrl ( "http://stackoverflow.com/");
}
public void goToSu (View view) {
goToUrl ( "http://superuser.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
And here is the layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/select" />
<Button android:layout_height="wrap_content" android:clickable="true" android:autoLink="web" android:cursorVisible="true" android:layout_width="match_parent" android:id="@+id/button_so" android:text="StackOverflow" android:linksClickable="true" android:onClick="goToSo"></Button>
<Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"></Button>
</LinearLayout>
Bootstrap 3 2-column form layout
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_
http://jsfiddle.net/m3u8bjv0/2/
How do I add BundleConfig.cs to my project?
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
How to get an object's methods?
In ES6:
let myObj = {myFn : function() {}, tamato: true};
let allKeys = Object.keys(myObj);
let fnKeys = allKeys.filter(key => typeof myObj[key] == 'function');
console.log(fnKeys);
// output: ["myFn"]
How to detect if javascript files are loaded?
Change the loading order of your scripts so that function1
was defined before using it in ready
callback.
Plus I always found it better to define ready
callback as an anonymous method then named one.
How to pass payload via JSON file for curl?
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
How to deploy ASP.NET webservice to IIS 7?
- rebuild project in VS
- copy project folder to iis folder, probably C:\inetpub\wwwroot\
- in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
- add web service to created website, almost the same as 3.
- INSTALL ASP
for windows 7 and .net 4.0:
c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
- check access to web service on your browser
How to set value to variable using 'execute' in t-sql?
The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised
You'll have to use a temp table/table variable outside of the dynamic SQL:
DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)
INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')
select * FROM @siteId
Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY
HttpClient - A task was cancelled?
I ran into this issue because my Main()
method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask
was being cancelled when my console program exited.
The solution was to call myTask.GetAwaiter().GetResult()
in Main()
(from this answer).
Capturing count from an SQL query
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();
Change url query string value using jQuery
purls $.params()
used without a parameter will give you a key-value object of the parameters.
jQuerys $.param()
will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete
here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);
What is the boundary in multipart/form-data?
multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.
The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).
The payload passed looks something like this:
Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”file”; filename=”captcha”
Content-Type:
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name=”action”
submit
-----WebKitFormBoundary7MA4YWxkTrZu0gW--
On the webservice side, it's consumed in @Consumes("multipart/form-data") form.
Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.
See RFC1341 sec7.2 The Multipart Content-Type
Difference between acceptance test and functional test?
Acceptance testing:
... is black-box testing performed on a system (e.g. software, lots of manufactured mechanical parts, or batches of chemical products) prior to its delivery.
Though this goes on to say:
It is also known as functional testing, black-box testing, release acceptance, QA testing, application testing, confidence testing, final testing, validation testing, or factory acceptance testing
with a "citation needed" mark.
Functional testing (which actually redirects to System Testing):
conducted on a complete, integrated system to evaluate the system's compliance with its specified requirements. System testing falls within the scope of black box testing, and as such, should require no knowledge of the inner design of the code or logic.
So from this definition they are pretty much the same thing.
In my experience acceptance test are usually a subset of the functional tests and are used in the formal sign off process by the customer while functional/system tests will be those run by the developer/QA department.
Get current time in milliseconds in Python?
If you use my code (below), the time will appear in seconds, then, after a decimal, milliseconds. I think that there is a difference between Windows and Unix - please comment if there is.
from time import time
x = time()
print(x)
my result (on Windows) was:
1576095264.2682993
EDIT: There is no difference:) Thanks tc0nn
Casting to string in JavaScript
They behave the same but toString
also provides a way to convert a number binary, octal, or hexadecimal strings:
Example:
var a = (50274).toString(16) // "c462"
var b = (76).toString(8) // "114"
var c = (7623).toString(36) // "5vr"
var d = (100).toString(2) // "1100100"
Convert DataSet to List
Fill the dataset with data from, say a stored proc command
DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
adapter.Fill(ds);
Get The Schema,
string s = ds.GetXmlSchema();
save it to a file say: datasetSchema.xsd. Generate the C# classes for the Schema: (at the VS Command Prompt)
xsd datasetSchema.xsd /c
Now, when you need to convert the DataSet data to classes you can deserialize (the default name given to the generated root class is NewDataSet):
public static T Create<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
T t = (T)serializer.Deserialize(reader);
reader.Close();
return t;
}
}
var xml = ds.GetXml();
var dataSetObjects = Create<NewDataSet>(xml);
JAVA_HOME directory in Linux
I know this is late, but this command searches the /usr/ directory to find java for you
sudo find /usr/ -name *jdk
Results to
/usr/lib/jvm/java-6-openjdk
/usr/lib/jvm/java-1.6.0-openjdk
FYI, if you are on a Mac, currently JAVA_HOME is located at
/System/Library/Frameworks/JavaVM.framework/Home
Check if a property exists in a class
This answers a different question:
If trying to figure out if an OBJECT (not class) has a property,
OBJECT.GetType().GetProperty("PROPERTY") != null
returns true if (but not only if) the property exists.
In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.
@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
Model.AddTimeoffBlackouts)
helped me here.
Edit: Nowadays, it's probably smart to use the nameof
operator instead of the stringified property name.
Variable interpolation in the shell
Use
"$filepath"_newstap.sh
or
${filepath}_newstap.sh
or
$filepath\_newstap.sh
_
is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap
.
You can use set -u
to make the shell exit with an error when you reference an undefined variable.
Jersey stopped working with InjectionManagerFactory not found
Here is the new dependency (August 2017)
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.0-m03</version>
</dependency>
How should I use try-with-resources with JDBC?
There's no need for the outer try in your example, so you can at least go down from 3 to 2, and also you don't need closing ;
at the end of the resource list. The advantage of using two try blocks is that all of your code is present up front so you don't have to refer to a separate method:
public List<User> getUser(int userId) {
String sql = "SELECT id, username FROM users WHERE id = ?";
List<User> users = new ArrayList<>();
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
How can I find script's directory?
You need to call os.path.realpath
on __file__
, so that when __file__
is a filename without the path you still get the dir path:
import os
print(os.path.dirname(os.path.realpath(__file__)))
Move entire line up and down in Vim
Assuming the cursor is on the line you like to move.
Moving up and down:
:m
for move
:m +1
- moves down 1 line
:m -2
- move up 1 lines
(Note you can replace +1 with any numbers depending on how many lines you want to move it up or down, ie +2 would move it down 2 lines, -3 would move it up 2 lines)
To move to specific line
:set number
- display number lines (easier to see where you are moving it to)
:m 3
- move the line after 3rd line (replace 3 to any line you'd like)
Moving multiple lines:
V
(i.e. Shift-V) and move courser up and down to select multiple lines in VIM
once selected hit : and run the commands above, m +1
etc
Running multiple async tasks and waiting for them all to complete
Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:
var cats = new List<Cat>();
var dog = new Dog();
var loadDataTasks = new Task[]
{
Task.Run(async () => cats = await LoadCatsAsync()),
Task.Run(async () => dog = await LoadDogAsync())
};
try
{
await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
// handle exception
}
mysqli_select_db() expects parameter 1 to be mysqli, string given
Your arguments are in the wrong order. The connection comes first according to the docs
<?php
require("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
error_log("Failed to connect to MySQL: " . mysqli_error($connection));
die('Internal server error');
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
error_log("Database selection failed: " . mysqli_error($connection));
die('Internal server error');
}
?>
Why I get 411 Length required error?
Google search
2nd result
System.Net.WebException: The remote server returned an error: (411) Length Required.
This is a pretty common issue that comes up when trying to make call a
REST based API method through POST. Luckily, there is a simple fix for
this one.
This is the code I was using to call the Windows Azure Management API.
This particular API call requires the request method to be set as
POST, however there is no information that needs to be sent to the
server.
var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";
To fix this error, add an explicit content length to your request
before making the API call.
request.ContentLength = 0;
The character encoding of the plain text document was not declared - mootool script
I got this error using Spring Boot (in Mozilla),
because I was just testing some basic controller -> service -> repository communication by directly returning some entities from the database to the browser (as JSON).
I forgot to put data in the database, so my method wasn't returning anything... and I got this error.
Now that I put some data in my db, it works fine (the error is removed). :D
How to check if directory exists in %PATH%?
First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.
For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.
From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:
The trailing \
is optional in a path
Most paths work equally well both with and without the trailing \
. The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \
. This is probably the most common practical issue when searching a PATH for a match.
- There is one exception: The relative path
C:
(meaning the current working directory of drive C) is very different than C:\
(meaning the root directory of drive C)
Some paths have alternate short names
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.
Windows accepts both /
and \
as folder separators within a path.
This is not seen very often, but a path can be specified using /
instead of \
and it will function just fine within PATH (as well as in many other Windows contexts)
Windows treats consecutive folder separators as one logical separator.
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \
to a path without bothering to check if the trailing \
already exists. But this obviously can cause problems if trying to perform an exact string match.
- Exceptions: Not only is
C:
, different than C:\
, but C:\
(a valid path), is different than C:\\
(an invalid path).
Windows trims trailing dots and spaces from file and directory names.
"C:\test. "
is equivalent to "C:\test"
.
The current .\
and parent ..\
folder specifiers may appear within a path
Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\
is equivalent to C:\parent\child
A path can optionally be enclosed within double quotes.
A path is often enclosed in quotes to protect against special characters like <space>
,
;
^
&
=
. Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ;
, but the quotes may be present never-the-less.
A path may be fully qualified or relative.
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:
D:
is relative to the current working directory of volume D:
\myPath
is relative to the current working volume (could be C:, D: etc.)
myPath
is relative to the current working volume and directory
It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\
. But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.
So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The ~s
modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 - 6, and partially addresses issue 7. The ~s
modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the ~s
modifier will not append the \
to the path, nor will it convert the path into a valid 8.3 format.
The problem with ~s
is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with <letter>:<separator>
but not <letter>:<separator><separator>
, where <separator> is either \
or /
. UNC paths are always fully qualified and must start with \\
. When comparing fully qualified paths we use the ~s
modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.
There are some additional issues that complicate this problem:
9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like
C:\THIS & THAT;"C:\& THE OTHER THING"
is perfectly valid, but it cannot be expanded safely using simple expansion because both "%PATH%"
and %PATH%
will fail.
10) The path delimiter is also valid within a path name
A ;
is used to delimit paths within PATH, but ;
can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.
jeb solved both issues 9 and 10 at 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell
So we can combine the ~s
modifier and path classification techniques along with my variation of jeb's PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.
@echo off
:inPath pathVar
::
:: Tests if the path stored within variable pathVar exists within PATH.
::
:: The result is returned as the ERRORLEVEL:
:: 0 if the pathVar path is found in PATH.
:: 1 if the pathVar path is not found in PATH.
:: 2 if pathVar is missing or undefined or if PATH is undefined.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings don't have
:: to match exactly, they just need to be logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then do
:: proper comparison with pathVar.
:: Exit with ERRORLEVEL 0 if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" endlocal
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i "%%~A"=="%%~C" exit /b 0)
)
)
:: No match was found so exit with ERRORLEVEL 1
exit /b 1
The function can be used like so (assuming the batch file is named inPath.bat):
set test=c:\mypath
call inPath test && (echo found) || (echo not found)
Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn't there. This is normally done simply by using something like
path %path%;%newPath%
. But Issue 9 demonstrates how this is not reliable.
Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped !
will corrupt the value if delayed expansion is enabled.
These problems are resolved using an amazing safe return technique that jeb invented here: http://www.dostips.com/forum/viewtopic.php?p=6930#p6930
@echo off
:addPath pathVar /B
::
:: Safely appends the path contained within variable pathVar to the end
:: of PATH if and only if the path does not already exist within PATH.
::
:: If the case insensitive /B option is specified, then the path is
:: inserted into the front (Beginning) of PATH instead.
::
:: If the pathVar path is fully qualified, then it is logically compared
:: to each fully qualified path within PATH. The path strings are
:: considered a match if they are logically equivalent.
::
:: If the pathVar path is relative, then it is strictly compared to each
:: relative path within PATH. Case differences and double quotes are
:: ignored, but otherwise the path strings must match exactly.
::
:: Before appending the pathVar path, all double quotes are stripped, and
:: then the path is enclosed in double quotes if and only if the path
:: contains at least one semicolon.
::
:: addPath aborts with ERRORLEVEL 2 if pathVar is missing or undefined
:: or if PATH is undefined.
::
::------------------------------------------------------------------------
::
:: Error checking
if "%~1"=="" exit /b 2
if not defined %~1 exit /b 2
if not defined path exit /b 2
::
:: Determine if function was called while delayed expansion was enabled
setlocal
set "NotDelayed=!"
::
:: Prepare to safely parse PATH into individual paths
setlocal DisableDelayedExpansion
set "var=%path:"=""%"
set "var=%var:^=^^%"
set "var=%var:&=^&%"
set "var=%var:|=^|%"
set "var=%var:<=^<%"
set "var=%var:>=^>%"
set "var=%var:;=^;^;%"
set var=%var:""="%
set "var=%var:"=""Q%"
set "var=%var:;;="S"S%"
set "var=%var:^;^;=;%"
set "var=%var:""="%"
setlocal EnableDelayedExpansion
set "var=!var:"Q=!"
set "var=!var:"S"S=";"!"
::
:: Remove quotes from pathVar and abort if it becomes empty
set "new=!%~1:"^=!"
if not defined new exit /b 2
::
:: Determine if pathVar is fully qualified
echo("!new!"|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& set "abs=1" || set "abs=0"
::
:: For each path in PATH, check if path is fully qualified and then
:: do proper comparison with pathVar. Exit if a match is found.
:: Delayed expansion must be disabled when expanding FOR variables
:: just in case the value contains !
for %%A in ("!new!\") do for %%B in ("!var!") do (
if "!!"=="" setlocal disableDelayedExpansion
for %%C in ("%%~B\") do (
echo(%%B|findstr /i /r /c:^"^^\"[a-zA-Z]:[\\/][^\\/]" ^
/c:^"^^\"[\\][\\]" >nul ^
&& (if %abs%==1 if /i "%%~sA"=="%%~sC" exit /b 0) ^
|| (if %abs%==0 if /i %%A==%%C exit /b 0)
)
)
::
:: Build the modified PATH, enclosing the added path in quotes
:: only if it contains ;
setlocal enableDelayedExpansion
if "!new:;=!" neq "!new!" set new="!new!"
if /i "%~2"=="/B" (set "rtn=!new!;!path!") else set "rtn=!path!;!new!"
::
:: rtn now contains the modified PATH. We need to safely pass the
:: value accross the ENDLOCAL barrier
::
:: Make rtn safe for assignment using normal expansion by replacing
:: % and " with not yet defined FOR variables
set "rtn=!rtn:%%=%%A!"
set "rtn=!rtn:"=%%B!"
::
:: Escape ^ and ! if function was called while delayed expansion was enabled.
:: The trailing ! in the second assignment is critical and must not be removed.
if not defined NotDelayed set "rtn=!rtn:^=^^^^!"
if not defined NotDelayed set "rtn=%rtn:!=^^^!%" !
::
:: Pass the rtn value accross the ENDLOCAL barrier using FOR variables to
:: restore the % and " characters. Again the trailing ! is critical.
for /f "usebackq tokens=1,2" %%A in ('%%^ ^"') do (
endlocal & endlocal & endlocal & endlocal & endlocal
set "path=%rtn%" !
)
exit /b 0
T-SQL get SELECTed value of stored procedure
There is also a combination, you can use a return value with a recordset:
--Stored Procedure--
CREATE PROCEDURE [TestProc]
AS
BEGIN
DECLARE @Temp TABLE
(
[Name] VARCHAR(50)
)
INSERT INTO @Temp VALUES ('Mark')
INSERT INTO @Temp VALUES ('John')
INSERT INTO @Temp VALUES ('Jane')
INSERT INTO @Temp VALUES ('Mary')
-- Get recordset
SELECT * FROM @Temp
DECLARE @ReturnValue INT
SELECT @ReturnValue = COUNT([Name]) FROM @Temp
-- Return count
RETURN @ReturnValue
END
--Calling Code--
DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc]
SELECT @SelectedValue
--Results--
What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors
I had the similar issue. It happened every time when I run a pack of database (Spring JDBC) tests with SpringJUnit4ClassRunner
, so I resolved the issue putting @DirtiesContext
annotation for each test in order to cleanup the application context and release all resources thus each test could run with a new initalization of the application context.
How to atomically delete keys matching a pattern using Redis
Execute in bash:
redis-cli KEYS "prefix:*" | xargs redis-cli DEL
UPDATE
Ok, i understood. What about this way: store current additional incremental prefix and add it to all your keys. For example:
You have values like this:
prefix_prefix_actuall = 2
prefix:2:1 = 4
prefix:2:2 = 10
When you need to purge data, you change prefix_actuall first (for example set prefix_prefix_actuall = 3), so your application will write new data to keys prefix:3:1 and prefix:3:2. Then you can safely take old values from prefix:2:1 and prefix:2:2 and purge old keys.
SQL JOIN vs IN performance?
Generally speaking, IN
and JOIN
are different queries that can yield different results.
SELECT a.*
FROM a
JOIN b
ON a.col = b.col
is not the same as
SELECT a.*
FROM a
WHERE col IN
(
SELECT col
FROM b
)
, unless b.col
is unique.
However, this is the synonym for the first query:
SELECT a.*
FROM a
JOIN (
SELECT DISTINCT col
FROM b
)
ON b.col = a.col
If the joining column is UNIQUE
and marked as such, both these queries yield the same plan in SQL Server
.
If it's not, then IN
is faster than JOIN
on DISTINCT
.
See this article in my blog for performance details:
Spring Boot Rest Controller how to return different HTTP status codes?
There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC
NOTE
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.
Support for ES6 in Internet Explorer 11
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
How to get the caret column (not pixels) position in a textarea, in characters, from the start?
If you don't have to support IE, you can use selectionStart
and selectionEnd
attributes of textarea
.
To get caret position just use selectionStart
:
function getCaretPosition(textarea) {
return textarea.selectionStart
}
To get the strings surrounding the selection, use following code:
function getSurroundingSelection(textarea) {
return [textarea.value.substring(0, textarea.selectionStart)
,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]
}
Demo on JSFiddle.
See also HTMLTextAreaElement docs.
size of struct in C
Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.
jQuery: how to change title of document during .ready()?
Like this:
$(document).ready(function ()
{
document.title = "Hello World!";
});
Be sure to set a default-title if you want your site to be properly indexed by search-engines.
A little tip:
$(function ()
{
// this is a shorthand for the whole document-ready thing
// In my opinion, it's more readable
});
How to read json file into java with simple JSON library
package com.json;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadJSONFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));
JSONArray array = (JSONArray) obj;
JSONObject jsonObject = (JSONObject) array.get(0);
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
What is parsing in terms that a new programmer would understand?
I'd explain parsing as the process of turning some kind of data into another kind of data.
In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.
For example, turning
":Nick!User@Host PRIVMSG #channel :Hello!"
into (C)
struct irc_line {
char *nick;
char *user;
char *host;
char *command;
char **arguments;
char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }
Converting ArrayList to Array in java
public T[] toArray(T[] a) - In this method we create a array with size of arraylist and pass it as argument and it will return array of element of arraylist
String[] arr = new String[list.size()];
arr = list.toArray(arr);
Equivalent of jQuery .hide() to set visibility: hidden
An even simpler way to do this is to use jQuery's toggleClass() method
CSS
.newClass{visibility: hidden}
HTML
<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>
JS
$(document).ready(function(){
$(".trigger").click(function(){
$(".hidden_element").toggleClass("newClass");
});
});
How to find list of possible words from a letter matrix [Boggle Solver]
A Node.JS JavaScript solution. Computes all 100 unique words in less than a second which includes reading dictionary file (MBA 2012).
Output:
["FAM","TUX","TUB","FAE","ELI","ELM","ELB","TWA","TWA","SAW","AMI","SWA","SWA","AME","SEA","SEW","AES","AWL","AWE","SEA","AWA","MIX","MIL","AST","ASE","MAX","MAE","MAW","MEW","AWE","MES","AWL","LIE","LIM","AWA","AES","BUT","BLO","WAS","WAE","WEA","LEI","LEO","LOB","LOX","WEM","OIL","OLM","WEA","WAE","WAX","WAF","MILO","EAST","WAME","TWAS","TWAE","EMIL","WEAM","OIME","AXIL","WEST","TWAE","LIMB","WASE","WAST","BLEO","STUB","BOIL","BOLE","LIME","SAWT","LIMA","MESA","MEWL","AXLE","FAME","ASEM","MILE","AMIL","SEAX","SEAM","SEMI","SWAM","AMBO","AMLI","AXILE","AMBLE","SWAMI","AWEST","AWEST","LIMAX","LIMES","LIMBU","LIMBO","EMBOX","SEMBLE","EMBOLE","WAMBLE","FAMBLE"]
Code:
var fs = require('fs')
var Node = function(value, row, col) {
this.value = value
this.row = row
this.col = col
}
var Path = function() {
this.nodes = []
}
Path.prototype.push = function(node) {
this.nodes.push(node)
return this
}
Path.prototype.contains = function(node) {
for (var i = 0, ii = this.nodes.length; i < ii; i++) {
if (this.nodes[i] === node) {
return true
}
}
return false
}
Path.prototype.clone = function() {
var path = new Path()
path.nodes = this.nodes.slice(0)
return path
}
Path.prototype.to_word = function() {
var word = ''
for (var i = 0, ii = this.nodes.length; i < ii; ++i) {
word += this.nodes[i].value
}
return word
}
var Board = function(nodes, dict) {
// Expects n x m array.
this.nodes = nodes
this.words = []
this.row_count = nodes.length
this.col_count = nodes[0].length
this.dict = dict
}
Board.from_raw = function(board, dict) {
var ROW_COUNT = board.length
, COL_COUNT = board[0].length
var nodes = []
// Replace board with Nodes
for (var i = 0, ii = ROW_COUNT; i < ii; ++i) {
nodes.push([])
for (var j = 0, jj = COL_COUNT; j < jj; ++j) {
nodes[i].push(new Node(board[i][j], i, j))
}
}
return new Board(nodes, dict)
}
Board.prototype.toString = function() {
return JSON.stringify(this.nodes)
}
Board.prototype.update_potential_words = function(dict) {
for (var i = 0, ii = this.row_count; i < ii; ++i) {
for (var j = 0, jj = this.col_count; j < jj; ++j) {
var node = this.nodes[i][j]
, path = new Path()
path.push(node)
this.dfs_search(path)
}
}
}
Board.prototype.on_board = function(row, col) {
return 0 <= row && row < this.row_count && 0 <= col && col < this.col_count
}
Board.prototype.get_unsearched_neighbours = function(path) {
var last_node = path.nodes[path.nodes.length - 1]
var offsets = [
[-1, -1], [-1, 0], [-1, +1]
, [ 0, -1], [ 0, +1]
, [+1, -1], [+1, 0], [+1, +1]
]
var neighbours = []
for (var i = 0, ii = offsets.length; i < ii; ++i) {
var offset = offsets[i]
if (this.on_board(last_node.row + offset[0], last_node.col + offset[1])) {
var potential_node = this.nodes[last_node.row + offset[0]][last_node.col + offset[1]]
if (!path.contains(potential_node)) {
// Create a new path if on board and we haven't visited this node yet.
neighbours.push(potential_node)
}
}
}
return neighbours
}
Board.prototype.dfs_search = function(path) {
var path_word = path.to_word()
if (this.dict.contains_exact(path_word) && path_word.length >= 3) {
this.words.push(path_word)
}
var neighbours = this.get_unsearched_neighbours(path)
for (var i = 0, ii = neighbours.length; i < ii; ++i) {
var neighbour = neighbours[i]
var new_path = path.clone()
new_path.push(neighbour)
if (this.dict.contains_prefix(new_path.to_word())) {
this.dfs_search(new_path)
}
}
}
var Dict = function() {
this.dict_array = []
var dict_data = fs.readFileSync('./web2', 'utf8')
var dict_array = dict_data.split('\n')
for (var i = 0, ii = dict_array.length; i < ii; ++i) {
dict_array[i] = dict_array[i].toUpperCase()
}
this.dict_array = dict_array.sort()
}
Dict.prototype.contains_prefix = function(prefix) {
// Binary search
return this.search_prefix(prefix, 0, this.dict_array.length)
}
Dict.prototype.contains_exact = function(exact) {
// Binary search
return this.search_exact(exact, 0, this.dict_array.length)
}
Dict.prototype.search_prefix = function(prefix, start, end) {
if (start >= end) {
// If no more place to search, return no matter what.
return this.dict_array[start].indexOf(prefix) > -1
}
var middle = Math.floor((start + end)/2)
if (this.dict_array[middle].indexOf(prefix) > -1) {
// If we prefix exists, return true.
return true
} else {
// Recurse
if (prefix <= this.dict_array[middle]) {
return this.search_prefix(prefix, start, middle - 1)
} else {
return this.search_prefix(prefix, middle + 1, end)
}
}
}
Dict.prototype.search_exact = function(exact, start, end) {
if (start >= end) {
// If no more place to search, return no matter what.
return this.dict_array[start] === exact
}
var middle = Math.floor((start + end)/2)
if (this.dict_array[middle] === exact) {
// If we prefix exists, return true.
return true
} else {
// Recurse
if (exact <= this.dict_array[middle]) {
return this.search_exact(exact, start, middle - 1)
} else {
return this.search_exact(exact, middle + 1, end)
}
}
}
var board = [
['F', 'X', 'I', 'E']
, ['A', 'M', 'L', 'O']
, ['E', 'W', 'B', 'X']
, ['A', 'S', 'T', 'U']
]
var dict = new Dict()
var b = Board.from_raw(board, dict)
b.update_potential_words()
console.log(JSON.stringify(b.words.sort(function(a, b) {
return a.length - b.length
})))
Displaying standard DataTables in MVC
While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.
Get your Dataset into a List .....
I have a repository pattern and here is an example of getting a dataset from an old school asmx web service
private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;
public Get_Client_Repository()
: this(new CISOnlineSRVDEV.ServiceSoapClient())
{
}
public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
{
_ServiceSoapClient = serviceSoapClient;
}
public IEnumerable<IClient> GetClient(IClient client)
{
// **** Calling teh web service with passing in the clientId and returning a dataset
DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
client.ClientId,
client.AhcccsId,
client.LastName,
client.FirstName,
"");//client.BirthDate.ToString()); //TODO: NEED TO FIX
// USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
select new Client()
{
RbhaId = c[5].ToString(),
ClientId = c[2].ToString(),
AhcccsId = c[6].ToString(),
LastName = c[0].ToString(), // Add another field called Sex M/F c[4]
FirstName = c[1].ToString(),
BirthDate = c[3].ToDateTime() //extension helper ToDateTime()
}).ToList<IClient>();
return clients;
}
Then in the Controller I'm doing this
IClient client = (IClient)TempData["Client"];
// Instantiate and instance of the repository
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);
// Call the View up passing in the data from the list
return View(model);
Then in the View it is easy :
@model IEnumerable<CISOnlineMVC.DAL.IClient>
@{
ViewBag.Title = "CLIENT ALL INFORMATION";
}
<h2>CLIENT ALL INFORMATION</h2>
<table>
<tr>
<th></th>
<th>Last Name</th>
<th>First Name</th>
<th>Client ID</th>
<th>DOB</th>
<th>Gender</th>
<th>RBHA ID</th>
<th>AHCCCS ID</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
</td>
<td>
@item.LastName
</td>
<td>
@item.FirstName
</td>
<td>
@item.ClientId
</td>
<td>
@item.BirthDate
</td>
<td>
Gender @* ADD in*@
</td>
<td>
@item.RbhaId
</td>
<td>
@item.AhcccsId
</td>
</tr>
}
</table>
How can you run a Java program without main method?
Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The System.exit(0)
lets the program exit before the JVM is looking for the main
method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main
In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args).
Here an alternative is to write your own launcher, this way you can define entry points as you want.
In the article JVM Launcher you will find the necessary information to get started:
This article explains how can we create a Java Virtual Machine
Launcher (like java.exe or javaw.exe). It explores how the Java
Virtual Machine launches a Java application. It gives you more ideas
on the JDK or JRE you are using. This launcher is very useful in
Cygwin (Linux emulator) with Java Native Interface. This article
assumes a basic understanding of JNI.
Using jQuery's ajax method to retrieve images as a blob
If you need to handle error messages using jQuery.AJAX you will need to modify the xhr
function so the responseType
is not being modified when an error happens.
So you will have to modify the responseType
to "blob" only if it is a successful call:
$.ajax({
...
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if (xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
...
error: function(xhr, textStatus, errorThrown) {
// Here you are able now to access to the property "responseText"
// as you have the type set to "text" instead of "blob".
console.error(xhr.responseText);
},
success: function(data) {
console.log(data); // Here is "blob" type
}
});
Note
If you debug and place a breakpoint at the point right after setting the xhr.responseType
to "blob" you can note that if you try to get the value for responseText
you will get the following message:
The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
What is Type-safe?
Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.
In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).
PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).
C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.
Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).
initialize a numpy array
To initialize a numpy array with a specific matrix:
import numpy as np
mat = np.array([[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[1, 0, 1, 0, 1]])
print mat.shape
print mat
output:
(5, 5)
[[1 1 0 0 0]
[0 1 0 0 1]
[1 0 0 1 1]
[0 0 0 0 0]
[1 0 1 0 1]]
Run jar file with command line arguments
For the question
How can i run a jar file in command prompt but with arguments
.
To pass arguments to the jar file at the time of execution
java -jar myjar.jar arg1 arg2
In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:
String arg1 = args[0];
String arg2 = args[1];
Memory address of variables in Java
That is the class name and System.identityHashCode() separated by the '@' character. What the identity hash code represents is implementation-specific. It often is the initial memory address of the object, but the object can be moved in memory by the VM over time. So (briefly) you can't rely on it being anything.
Getting the memory addresses of variables is meaningless within Java, since the JVM is at liberty to implement objects and move them as it seems fit (your objects may/will move around during garbage collection etc.)
Integer.toBinaryString() will give you an integer in binary form.
com.apple.WebKit.WebContent drops 113 error: Could not find specified service
Mine was different again. I was setting the user-agent like so:
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
This was causing something on the web page to freak out and leak memory. Not sure why but removing this sorted the issue for me.
How do you declare an interface in C++?
To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.
class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Parent
{
public:
virtual ~Parent();
};
class Child : public Parent, public IDemo
{
public:
virtual void OverrideMe()
{
//do stuff
}
};
You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.
Get json value from response
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
How to initialize List<String> object in Java?
List is an Interface, you cannot instantiate an Interface, because interface is a convention, what methods should have your classes. In order to instantiate, you need some realizations(implementations) of that interface. Try the below code with very popular implementations of List interface:
List<String> supplierNames = new ArrayList<String>();
or
List<String> supplierNames = new LinkedList<String>();
Issue with Task Scheduler launching a task
I was having the same issue. I tried with the compatibility option, but in Windows 10 it doesn't show the compatibility option. The following steps solved the problem for me:
- I made sure the account with which the task was running had the full access privileges on the file to be executed.
(Executed the task and was still not running)
- I man
taskschd.msc
as administrator
- I added the account to run the task (whether was it logged or not)
- I executed the task and now IT WORKED!
So somehow setting up the task in taskschd.msc
as a regular user wasn't working, even though my account is an admin one.
Hope this helps anyone having the same issue
Why XML-Serializable class need a parameterless constructor
This is a limitation of XmlSerializer
. Note that BinaryFormatter
and DataContractSerializer
do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.
Since you are using xml, you might consider using DataContractSerializer
and marking your class with [DataContract]
/[DataMember
], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute]
- everything becomes elements).
Update: if you really want to know, BinaryFormatter
et al use FormatterServices.GetUninitializedObject()
to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:
Because the new instance of the object
is initialized to zero and no
constructors are run, the object might
not represent a state that is regarded
as valid by that object. The current
method should only be used for
deserialization when the user intends
to immediately populate all fields. It
does not create an uninitialized
string, since creating an empty
instance of an immutable type serves
no purpose.
I have my own serialization engine, but I don't intend making it use FormatterServices
; I quite like knowing that a constructor (any constructor) has actually executed.
Can anonymous class implement interface?
The best solution is just not to use anonymous classes.
public class Test
{
class DummyInterfaceImplementor : IDummyInterface
{
public string A { get; set; }
public string B { get; set; }
}
public void WillThisWork()
{
var source = new DummySource[0];
var values = from value in source
select new DummyInterfaceImplementor()
{
A = value.A,
B = value.C + "_" + value.D
};
DoSomethingWithDummyInterface(values.Cast<IDummyInterface>());
}
public void DoSomethingWithDummyInterface(IEnumerable<IDummyInterface> values)
{
foreach (var value in values)
{
Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
}
}
}
Note that you need to cast the result of the query to the type of the interface. There might be a better way to do it, but I couldn't find it.
How do I extract part of a string in t-sql
declare @data as varchar(50)
set @data='ciao335'
--get text
Select Left(@Data, PatIndex('%[0-9]%', @Data + '1') - 1) ---->>ciao
--get numeric
Select right(@Data, len(@data) - (PatIndex('%[0-9]%', @Data )-1) ) ---->>335
What's the best way to calculate the size of a directory in .NET?
This .NET core command line app here calculates directory sizes for a given path:
https://github.com/garethrbrown/folder-size
The key method is this one which recursively inspects sub-directories to come up with a total size.
private static long DirectorySize(SortDirection sortDirection, DirectoryInfo directoryInfo, DirectoryData directoryData)
{
long directorySizeBytes = 0;
// Add file sizes for current directory
FileInfo[] fileInfos = directoryInfo.GetFiles();
foreach (FileInfo fileInfo in fileInfos)
{
directorySizeBytes += fileInfo.Length;
}
directoryData.Name = directoryInfo.Name;
directoryData.SizeBytes += directorySizeBytes;
// Recursively add subdirectory sizes
DirectoryInfo[] subDirectories = directoryInfo.GetDirectories();
foreach (DirectoryInfo di in subDirectories)
{
var subDirectoryData = new DirectoryData(sortDirection);
directoryData.DirectoryDatas.Add(subDirectoryData);
directorySizeBytes += DirectorySize(sortDirection, di, subDirectoryData);
}
directoryData.SizeBytes = directorySizeBytes;
return directorySizeBytes;
}
}
Calculate AUC in R?
Without any additional packages:
true_Y = c(1,1,1,1,2,1,2,1,2,2)
probs = c(1,0.999,0.999,0.973,0.568,0.421,0.382,0.377,0.146,0.11)
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 2)/sum(roc_y == 2)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
aList = getROC_AUC(probs, true_Y)
stack_x = unlist(aList$stack_x)
stack_y = unlist(aList$stack_y)
auc = unlist(aList$auc)
plot(stack_x, stack_y, type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
axis(1, seq(0.0,1.0,0.1))
axis(2, seq(0.0,1.0,0.1))
abline(h=seq(0.0,1.0,0.1), v=seq(0.0,1.0,0.1), col="gray", lty=3)
legend(0.7, 0.3, sprintf("%3.3f",auc), lty=c(1,1), lwd=c(2.5,2.5), col="blue", title = "AUC")
UICollectionView cell selection and cell reuse
UICollectionView has changed in iOS 10 introducing some problems to solutions above.
Here is a good guide:
https://littlebitesofcocoa.com/241-uicollectionview-cell-pre-fetching
Cells now stay around for a bit after going off-screen. Which means that sometimes we might not be able to get hold of a cell in didDeselectItemAt indexPath
in order to adjust it. It can then show up on screen un-updated and un-recycled. prepareForReuse
does not help this corner case.
The easiest solution is disabling the new scrolling by setting isPrefetchingEnabled
to false. With this, managing the cell's display with
cellForItemAt
didSelect
didDeselect
works as it used to.
However, if you'd rather keep the new smooth scrolling behaviour it's better to use willDisplay
:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
let customCell = cell as! CustomCell
if customCell.isSelected {
customCell.select()
} else {
customCell.unselect()
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
//Don't even need to set selection-specific things here as recycled cells will also go through willDisplay
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? CustomCell
cell?.select()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? CustomCell
cell?.unselect() // <----- this can be null here, and the cell can still come back on screen!
}
With the above you control the cell when it's selected, unselected on-screen, recycled, and just re-displayed.
How to autosize a textarea using Prototype?
Here's a Prototype version of resizing a text area that is not dependent on the number of columns in the textarea. This is a superior technique because it allows you to control the text area via CSS as well as have variable width textarea. Additionally, this version displays the number of characters remaining. While not requested, it's a pretty useful feature and is easily removed if unwanted.
//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {};
Widget.Textarea = Class.create({
initialize: function(textarea, options)
{
this.textarea = $(textarea);
this.options = $H({
'min_height' : 30,
'max_length' : 400
}).update(options);
this.textarea.observe('keyup', this.refresh.bind(this));
this._shadow = new Element('div').setStyle({
lineHeight : this.textarea.getStyle('lineHeight'),
fontSize : this.textarea.getStyle('fontSize'),
fontFamily : this.textarea.getStyle('fontFamily'),
position : 'absolute',
top: '-10000px',
left: '-10000px',
width: this.textarea.getWidth() + 'px'
});
this.textarea.insert({ after: this._shadow });
this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
this.textarea.insert({after: this._remainingCharacters});
this.refresh();
},
refresh: function()
{
this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
this.textarea.setStyle({
height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
});
var remaining = this.options.get('max_length') - $F(this.textarea).length;
this._remainingCharacters.update(Math.abs(remaining) + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
}
});
Create the widget by calling new Widget.Textarea('element_id')
. The default options can be overridden by passing them as an object, e.g. new Widget.Textarea('element_id', { max_length: 600, min_height: 50})
. If you want to create it for all textareas on the page, do something like:
Event.observe(window, 'load', function() {
$$('textarea').each(function(textarea) {
new Widget.Textarea(textarea);
});
});
Sort JavaScript object by key
The one line:
Object.entries(unordered)
.sort(([keyA], [keyB]) => keyA > keyB)
.reduce((obj, [key,value]) => Object.assign(obj, {[key]: value}), {})
In Bootstrap 3,How to change the distance between rows in vertical?
There's a simply way of doing it.
You define for all the rows, except the first one, the following class with properties:
.not-first-row
{
position: relative;
top: -20px;
}
Then you apply the class to all non-first rows and adjust the negative top value to fit your desired row space. It's easy and works way better. :)
Hope it helped.
C++, How to determine if a Windows Process is running?
This is a solution that I've used in the past. Although the example here is in VB.net - I've used this technique with c and c++. It bypasses all the issues with Process IDs & Process handles, and return codes. Windows is very faithful in releasing the mutex no matter how Process2 is terminated. I hope it is helpful to someone...
**PROCESS1 :-**
Randomize()
mutexname = "myprocess" & Mid(Format(CDbl(Long.MaxValue) * Rnd(), "00000000000000000000"), 1, 16)
hnd = CreateMutex(0, False, mutexname)
' pass this name to Process2
File.WriteAllText("mutexname.txt", mutexname)
<start Process2>
<wait for Process2 to start>
pr = WaitForSingleObject(hnd, 0)
ReleaseMutex(hnd)
If pr = WAIT_OBJECT_0 Then
<Process2 not running>
Else
<Process2 is running>
End If
...
CloseHandle(hnd)
EXIT
**PROCESS2 :-**
mutexname = File.ReadAllText("mutexname.txt")
hnd = OpenMutex(MUTEX_ALL_ACCESS Or SYNCHRONIZE, True, mutexname)
...
ReleaseMutex(hnd)
CloseHandle(hnd)
EXIT
get name of a variable or parameter
Alternatively,
1) Without touching System.Reflection
namespace,
GETNAME(new { myInput });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}
2) The below one can be faster though (from my tests)
GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
You can also extend this for properties of objects (may be with extension methods):
new { myClass.MyProperty1 }.GETNAME();
You can cache property values to improve performance further as property names don't change during runtime.
The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine
Passing data between controllers in Angular JS?
1
using $localStorage
app.controller('ProductController', function($scope, $localStorage) {
$scope.setSelectedProduct = function(selectedObj){
$localStorage.selectedObj= selectedObj;
};
});
app.controller('CartController', function($scope,$localStorage) {
$scope.selectedProducts = $localStorage.selectedObj;
$localStorage.$reset();//to remove
});
2
On click you can call method that invokes broadcast:
$rootScope.$broadcast('SOME_TAG', 'your value');
and the second controller will listen on this tag like:
$scope.$on('SOME_TAG', function(response) {
// ....
})
3
using $rootScope:
4
window.sessionStorage.setItem("Mydata",data);
$scope.data = $window.sessionStorage.getItem("Mydata");
5
One way using angular service:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
ggplot geom_text font size control
Here are a few options for changing text / label sizes
library(ggplot2)
# Example data using mtcars
a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=20)
The size
in the geom_text
changes the size of the geom_text
labels.
p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels
p <- p + theme(axis.title = element_text(size = 25)) # change axis titles
p <- p + theme(text = element_text(size = 10)) # this will change all text size
# (except geom_text)
For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?
Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text
sizes to theme
sizes.
So a horrible fix for uniform sizes is to scale by this ratio
geom.text.size = 7
theme.size = (14/5) * geom.text.size
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) +
geom_bar(stat="identity",position="dodge") +
geom_text(data = a, aes(label = mpg),
position = position_dodge(width=0.9), size=geom.text.size) +
theme(axis.text = element_text(size = theme.size, colour="black"))
This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)
linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04
The current answer is incomplete. Installing libv4l-dev
creates a /usr/include/linux/videodev2.h
but doesn't solve the stated problem of not being able to find linux/videodev.h
. The library does ship header files for compatibility, but fails to put them where applications will look for them.
sudo apt-get install libv4l-dev
cd /usr/include/linux
sudo ln -s ../libv4l1-videodev.h videodev.h
This provides a linux/videodev.h
, and of the right version (1).
SQL Server: Null VS Empty String
How are the "NULL" and "empty varchar" values stored in SQL Server.
Why would you want to know that? Or in other words, if you knew the answer, how would you use that information?
And in case I have no user entry for a string field on my UI, should I store a NULL or a ''?
It depends on the nature of your field. Ask yourself whether the empty string is a valid value for your field.
If it is (for example, house name in an address) then that might be what you want to store (depending on whether or not you know that the address has no house name).
If it's not (for example, a person's name), then you should store a null, because people don't have blank names (in any culture, so far as I know).
How to read a PEM RSA private key from .NET
Check http://msdn.microsoft.com/en-us/library/dd203099.aspx
under Cryptography Application Block.
Don't know if you will get your answer, but it's worth a try.
Edit after Comment.
Ok then check this code.
using System.Security.Cryptography;
public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) {
X509Certificate2 myCertificate;
try{
myCertificate = new X509Certificate2(PathToPrivateKeyFile);
} catch{
throw new CryptographicException("Unable to open key file.");
}
RSACryptoServiceProvider rsaObj;
if(myCertificate.HasPrivateKey) {
rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey;
} else
throw new CryptographicException("Private key not contained within certificate.");
if(rsaObj == null)
return String.Empty;
byte[] decryptedBytes;
try{
decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false);
} catch {
throw new CryptographicException("Unable to decrypt data.");
}
// Check to make sure we decrpyted the string
if(decryptedBytes.Length == 0)
return String.Empty;
else
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
Case in Select Statement
you can also use:
SELECT CASE
WHEN upper(t.name) like 'P%' THEN
'productive'
WHEN upper(t.name) like 'T%' THEN
'test'
WHEN upper(t.name) like 'D%' THEN
'development'
ELSE
'unknown'
END as type
FROM table t
Is an HTTPS query string secure?
I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.
The HTTP 1.1 RFC explicitly states:
Clients SHOULD NOT include a Referer
header field in a (non-secure) HTTP
request if the referring page was
transferred with a secure protocol.
Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.
Ignore files that have already been committed to a Git repository
Thanks to your answer, I was able to write this little one-liner to improve it. I ran it on my .gitignore and repo, and had no issues, but if anybody sees any glaring problems, please comment. This should git rm -r --cached
from .gitignore
:
cat $(git rev-parse --show-toplevel)/.gitIgnore | sed "s/\/$//" | grep -v "^#" | xargs -L 1 -I {} find $(git rev-parse --show-toplevel) -name "{}" | xargs -L 1 git rm -r --cached
Note that you'll get a lot of fatal: pathspec '<pathspec>' did not match any files
. That's just for the files which haven't been modified.
What is the difference between max-device-width and max-width for mobile web?
What do you think about using this style?
For all breakpoints which are mostly for "mobile device" I use min(max)-device-width
and for breakpoints which are mostly for "desktop" use min(max)-width
.
There are a lot of "mobile devices" that badly calculate width.
Look at http://www.javascriptkit.com/dhtmltutors/cssmediaqueries2.shtml:
/* #### Mobile Phones Portrait #### */
@media screen and (max-device-width: 480px) and (orientation: portrait){
/* some CSS here */
}
/* #### Mobile Phones Landscape #### */
@media screen and (max-device-width: 640px) and (orientation: landscape){
/* some CSS here */
}
/* #### Mobile Phones Portrait or Landscape #### */
@media screen and (max-device-width: 640px){
/* some CSS here */
}
/* #### iPhone 4+ Portrait or Landscape #### */
@media screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2){
/* some CSS here */
}
/* #### Tablets Portrait or Landscape #### */
@media screen and (min-device-width: 768px) and (max-device-width: 1024px){
/* some CSS here */
}
/* #### Desktops #### */
@media screen and (min-width: 1024px){
/* some CSS here */
}
UICollectionView spacing margins
To put space between CollectionItem
s use this
write this two Line in viewdidload
UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
collectionViewLayout.sectionInset = UIEdgeInsetsMake(<CGFloat top>, <CGFloat left>, <CGFloat bottom>, <CGFloat right>)
What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?
This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip
.
For example if a compressed pickle archive is made like this,
import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
pickle.dump([1,2,3], ofp)
Trying to open it throws the errors
with open('test.pklz', 'rb') as ifp:
print(pickle.load(ifp))
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.
But, if the pickle file is opened using gzip
all is harmonious
with gzip.open('test.pklz', 'rb') as ifp:
print(pickle.load(ifp))
[1, 2, 3]
Tracking Google Analytics Page Views with AngularJS
For those of you using AngularUI Router instead of ngRoute can use the following code to track page views.
app.run(function ($rootScope) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
ga('set', 'page', toState.url);
ga('send', 'pageview');
});
});
How to create circular ProgressBar in android?
It's easy to create this yourself
In your layout include the following ProgressBar
with a specific drawable (note you should get the width from dimensions instead). The max value is important here:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="500"
android:progress="0"
android:progressDrawable="@drawable/circular" />
Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius
instead of innerRadiusRatio
) and thickness values.
circular (Pre Lollipop OR API Level < 21)
<shape
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
circular ( >= Lollipop OR API Level >= 21)
<shape
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
useLevel is "false" by default in API Level 21 (Lollipop) .
Start Animation
Next in your code use an ObjectAnimator
to animate the progress field of the ProgessBar
of your layout.
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
Stop Animation
progressBar.clearAnimation();
P.S. unlike examples above, it give smooth animation.
Copying files to a container with Docker Compose
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
How to remove the left part of a string?
The simplest way I can think of is with slicing:
def find_path(i_file):
lines = open(i_file).readlines()
for line in lines:
if line.startswith("Path=") :
return line[5:]
A quick note on slice notation, it uses two indices instead of the usual one. The first index indicates the first element of the sequence you want to include in the slice and the last index is the index immediately after the last element you wish to include in the slice.
Eg:
sequence_obj[first_index:last_index]
The slice consists of all the elements between first_index
and last_index
, including first_index
and not last_index
. If the first index is omitted, it defaults to the start of the sequence. If the last index is omitted, it includes all elements up to the last element in the sequence. Negative indices are also allowed. Use Google to learn more about the topic.
Why does the html input with type "number" allow the letter 'e' to be entered in the field?
Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e
or E
character (where the exponent is the number after the e
or E
):
A floating-point number consists of the following parts, in exactly
the following order:
- Optionally, the first character may be a "
-
" character.
- One or more characters in the range "
0—9
".
- Optionally, the following parts, in exactly the following order:
- a "
.
" character
- one or more characters in the range "
0—9
"
- Optionally, the following parts, in exactly the following order:
- a "
e
" character or "E
" character
- optionally, a "
-
" character or "+
" character
- One or more characters in the range "
0—9
".
Key hash for Android-Facebook app
Here are the steps-
Download openssl from Google code (If you have a 64 bit machine you must download openssl-0.9.8e X64 not the latest version)
Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.
detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.
detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-
$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary
|"C:\OpenSSL\bin\openssl" base64
- it will ask for password, put android
- that's all. u will get a key-hash
For more info visit here
Selenium IDE - Command to wait for 5 seconds
This will do what you are looking for in C# (WebDriver/Selenium 2.0)
var browser = new FirefoxDriver();
var overallTimeout = Timespan.FromSeconds(10);
var sleepCycle = TimeSpan.FromMiliseconds(50);
var wait = new WebDriverWait(new SystemClock(), browser, overallTimeout, sleepCycle);
var hasTimedOut = wait.Until(_ => /* here goes code that looks for the map */);
And never use Thread.Sleep because it makes your tests unreliable
Firing a Keyboard Event in Safari, using JavaScript
The Mozilla Developer Network provides the following explanation:
- Create an event using
event = document.createEvent("KeyboardEvent")
- Init the keyevent
using:
event.initKeyEvent (type, bubbles, cancelable, viewArg,
ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg,
keyCodeArg, charCodeArg)
- Dispatch the event using
yourElement.dispatchEvent(event)
I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...
Invert "if" statement to reduce nesting
As others have mentioned, there shouldn't be a performance hit, but there are other considerations. Aside from those valid concerns, this also can open you up to gotchas in some circumstances. Suppose you were dealing with a double
instead:
public void myfunction(double exampleParam){
if(exampleParam > 0){
//Body will *not* be executed if Double.IsNan(exampleParam)
}
}
Contrast that with the seemingly equivalent inversion:
public void myfunction(double exampleParam){
if(exampleParam <= 0)
return;
//Body *will* be executed if Double.IsNan(exampleParam)
}
So in certain circumstances what appears to be a a correctly inverted if
might not be.
How to create <input type=“text”/> dynamically
Try this:
_x000D_
_x000D_
function generateInputs(form, input) {
x = input.value;
for (y = 0; x > y; y++) {
var element = document.createElement('input');
element.type = "text";
element.placeholder = "New Input";
form.appendChild(element);
}
}
_x000D_
input {
padding: 10px;
margin: 10px;
}
_x000D_
<div id="input-form">
<input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)" required><br>
</div>
_x000D_
_x000D_
_x000D_
The code above, has a form with an input which accepts a number in it:
<form id="input-form">
<input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)"><br>
</form>
The input runs a function onchange
, meaning that when the user has entered a number and clicked submit, it run a function. The user is required to fill out the input with a value before submitting. This value must be numerical. Once submitted the parent form and the input are passed to the function:
...
generateInputs(document.getElementById('input-form'), this)
...
The generate then loops according to the given value inside the input:
...
x = input.value;
for (y=0; x>y; y++) {
...
Then it generates an input inside the form, on each loop:
...
var element = document.createElement('input');
element.type = "text";
element.placeholder = "New Input";
form.appendChild(element);
...
I have also added in a few CSS
stylings to make the inputs
look nice, and some placeholders
as well.
To read more about creating elements createElement()
:
https://www.w3schools.com/jsref/met_document_createelement.asp
To read more about for
loops:
https://www.w3schools.com/js/js_loop_for.asp
Python using enumerate inside list comprehension
Or, if you don't insist on using a list comprehension:
>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
#if DEBUG vs. Conditional("DEBUG")
I'm sure plenty will disagree with me, but having spent time as a build guy constantly hearing "But it works on my machine!", I take the standpoint that you should pretty much never use either. If you really need something for testing and debugging, figure out a way to make that testability seperate from the actual production code.
Abstract the scenarios with mocking in unit tests, make one off versions of things for one off scenarios you want to test, but don't put tests for debug into the code for binaries which you test and write for production release. These debug tests just hide possible bugs from devs so they aren't found until later in the process.
How to place a JButton at a desired location in a JFrame using Java
Following line should be called before you add your component
pnlButton.setLayout(null);
Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds
method.
In general I wouldn't recommend using absolute layout.
jQuery addClass onClick
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick
handlers.