If min value in array, you can try like:
>>> mydict = {"a": -1.5, "b": -1000.44, "c": -3}
>>> min(mydict.values())
-1000.44
I've taken Irritate's answer and refactored it so as to minimize the computational steps for subsequent computations by factoring it into the fewest constants. The motivation is to allow a scaler to be trained on one set of data, and then be run on new data (for an ML algo). In effect, it's much like SciKit's preprocessing MinMaxScaler for Python in usage.
Thus, x' = (b-a)(x-min)/(max-min) + a
(where b!=a) becomes x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
which can be reduced to two constants in the form x' = x*Part1 + Part2
.
Here's a C# implementation with two constructors: one to train, and one to reload a trained instance (e.g., to support persistence).
public class MinMaxColumnSpec
{
/// <summary>
/// To reduce repetitive computations, the min-max formula has been refactored so that the portions that remain constant are just computed once.
/// This transforms the forumula from
/// x' = (b-a)(x-min)/(max-min) + a
/// into x' = x(b-a)/(max-min) + min(-b+a)/(max-min) + a
/// which can be further factored into
/// x' = x*Part1 + Part2
/// </summary>
public readonly double Part1, Part2;
/// <summary>
/// Use this ctor to train a new scaler.
/// </summary>
public MinMaxColumnSpec(double[] columnValues, int newMin = 0, int newMax = 1)
{
if (newMax <= newMin)
throw new ArgumentOutOfRangeException("newMax", "newMax must be greater than newMin");
var oldMax = columnValues.Max();
var oldMin = columnValues.Min();
Part1 = (newMax - newMin) / (oldMax - oldMin);
Part2 = newMin + (oldMin * (newMin - newMax) / (oldMax - oldMin));
}
/// <summary>
/// Use this ctor for previously-trained scalers with known constants.
/// </summary>
public MinMaxColumnSpec(double part1, double part2)
{
Part1 = part1;
Part2 = part2;
}
public double Scale(double x) => (x * Part1) + Part2;
}
getMaxValue(array);
// get smallest number
getMinValue(array);
You are calling the methods but not using the returned values.
System.out.println(getMaxValue(array));
System.out.println(getMinValue(array));
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Is this what you are looking for?
d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'
print d[min(d.keys())]
Prints 'fourteen'
import syslog
syslog.openlog(ident="LOG_IDENTIFIER",logoption=syslog.LOG_PID, facility=syslog.LOG_LOCAL0)
syslog.syslog('Log processing initiated...')
the above script will log to LOCAL0 facility with our custom "LOG_IDENTIFIER"... you can use LOCAL[0-7] for local purpose.
If there is no bulk insert into mongodb, we loop all objects in the small_collection
and insert them one by one into the big_collection
:
db.small_collection.find().forEach(function(obj){
db.big_collection.insert(obj)
});
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0
One solution is to define a simple recursive function:
u0 = ...
def f(x):
...
def u(n):
if n==0: return u0
return f(u(n-1))
Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.
Another solution is a simple loop:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
return ux
But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:
def u(n):
ux = u0
for i in xrange(n):
ux=f(ux)
yield ux
for val in u(1000):
print val
There are many other options, but I guess these are the main ones.
Just in addition to the above answers, for the question where and when you should call getLocationOnScreen
?
For any information that is related to the view
, will be available only after the view has been laid out(created) on the screen. So to get the location put your code inside view.post(Runnable)
which is called after view
has been laid out, like this:
view.post(new Runnable() {
@Override
public void run() {
// This code will run when view created and rendered on screen
// So as the answer to this question, you can put the code here
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
}
});
There are two kinds of cascades in Doctrine:
1) ORM level - uses cascade={"remove"}
in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.
2) Database level - uses onDelete="CASCADE"
on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:
@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")
I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.
You could also try this:
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
Then in your default function you call the functions you want:
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
Most of the aspects are covered. But there could be a requirement to find the aggregation of other data types apart from Integer, Long(for which specialized stream support is already present). For e.g. stram with BigInteger For such a type we can use reduce operation like
list.stream().reduce((bigInteger1, bigInteger2) -> bigInteger1.add(bigInteger2))
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
Try this example
CREATE PROCEDURE MyProc
BEGIN
--Stored Procedure variables
Declare @maxOr int;
Declare @maxCa int;
--Getting query result in the variable (first variant of syntax)
SET @maxOr = (SELECT MAX(orId) FROM [order]);
--Another variant of seting variable from query
SELECT @maxCa=MAX(caId) FROM [cart];
--Updating record through the variable
INSERT INTO [order_cart] (orId,caId)
VALUES(@maxOr, @maxCa);
--return values to the program as dataset
SELECT
@maxOr AS maxOr,
@maxCa AS maxCa
-- return one int value as "return value"
RETURN @maxOr
END
GO
SQL-command to call the stored procedure
EXEC MyProc
After some research I understand - I have very similar, but different root project locations and its cached in /bootstrap/cache
. After cache clearing project started.
You can try atoi() library function. Also sscanf() and sprintf() would help.
Here is a small example to show converting integer to character string:
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Here for another Example
#include <stdio.h>
int main(void)
{
char text[] = "StringX";
int digit;
for (digit = 0; digit < 10; ++digit)
{
text[6] = digit + '0';
puts(text);
}
return 0;
}
/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/
Check if there is whitespace before =
sign of excel formula
select regexp_replace(field, E'[\\n\\r]+', ' ', 'g' )
read the manual http://www.postgresql.org/docs/current/static/functions-matching.html
I think that your problem is that you are expecting np.append
to add the column in-place, but what it does, because of how numpy data is stored, is create a copy of the joined arrays
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that `append`
does not occur in-place: a new array is allocated and filled. If
`axis` is None, `out` is a flattened array.
so you need to save the output all_data = np.append(...)
:
my_data = np.random.random((210,8)) #recfromcsv('LIAB.ST.csv', delimiter='\t')
new_col = my_data.sum(1)[...,None] # None keeps (n, 1) shape
new_col.shape
#(210,1)
all_data = np.append(my_data, new_col, 1)
all_data.shape
#(210,9)
Alternative ways:
all_data = np.hstack((my_data, new_col))
#or
all_data = np.concatenate((my_data, new_col), 1)
I believe that the only difference between these three functions (as well as np.vstack
) are their default behaviors for when axis
is unspecified:
concatenate
assumes axis = 0
hstack
assumes axis = 1
unless inputs are 1d, then axis = 0
vstack
assumes axis = 0
after adding an axis if inputs are 1dappend
flattens arrayBased on your comment, and looking more closely at your example code, I now believe that what you are probably looking to do is add a field to a record array. You imported both genfromtxt
which returns a structured array and recfromcsv
which returns the subtly different record array (recarray
). You used the recfromcsv
so right now my_data
is actually a recarray
, which means that most likely my_data.shape = (210,)
since recarrays are 1d arrays of records, where each record is a tuple with the given dtype.
So you could try this:
import numpy as np
from numpy.lib.recfunctions import append_fields
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
data = np.array( list(zip(x,y,z)), dtype=[('x',float),('y',float),('z',float)])
data = np.recarray(data.shape, data.dtype, buf=data)
data.shape
#(10,)
tot = data['x'] + data['y'] + data['z'] # sum(axis=1) won't work on recarray
tot.shape
#(10,)
all_data = append_fields(data, 'total', tot, usemask=False)
all_data
#array([(0.4374783740738456 , 0.04307289878861764, 0.021176067323686598, 0.5017273401861498),
# (0.07622262416466963, 0.3962146058689695 , 0.27912715826653534 , 0.7515643883001745),
# (0.30878532523061153, 0.8553768789387086 , 0.9577415585116588 , 2.121903762680979 ),
# (0.5288343561208022 , 0.17048864443625933, 0.07915689716226904 , 0.7784798977193306),
# (0.8804269791375121 , 0.45517504750917714, 0.1601389248542675 , 1.4957409515009568),
# (0.9556552723429782 , 0.8884504475901043 , 0.6412854758843308 , 2.4853911958174133),
# (0.0227638618687922 , 0.9295332854783015 , 0.3234597575660103 , 1.275756904913104 ),
# (0.684075052174589 , 0.6654774682866273 , 0.5246593820025259 , 1.8742119024637423),
# (0.9841793718333871 , 0.5813955915551511 , 0.39577520705133684 , 1.961350170439875 ),
# (0.9889343795296571 , 0.22830104497714432, 0.20011292764078448 , 1.4173483521475858)],
# dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'), ('total', '<f8')])
all_data.shape
#(10,)
all_data.dtype.names
#('x', 'y', 'z', 'total')
Vim has three modes of operation: Input mode, Command mode & Ex mode.
Input mode - everything that you type, all keystrokes are echoed on the screen.
Command mode or Escape mode - everything that you type in this mode is interpreted as a command.
Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.
In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.
Exiting from ex mode
You need to be sure that you are in the Command mode. To do that, simply press the Esc key.
Go to the ex mode by pressing the : key
Use any of the following combinations in ex mode to exit:
:q
- quit
:q!
- quit without saving
:wq
- save & quit or write & quit
:wq!
- same as wq, but force write in case file permissions are readonly
:x
- write & quit
:qa
- quit all. useful when multiple files are opened like: vim abc.txt xyz.txt
Exiting from command mode
Press the escape key. You probably have done this already if you are in command mode.
Press capital ZZ (shift zz
) - save & exit
Press capital ZQ (shift zq
) - exit without saving.
Maven does solve working problems, it builds java softwares, and easy dependence management. But it is very different from Ant, and GNU Make, or other Unix-like package management system. This make new-comer have to pay a lot to learn it.
There are lots Maven document, but some of them pushing you away, like this from "using m2eclipse":
By simply entering a groupId into the query field, m2eclipse queries the repository indexes and even shows a version of the artifact that is currently in my local Maven repository. This option is preferred because it is such a tremendous time saver.
I really hate to figure out a long sentence and found it says nothing. I can remember how good feel when reading python official tutorial, and erlang's. Good document will show the author has good senses.
Maven appears strange to newcomers, it's command line style is different from Unix command line traditions. If you pay time to go through "maven by examples" or "The Definitive Guide", it pay off, you can find it on http://www.sonatype.com/. But even if you read all those documents, and can use the tool with confidences, you can come across troubles time by time, some caused by software bugs. And expert get ways to live with it and keep productive.
After all, Maven is open source software, it contributes knowledges to freelance engineers. And this make it respectful. When people talks more about it's bad reputation, it is doing good job for open source world.
So, as how skilled people use any tools, just use it, and don't depend on it, depend on yourself.
In Windows, it could be a wrong path in "System environment variables". "Path" to the php.exe directory must be the good one.
SQL> select trunc(months_between(sysdate,dob)/12) year,
2 trunc(mod(months_between(sysdate,dob),12)) month,
3 trunc(sysdate-add_months(dob,trunc(months_between(sysdate,dob)/12)*12+trunc(mod(months_between(sysdate,dob),12)))) day
4 from (Select to_date('15122000','DDMMYYYY') dob from dual);
YEAR MONTH DAY
---------- ---------- ----------
9 5 26
SQL>
If you show the file in a canvas anyway you can also convert the canvas content to a blob object.
canvas.toBlob(function(my_file){
//.toBlob is only implemented in > FF18 but there is a polyfill
//for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
var myBlob = (my_file);
})
swift 4
if you don't want use storyboard, this might be help.
you can add table view and set properties in a closure:
lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .grouped)
tableView.backgroundColor = UIColor(named: Palette.secondaryLight.rawValue)
tableView.rowHeight = 68
tableView.separatorStyle = .none
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
then add in subview and set constraints.
To get the text of the selected option
$("#your_select :selected").text();
To get the value of the selected option
$("#your_select").val();
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
. See this.
I agree with @zzzzBov's answer, but the "fail fast" advantage of Promise.all
is not the only difference. Some users in the comments have asked why using Promise.all
is worth it when it's only faster in the negative scenario (when some task fails). And I ask, why not? If I have two independent async parallel tasks and the first one takes a very long time to resolve but the second is rejected in a very short time, why leave the user to wait for the longer call to finish to receive an error message? In real-life applications we must consider the negative scenario. But OK - in this first difference you can decide which alternative to use: Promise.all
vs. multiple await
.
But when considering error handling, YOU MUST use Promise.all
. It is not possible to correctly handle errors of async parallel tasks triggered with multiple await
s. In the negative scenario you will always end with UnhandledPromiseRejectionWarning
and PromiseRejectionHandledWarning
, regardless of where you use try/ catch. That is why Promise.all
was designed. Of course someone could say that we can suppress those errors using process.on('unhandledRejection', err => {})
and process.on('rejectionHandled', err => {})
but this is not good practice. I've found many examples on the internet that do not consider error handling for two or more independent async parallel tasks at all, or consider it but in the wrong way - just using try/ catch and hoping it will catch errors. It's almost impossible to find good practice in this.
TL;DR: Never use multiple await
for two or more independent async parallel tasks, because you will not be able to handle errors correctly. Always use Promise.all()
for this use case.
Async/ await
is not a replacement for Promises, it's just a pretty way to use promises. Async code is written in "sync style" and we can avoid multiple then
s in promises.
Some people say that when using Promise.all()
we can't handle task errors separately, and that we can only handle the error from the first rejected promise (separate handling can be useful e.g. for logging). This is not a problem - see "Addition" heading at the bottom of this answer.
Consider this async task...
const task = function(taskNum, seconds, negativeScenario) {
return new Promise((resolve, reject) => {
setTimeout(_ => {
if (negativeScenario)
reject(new Error('Task ' + taskNum + ' failed!'));
else
resolve('Task ' + taskNum + ' succeed!');
}, seconds * 1000)
});
};
When you run tasks in the positive scenario there is no difference between Promise.all
and multiple await
s. Both examples end with Task 1 succeed! Task 2 succeed!
after 5 seconds.
// Promise.all alternative
const run = async function() {
// tasks run immediate in parallel and wait for both results
let [r1, r2] = await Promise.all([
task(1, 5, false),
task(2, 5, false)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
// tasks run immediate in parallel
let t1 = task(1, 5, false);
let t2 = task(2, 5, false);
// wait for both results
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
However, when the first task takes 10 seconds and succeeds, and the second task takes 5 seconds but fails, there are differences in the errors issued.
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
We should already notice here that we are doing something wrong when using multiple await
s in parallel. Let's try handling the errors:
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!
As you can see, to successfully handle errors, we need to add just one catch to the run
function and add code with catch logic into the callback. We do not need to handle errors inside the run
function because async functions do this automatically - promise rejection of the task
function causes rejection of the run
function.
To avoid a callback we can use "sync style" (async/ await
+ try/ catch)
try { await run(); } catch(err) { }
but in this example it's not possible, because we can't use await
in the main thread - it can only be used in async functions (because nobody wants to block main thread). To test if handling works in "sync style" we can call the run
function from another async function or use an IIFE (Immediately Invoked Function Expression: MDN):
(async function() {
try {
await run();
} catch(err) {
console.log('Caught error', err);
}
})();
This is the only correct way to run two or more async parallel tasks and handle errors. You should avoid the examples below.
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
We can try to handle errors in the code above in several ways...
try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled
... nothing got caught because it handles sync code but run
is async.
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... huh? We see firstly that the error for task 2 was not handled and later that it was caught. Misleading and still full of errors in console, it's still unusable this way.
(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... the same as above. User @Qwerty in his deleted answer asked about this strange behavior where an error seems to be caught but are also unhandled. We catch error the because run()
is rejected on the line with the await
keyword and can be caught using try/ catch when calling run()
. We also get an unhandled error because we are calling an async task function synchronously (without the await
keyword), and this task runs and fails outside the run()
function.
It is similar to when we are not able to handle errors by try/ catch when calling some sync function which calls setTimeout:
function test() {
setTimeout(function() {
console.log(causesError);
}, 0);
};
try {
test();
} catch(e) {
/* this will never catch error */
}`.
Another poor example:
const run = async function() {
try {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
}
catch (err) {
return new Error(err);
}
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... "only" two errors (3rd one is missing) but nothing is caught.
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!
... note that in this example I rejected both tasks to better demonstrate what happens (throw err
is used to fire final error).
If you changed my.ini
and restarted mysql
and you still get this error please check your file path and replace "\"
to "/"
.
I solved my proplem after replacing.
There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.
Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.
You have to validate the connection.
If you use Oracle it is likely that you use Oracle´s Universal Connection Pool. The following assumes that you do so.
The easiest way to validate the connection is to tell Oracle that the connection must be validated while borrowing it. This can be done with
pool.setValidateConnectionOnBorrow(true);
But it works only if you hold the connection for a short period. If you borrow the connection for a longer time, it is likely that the connection gets broken while you hold it. In that case you have to validate the connection explicitly with
if (connection == null || !((ValidConnection) connection).isValid())
See the Oracle documentation for further details.
I second that.
Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.
However, JDGUI generates .java files which have ,more often than not, errors.
It has got something to do with code obfuscation I guess.
I have tried all the above solutions. But it was not working in any way.
Finally, I just uninstalled XAMPP and installed it again. Then it worked for me.
Now I am able to run the server on any port (including 80).
text-shadow: 4px 4px 2px rgba(150, 150, 150, 1);
for box shadow:
-webkit-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
box-shadow: 7px 7px 5px rgba(50, 50, 50, 0.75);
you can see online text and box shadow: online text and box shadow
for more example you can go to this address : more example code freeclup
The problem I had was that I was putting the --env-file at the end of the command
docker run -it --rm -p 8080:80 imagename --env-file ./env.list
Fix
docker run --env-file ./env.list -it --rm -p 8080:80 imagename
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
Probably because for both sides (B and C) only the type is relevant, not the implementation. In your example
public class A<B extends C>{}
B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.
interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}
I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.
For Kotlin Users
val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params
Here I used FrameLayout.LayoutParams
since my views( ImageView
) parent is FrameLayout
Assuming popup
is the ID of your "description box":
HTML
<div id="parent"> <!-- This is the main container, to mouse over -->
<div id="popup" style="display: none">description text here</div>
</div>
JavaScript
var e = document.getElementById('parent');
e.onmouseover = function() {
document.getElementById('popup').style.display = 'block';
}
e.onmouseout = function() {
document.getElementById('popup').style.display = 'none';
}
Alternatively you can get rid of JavaScript entirely and do it just with CSS:
CSS
#parent #popup {
display: none;
}
#parent:hover #popup {
display: block;
}
Reading the file
import scipy.io
mat = scipy.io.loadmat(file_name)
Inspecting the type of MAT variable
print(type(mat))
#OUTPUT - <class 'dict'>
The keys inside the dictionary are MATLAB variables, and the values are the objects assigned to those variables.
Here is the generic solution I use. It solves the problem for importing from modules in the same folder:
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
Put this at top of the module which gives the error "No module named xxxx"
Try this:
You need to add left: 0
and right: 0
(not supported by IE6). Or specify a width
Just to give some examples. Let's say you modify the password for an user called 'alex'. You can modify this password in several ways. For instance:
mysql> update* user set password=PASSWORD('test!23') where user='alex';
mysql> flush privileges;
Here you used UPDATE. If you use INSERT, UPDATE or DELETE on grant tables directly you need use FLUSH PRIVILEGES in order to reload the grant tables.
Or you can modify the password like this:
mysql> set password for 'alex'@'localhost'= password('test!24');
Here it's not necesary to use "FLUSH PRIVILEGES;" If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately.
I have to run SCOM 2012 functions from a remote server that requires a different credential. I avoid clear-text passwords by passing the output of a password decryption function as input to ConvertTo-SecureString. For clarity, this is not shown here.
I like to strongly type my declarations. The type declaration for $strPass works correctly.
[object] $objCred = $null
[string] $strUser = 'domain\userID'
[System.Security.SecureString] $strPass = ''
$strPass = ConvertTo-SecureString -String "password" -AsPlainText -Force
$objCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)
Made a util inspired from Dave's answer
Basically passed in a done
callback to call when the operation is finished.
// Function to timeout if a request is taking too long
const setAsyncTimeout = (cb, timeout = 0) => new Promise((resolve, reject) => {
cb(resolve);
setTimeout(() => reject('Request is taking too long to response'), timeout);
});
This is how I use it:
try {
await setAsyncTimeout(async done => {
const requestOne = await someService.post(configs);
const requestTwo = await someService.get(configs);
const requestThree = await someService.post(configs);
done();
}, 5000); // 5 seconds max for this set of operations
}
catch (err) {
console.error('[Timeout] Unable to complete the operation.', err);
}
I don't know if this will help you but..
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );
I found that using the Common Event described above works well and you could have the common event set up like this:
private void checkChanged(object sender, EventArgs e)
{
foreach (RadioButton r in yourPanel.Controls)
{
if (r.Checked)
textBox.Text = r.Text;
}
}
Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)
My solution similar as mefa:::rep.data.frame
, but a little faster and cares about row names:
rep.data.frame <- function(x, times) {
rnames <- attr(x, "row.names")
x <- lapply(x, rep.int, times = times)
class(x) <- "data.frame"
if (!is.numeric(rnames))
attr(x, "row.names") <- make.unique(rep.int(rnames, times))
else
attr(x, "row.names") <- .set_row_names(length(rnames) * times)
x
}
Compare solutions:
library(Lahman)
library(microbenchmark)
microbenchmark(
mefa:::rep.data.frame(Batting, 10),
rep.data.frame(Batting, 10),
Batting[rep.int(seq_len(nrow(Batting)), 10), ],
times = 10
)
#> Unit: milliseconds
#> expr min lq mean median uq max neval cld
#> mefa:::rep.data.frame(Batting, 10) 127.77786 135.3480 198.0240 148.1749 278.1066 356.3210 10 a
#> rep.data.frame(Batting, 10) 79.70335 82.8165 134.0974 87.2587 191.1713 307.4567 10 a
#> Batting[rep.int(seq_len(nrow(Batting)), 10), ] 895.73750 922.7059 981.8891 956.3463 1018.2411 1127.3927 10 b
Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:
def check_authorization(f):
def wrapper(*args):
print args[0].url
return f(*args)
return wrapper
class Client(object):
def __init__(self, url):
self.url = url
@check_authorization
def get(self):
print 'get'
>>> Client('http://www.google.com').get()
http://www.google.com
get
The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr
if you don't want to hardcode the attribute name:
def check_authorization(attribute):
def _check_authorization(f):
def wrapper(self, *args):
print getattr(self, attribute)
return f(self, *args)
return wrapper
return _check_authorization
Pipes in Angular 2+ are a great way to transform and format data right from your templates.
Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.
List of Built-in Pipes from API List Examples
{{ user.name | uppercase }}
Example of Angular version 4.4.7. ng version
Custom Pipes which accepts multiple arguments.
HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS « transform(json: any[], args: any[]) : any[] { ... }
Filtering the content using a Pipe « json-filter-by.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]) : any[] {
var searchText = args[0];
var jsonKey = args[1];
// json = undefined, args = (2) [undefined, "name"]
if(searchText == null || searchText == 'undefined') return json;
if(jsonKey == null || jsonKey == 'undefined') return json;
// Copy all objects of original array into new Array.
var returnObjects = json;
json.forEach( function ( filterObjectEntery ) {
if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
console.log('Search key is available in JSON object.');
if ( typeof filterObjectEntery[jsonKey] != "undefined" &&
filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
} else {
// object didn't match a filter value so remove it from array via filter
returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
}
} else {
console.log('Search key is not available in JSON object.');
}
})
return returnObjects;
}
}
Add to @NgModule
« Add JsonFilterByPipe
to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy
. If you add to module then it is available to all the component's of that module.
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule, ReactiveFormsModule,
],
providers: [ StudentDetailsService ],
declarations: [
UsersComponent, UserComponent,
JsonFilterByPipe,
],
exports : [UsersComponent, UserComponent]
})
export class UsersModule {
// ...
}
File Name: users.component.ts
and StudentDetailsService
is created from this link.
import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: [ './users.component.css' ],
providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy {
students: MyStudents[];
selectedStudent: MyStudents;
constructor(private studentService: StudentDetailsService) { }
ngOnInit(): void {
this.loadAllUsers();
}
ngOnDestroy(): void {
// ONDestroy to prevent memory leaks
}
loadAllUsers(): void {
this.studentService.getStudentsList().then(students => this.students = students);
}
onSelect(student: MyStudents): void {
this.selectedStudent = student;
}
}
File Name: users.component.html
<div>
<br />
<div class="form-group">
<div class="col-md-6" >
Filter by Name:
<input type="text" [(ngModel)]="searchText"
class="form-control" placeholder="Search By Category" />
</div>
</div>
<h2>Present are Students</h2>
<ul class="students">
<li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
<a *ngIf="student" routerLink="/users/update/{{student.id}}">
<span class="badge">{{student.id}}</span> {{student.name | uppercase}}
</a>
</li>
</ul>
</div>
The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.
This error occurred for me when using window.location.reload()
. Replacing with window.location = window.location.href
solved the problem.
This may work as well.
SELECT *
FROM myTable
WHERE CHARINDEX('mall', name) > 0
OR CHARINDEX('mall', description) > 0
In my case, the issue was not resolved by updating butterknife
from: "com.jakewharton:butterknife:8.4.0" to: "com.jakewharton:butterknife:8.8.1"
I've tried to @BindView inside Adapter class and no success. As soon I used .findViewById(R.id.message_time), compilation had been completed successfully.
It took me a while but I was able to get this working finally after going through the suggestions offered and additional web searches being done. I used the information in the following YouTube video created by Mactasia:
http://www.youtube.com/watch?v=y1c7WFMMkZ4
When I did this I saw the file with .lock as the extension. However I still got the error when I tried to start the Rails Server when I resumed working on my Rails application using PostgreSQL. This time I got a permission denied error. This is when I remembered that not only did I have to change listen_addresses in the plist but I also had to change unit_socket_permissions to 0777. I also logged in as root to change the permissions on the var/pgsql_socket folder where I could access it at the user level. Postgres is working fine now. I am in the process of reloading my data from my SQL backup.
What I did not understand was that when I had wiki turned on PostgreSQL was supposedly working when I did a sudo serveradmin fullstatus postgres but I still got the error. Oh well.
If elem.find()
is not working for you, check that you are including JQuery script before angular script....
You can add a class and gives font-weight:700; in option. But by using this all the text will become bold.
Do you mean, a message box?
MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx
Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.
You can do something like this :
import commands
size = commands.getoutput('du -sh /path/').split()[0]
in this case I have not tested the result before returning it, if you want you can check it with commands.getstatusoutput.
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
The declare array doesn't work for Korn shell. Use the below example for the Korn shell:
promote_sla_chk_lst="cdi xlob"
set -A promote_arry $promote_sla_chk_lst
for i in ${promote_arry[*]};
do
echo $i
done
Fix your issue with this
tbody {
display: table-caption;
height: 200px;
caption-side: bottom;
overflow: auto;
}
Below I've incorporated suggestion from comments. Thank you al!
import hashlib
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
h = hash_factory()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(chunk_num_blocks*h.block_size), b''):
h.update(chunk)
return h.digest()
import hashlib
def checksum(filename, hash_factory=hashlib.md5, chunk_num_blocks=128):
h = hash_factory()
with open(filename,'rb') as f:
while chunk := f.read(chunk_num_blocks*h.block_size):
h.update(chunk)
return h.digest()
if you care about more pythonic (no 'while True') way of reading the file check this code:
import hashlib
def checksum_md5(filename):
md5 = hashlib.md5()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
md5.update(chunk)
return md5.digest()
Note that the iter() func needs an empty byte string for the returned iterator to halt at EOF, since read() returns b'' (not just '').
You have to put it in the root directory, that corresponds to your execution context.
Example:
MyProject
src
MyClass.java
log4j.properties
If you start executing from a different project, you need to have that file in the project used for starting the execution. For example, if a different project holds some JUnit tests, it needs to have also its log4j.properties file.
I suggest using log4j.xml instead of the log4j.properties. You have more options, get assistance from your IDE and so on...
Interesting that these answers utilize printf
like it is a given.
printf
converts the integer to a Hexadecimal string value.
//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base = number base for conversion; decimal=10,hex=16
// char sign = signed or unsigned output
// char *outbuf = buffer to hold the output number
//*************************************************************
void prntnum(unsigned long n, int base, char sign, char *outbuf)
{
int i = 12;
int j = 0;
do{
outbuf[i] = "0123456789ABCDEF"[num % base];
i--;
n = num/base;
}while( num > 0);
if(sign != ' '){
outbuf[0] = sign;
++j;
}
while( ++i < 13){
outbuf[j++] = outbuf[i];
}
outbuf[j] = 0;
}
If you are using CSS to style (Not recommended.) you can use display:block;
, however, this will only give you line breaks before and after the styled element.
var promise = $interval(function(){
if($location.path() == '/landing'){
$rootScope.$emit('testData',"test");
$interval.cancel(promise);
}
},2000);
here :
http://jsbin.com/ucuqot/3/edit
function findXX(word)
{
$.each(someArray, function(i,n)
{
$('body').append('-> '+i+'<br />');
if(n == word)
{
return false;
}
});
}
You could try:
<a href="<?php echo $directory ?>">The link to the file</a>
Or for PHP 5.4+ (<?=
is the PHP short echo tag):
<a href="<?= $directory ?>">The link to the file</a>
But your path is relative to the server, don't forget that.
I confirm. We must add:
webPreferences: {
nodeIntegration: true
}
For example:
mainWindow = new BrowserWindow({webPreferences: {
nodeIntegration: true
}});
For me, the problem has been resolved with that.
I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.
I believe you have libx264
installed and configured with ffmpeg
to convert video to h264
... Then you can try with -vcodec libx264
... The -format
option is for showing available formats, this is not a conversion option I think...
ls -l | awk '{print $9}' | tail -n1
In our case git
had to be installed on the Jenkins server.
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var form=$("#myForm");_x000D_
$("#smt").click(function(){_x000D_
$.ajax({_x000D_
type:"POST",_x000D_
url:form.attr("action"),_x000D_
data:form.serialize(),_x000D_
success: function(response){_x000D_
console.log(response); _x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This is perfect code , there is no problem.. You have to check that in php script.
The official position seems to be that this isn't something you'd ever "want to do". See this thread on the Android Developers list. Google envisage android running on a variety of different devices (CPUs, displays, etc). The best way to enable development is therefore to use (portable) managed code that targets the Dalvik VM. For this reason, the Android SDK doesn't support C/C++.
BUT, take a look at this page:
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.
The managed application framework appears to be layered on-top of these libraries. The page goes on to list the C/C++ libs: standard C library, media, 3D, SQL lite, and others.
So all you need is a compiler chain that will compile C/C++ to the appropriate CPU (ARM, in the case of the G1). Some brief instructions on how to do this are here.
What I don't know is where to find descriptions of the APIs that these libraries provide. I'd guess there may be header files buried in the SDK somewhere, but documentation may be sketchy/missing. But I think it can be done!
Hope thats useful. For the record, I haven't written any native android apps - just a few simple managed ones.
Andy
To expand slightly, if you're doing this with the svn command-line tool, you want to type:
svn propedit svn:ignore path/to/dir
which will open your text-editor of choice, then type '*' to ignore everything inside it, and save+quit - this will include the directory itself in svn, but ignore all the files inside it, to ignore the directory, use the path of the parent, and then type the name of the directory in the file. After saving, run an update ('svn up'), and then check in the appropriate path.
Let's suppose you have a book, probably a novel, a thick one with lots of things to read, hence lots of words. Now, hypothetically, you brought two dictionaries, consisting of only words that are only used, at least one time in the novel. All words in that two dictionaries are stored in typical alphabetical order. In hypothetical dictionary A, words are printed only once while in hypothetical dictionary B words are printed as many numbers of times it is printed in the novel. Remember, words are sorted alphabetically in both the dictionaries. Now you got stuck at some point while reading a novel and need to find the meaning of that word from anyone of those hypothetical dictionaries. What you will do? Surely you will jump to that word in a few steps to find its meaning, rather look for the meaning of each of the words in the novel, from starting, until you reach that bugging word.
This is how the index works in SQL. Consider Dictionary A as PRIMARY INDEX, Dictionary B as KEY/SECONDARY INDEX, and your desire to get for the meaning of the word as a QUERY/SELECT STATEMENT. The index will help to fetch the data at a very fast rate. Without an index, you will have to look for the data from the starting, unnecessarily time-consuming costly task.
For more about indexes and types, look this.
Unlike Java where you would declare boolean flag = True
, in Python you can just declare myFlag = True
Python would interpret this as a boolean variable
Default usage
el.addEventListener('input', function () {
fn();
});
But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.
var event = new Event('input');
el.addEventListener('input', function () {
fn();
});
form.addEventListener('input', function () {
anotherFn();
});
el.value = 'something';
el.dispatchEvent(input);
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
Downgrading openssl worked for me,
brew switch openssl 1.0.2s
hi @JackSlayer94 please find the below example to understand how to make an array of size 5.
class Hero {_x000D_
name: string;_x000D_
constructor(text: string) {_x000D_
this.name = text;_x000D_
}_x000D_
_x000D_
display() {_x000D_
return "Hello, " + this.name;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
console.log(heros[i].display());_x000D_
}
_x000D_
You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.
Second largest element: Let us take example : [1,5,4,2,3] in this case, Second largest element will be 4.
Sort the Array in descending order, once the sort done output will be A = [5,4,3,2,1]
Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.
private static int getMostOccuringElement(int[] A) { Map occuringMap = new HashMap();
//count occurences
for (int i = 0; i < A.length; i++) {
if (occuringMap.get(A[i]) != null) {
int val = occuringMap.get(A[i]) + 1;
occuringMap.put(A[i], val);
} else {
occuringMap.put(A[i], 1);
}
}
//find maximum occurence
int max = Integer.MIN_VALUE;
int element = -1;
for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
if (entry.getValue() > max) {
max = entry.getValue();
element = entry.getKey();
}
}
return element;
}
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
chrisofspades,
As far as I know that behavior is not compatible with the way the db engine works, but there is a simple (i don't know if elegant, but performant) solution to achive your two objectives of DO NOT
The solution is to use two fields, one nullable for insert, and other one calculated to selections:
CREATE TABLE t (
insValue VARCHAR(50) NULL
, selValue AS ISNULL(insValue, 'something')
)
DECLARE @d VARCHAR(10)
INSERT INTO t (insValue) VALUES (@d) -- null
SELECT selValue FROM t
This method even let You centralize the management of business defaults in a parameter table, placing an ad hoc function to do this, vg changing:
selValue AS ISNULL(insValue, 'something')
for
selValue AS ISNULL(insValue, **getDef(t,1)**)
I hope this helps.
You can also use ng-pattern ,[7-9] = > mobile number must start with 7 or 8 or 9 ,[0-9] = mobile number accepts digits ,{9} mobile number should be 10 digits.
function form($scope){_x000D_
$scope.onSubmit = function(){_x000D_
alert("form submitted");_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>_x000D_
<div ng-app ng-controller="form">_x000D_
<form name="myForm" ng-submit="onSubmit()">_x000D_
<input type="number" ng-model="mobile_number" name="mobile_number" ng-pattern="/^[7-9][0-9]{9}$/" required>_x000D_
<span ng-show="myForm.mobile_number.$error.pattern">Please enter valid number!</span>_x000D_
<input type="submit" value="submit"/>_x000D_
</form>_x000D_
</div>
_x000D_
example.php:
<?php
if(!isset($_GET['app_link'])){ ?>
<iframe src="example.php?app_link=YourApp://blabla" style="display:none;" scrolling="no" frameborder="0"></iframe>
<iframe src="example.php?full_link=http://play.google.com/xyz" style="display:none;" scrolling="no" frameborder="0"></iframe>
<?php
}
else { ?>
<script type="text/javascript">
self.window.location = '<?php echo $_GET['app_link'];?>';
window.parent.location.href = '<?php echo $_GET['full_link'];?>';
</script>
<?php
}
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
With Spring you can do:
String path = new UrlPathHelper().getPathWithinApplication(request);
It has been long time, but I faced the same Issue, and solved it as follow: 1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..
Try adding the following method to your app's root view controller:
- (BOOL)prefersStatusBarHidden
{
return YES;
}
We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.
Order Allow,Deny
Deny from all
Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.
<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
Allow from all
</FilesMatch>
your final .htaccess
file will look like
Order Allow,Deny
Deny from all
<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
Allow from all
</FilesMatch>
Source from Allow access to specific file types in a protected directory
You can use VectorDrawable as below :
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportHeight="64"
android:viewportWidth="64">
<path
android:fillColor="#ff00ff"
android:pathData="M22,32
A10,10 0 1,1 42,32
A10,10 0 1,1 22,32 Z" />
</vector>
The above xml renders as :
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
set the dll path in the config file
<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />
before calling the dll in you app, do the following
string dllPath= ConfigurationManager.AppSettings["dllPath"];
string appDirectory = Path.GetDirectoryName(dllPath);
Directory.SetCurrentDirectory(appDirectory);
then call the dll and you can use like below
[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);
The way I am doing it when I am running php scripts is:
* * * * * php /path/to/php/script.php &
<?php
if (shell_exec('ps aux | grep ' . __FILE__ . ' | wc -l') > 1) {
exit('already running...');
}
// do stuff
This command is searching in the system process list for the current php filename if it exists the line counter (wc -l) will be greater then one because the search command itself containing the filename
so if you running php crons add the above code to the start of your php code and it will run only once.
import sys.process._
"echo hello world" #> new java.io.File("/tmp/example.txt") !
I'd like to add on for the #else
case:
#if 0
/* Code here will NOT be complied. */
#else
/* Code will be compiled. */
#endif
#if 1
/* Code will be complied. */
#else
/* Code will NOT be compiled. */
#endif
No one seems to love mac re-indentation, So here How I do it:
[
{ "keys": ["command+shift+i"], "command": "reindent"}
]
In Preferences > Key Binding - User
One more extra tip: add
{ "keys": ["command+0"], "command": "focus_side_bar" }
to have sidebar file tree view navigation using keyboard.
Note: Add , at the end of each {}, if you have more than one {} set of objects
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
I came across these links:
http://mail.openjdk.java.net/pipermail/core-libs-dev/2009-May/001689.html
http://www.nabble.com/Review-request-for-5049299-td23667680.html
Seems to be a bug. Usage of a spawn() trick instead of the plain fork()/exec() is advised.
<?php
require_once 'PHPUnit/Framework.php';
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
$this->expectException(InvalidArgumentException::class);
// or for PHPUnit < 5.2
// $this->setExpectedException(InvalidArgumentException::class);
//...and then add your test code that generates the exception
exampleMethod($anInvalidArgument);
}
}
expectException() PHPUnit documentation
PHPUnit author article provides detailed explanation on testing exceptions best practices.
In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.
Place all files need to copied in a separate folder, for ease place them in c drive.
Open Command Prompt - windows>type cmd>select command prompt.
You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.
After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.
Now type : 'copy *.txt [newfile_name].txt' and press enter.
Done!
All the text in individual files will be copied to [newfile_name].txt
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
While my answer isn't 100% applicable, but most search engines find this as the first hit, I decided to post it nontheless:
If you're using PrimeFaces (or some similar API) p:commandButton
or p:commandLink
, chances are that you have forgotten to explicitly add process="@this"
to your command components.
As the PrimeFaces User's Guide states in section 3.18, the defaults for process
and update
are both @form
, which pretty much opposes the defaults you might expect from plain JSF f:ajax
or RichFaces, which are execute="@this"
and render="@none"
respectively.
Just took me a looong time to find out. (... and I think it's rather unclever to use defaults that are different from JSF!)
The -H 'Cache-Control: no-cache'
argument is not guaranteed to work because the remote server or any proxy layers in between can ignore it. If it doesn't work, you can do it the old-fashioned way, by adding a unique querystring parameter. Usually, the servers/proxies will think it's a unique URL and not use the cache.
curl "http://www.example.com?foo123"
You have to use a different querystring value every time, though. Otherwise, the server/proxies will match the cache again. To automatically generate a different querystring parameter every time, you can use date +%s
, which will return the seconds since epoch.
curl "http://www.example.com?$(date +%s)"
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\bMyClass\b/,'');
where MyID
is the ID of the element and MyClass is the name of the class you wish to remove.
UPDATE: To support class names containing dash character, such as "My-Class", use
document.getElementById("MyID").className =
document.getElementById("MyID").className
.replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
<Text>
Some Text
</Text>
</View>
flexDirection
: If you want to move horizontally (row) or vertically (column)
justifyContent
: the direction you want to move.
Update v3: https://www.npmjs.com/package/windows-build-tools
npm install --global windows-build-tools
downloads and installs Visual C++ Build Tools 2015, provided free of charge by Microsoft. These tools are required to compile popular native modules. It will also install Python 2.7, configuring your machine and npm appropriately.
Update v2:
node-gyp updated their readme to include HOW-TO for windows
Original:
No need for the entire visual studio, you can download just the build tools
Microsoft Build Tools 2013 : http://www.microsoft.com/en-us/download/details.aspx?id=40760
run cmd to set global flag to use the 2013 version:
npm config set msvs_version 2013 --global
after this everything should be back to normal and your npm install / node-gyp rebuild will work
SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;
Would give you 2 values after the decimal point. (MS SQL SERVER)
This code sample can be used to change date format. Here I want to change from yyyy-MM-dd to dd-MM-yyyy. Here pos
is position of column.
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class Test{
public static void main( String[] args )
{
String input="D:\\somefolder\\somefile.xlsx";
String output="D:\\somefolder\\someoutfile.xlsx"
FileInputStream file = new FileInputStream(new File(input));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=5; // 5th column is date.
while(iterator.hasNext())
{
row=iterator.next();
cell=row.getCell(pos-1);
//CellStyle cellStyle = wb.createCellStyle();
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("dd-MM-yyyy"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d=null;
try {
d= sdf.parse(cell.getStringCellValue());
} catch (ParseException e) {
// TODO Auto-generated catch block
d=null;
e.printStackTrace();
continue;
}
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File(output));
workbook.write(outFile);
workbook.close();
outFile.close();
}}
I would advise, it is slightly better practise to use string model references for ForeignKey
relationships if utilising an app based approach to seperation of logical concerns .
So, expanding on Martijn Pieters' answer:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
'app_label.Anniversary', on_delete=models.CASCADE)
address = models.ForeignKey(
'app_label.Address', on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
server {
server_name xyz.com;
root /home/ubuntu/project_folder/;
client_max_body_size 10M;
access_log /var/log/nginx/project.access.log;
error_log /var/log/nginx/project.error.log;
location /static {
index index.html;
}
location /media {
alias /home/ubuntu/project/media/;
}
}
Server block to live the static page on nginx.
Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:
CSS
#container {
display: table;
width: 300px; /* not required, just for example */
height: 400px; /* not required, just for example */
}
#update {
display: table-cell;
vertical-align: middle;
text-align: center;
}
HTML
<div id="container">
<a id="update" href="#">
<i class="icon-refresh"></i>
</a>
</div>
Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell
display property works.
Most of the answers above now doesn't give permanent token, they only extend it to 2 months. Here's how I got it:
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
When you open the file you want to write to, open it with a specific encoding that can handle all the characters.
with open('filename', 'w', encoding='utf-8') as f:
print(r['body'], file=f)
time_t
is of type long int
on 64 bit machines, else it is long long int
.
You could verify this in these header files:
time.h
: /usr/include
types.h
and typesizes.h
: /usr/include/x86_64-linux-gnu/bits
(The statements below are not one after another. They could be found in the resp. header file using Ctrl+f search.)
1)In time.h
typedef __time_t time_t;
2)In types.h
# define __STD_TYPE typedef
__STD_TYPE __TIME_T_TYPE __time_t;
3)In typesizes.h
#define __TIME_T_TYPE __SYSCALL_SLONG_TYPE
#if defined __x86_64__ && defined __ILP32__
# define __SYSCALL_SLONG_TYPE __SQUAD_TYPE
#else
# define __SYSCALL_SLONG_TYPE __SLONGWORD_TYPE
#endif
4) Again in types.h
#define __SLONGWORD_TYPE long int
#if __WORDSIZE == 32
# define __SQUAD_TYPE __quad_t
#elif __WORDSIZE == 64
# define __SQUAD_TYPE long int
#if __WORDSIZE == 64
typedef long int __quad_t;
#else
__extension__ typedef long long int __quad_t;
You can do it using streams map function like below, get result in new stream for further processing.
Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
newFruits.forEach(fruit->{
System.out.println(fruit.name);
});
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
this could do it:
perl -ne 'if(m/name="(.*?)"/){ print $1 . "\n"; }'
Breaking news: I've added another answer that uses an Observable rather than an EventEmitter. I recommend that answer over this one. And actually, using an EventEmitter in a service is bad practice.
Original answer: (don't do this)
Put the EventEmitter into a service, which allows the ObservingComponent to directly subscribe (and unsubscribe) to the event:
import {EventEmitter} from 'angular2/core';
export class NavService {
navchange: EventEmitter<number> = new EventEmitter();
constructor() {}
emit(number) {
this.navchange.emit(number);
}
subscribe(component, callback) {
// set 'this' to component when callback is called
return this.navchange.subscribe(data => call.callback(component, data));
}
}
@Component({
selector: 'obs-comp',
template: 'obs component, index: {{index}}'
})
export class ObservingComponent {
item: number;
subscription: any;
constructor(private navService:NavService) {
this.subscription = this.navService.subscribe(this, this.selectedNavItem);
}
selectedNavItem(item: number) {
console.log('item index changed!', item);
this.item = item;
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-nav',
template:`
<div class="nav-item" (click)="selectedNavItem(1)">item 1 (click me)</div>
`,
})
export class Navigation {
constructor(private navService:NavService) {}
selectedNavItem(item: number) {
console.log('selected nav item ' + item);
this.navService.emit(item);
}
}
If you try the Plunker, there are a few things I don't like about this approach:
subscribe()
so that the proper this
is set when the callback is calledUpdate: An alternative that solves the 2nd bullet is to have the ObservingComponent directly subscribe to the navchange
EventEmitter property:
constructor(private navService:NavService) {
this.subscription = this.navService.navchange.subscribe(data =>
this.selectedNavItem(data));
}
If we subscribe directly, then we wouldn't need the subscribe()
method on the NavService.
To make the NavService slightly more encapsulated, you could add a getNavChangeEmitter()
method and use that:
getNavChangeEmitter() { return this.navchange; } // in NavService
constructor(private navService:NavService) { // in ObservingComponent
this.subscription = this.navService.getNavChangeEmitter().subscribe(data =>
this.selectedNavItem(data));
}
There were a few ways I found to do this:
java InstallCert [host]:[port] keytool -exportcert -keystore jssecacerts -storepass changeit -file output.cert keytool -importcert -keystore [DESTINATION_KEYSTORE] -file output.cert
For completeness, here is a java-8 way of doing it
countMap.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
or
Collections.max(countMap.entrySet(), (entry1, entry2) -> entry1.getValue() - entry2.getValue()).getKey();
or
Collections.max(countMap.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getKey();
Below command worked for me
mongoimport --db test --collection docs --file example2.json
when i removed the extra newline character before Email
attribute in each of the documents.
{"FirstName": "Bruce", "LastName": "Wayne", "Email": "[email protected]"}
{"FirstName": "Lucius", "LastName": "Fox", "Email": "[email protected]"}
{"FirstName": "Dick", "LastName": "Grayson", "Email": "[email protected]"}
I have implemented a temporary solution until angular2 support form updateValue
initFormGroup(form: FormGroup, data: any) {
for(var key in form.controls) {
console.log(key);
if(form.controls[key] instanceof FormControl) {
if(data[key]){
let control = <FormControl>form.controls[key];
this.initFormControl(control,data[key]);
}
} else if(form.controls[key] instanceof FormGroup) {
if(data[key]){
this.initFormGroup(<FormGroup>form.controls[key],data[key]);
}
} else if(form.controls[key] instanceof FormArray) {
var control = <FormArray>form.controls[key];
if(data[key])
this.initFormArray(control, data[key]);
}
}
}
initFormArray(array: FormArray, data: Array<any>){
if(data.length>0){
var clone = array.controls[0];
array.removeAt(0);
for(var idx in data) {
array.push(_.cloneDeep(clone));
if(clone instanceof FormGroup)
this.initFormGroup(<FormGroup>array.controls[idx], data[idx]);
else if(clone instanceof FormControl)
this.initFormControl(<FormControl>array.controls[idx], data[idx]);
else if(clone instanceof FormArray)
this.initFormArray(<FormArray>array.controls[idx], data[idx]);
}
}
}
initFormControl(control: FormControl, value:any){
control.updateValue(value);
}
usage:
this.initFormGroup(this.form, {b:"data",c:"data",d:"data",e:["data1","data2"],f:data});
note: form and data must have the same structure and i have used lodash for deepcloning jQuery and other libs can do as well
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
The problem for me was that SSRS purposely treats your white space as if you intend it be honored:
As well as white space, make sure there is no right margin.
If upload_file
is meant to be the file, use:
files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}
r = requests.post(url, files=files, data=values)
and requests
will send a multi-part form POST body with the upload_file
field set to the contents of the file.txt
file.
The filename will be included in the mime header for the specific field:
>>> import requests
>>> open('file.txt', 'wb') # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"
--c226ce13d09842658ffbd31e0563c6bd--
Note the filename="file.txt"
parameter.
You can use a tuple for the files
mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:
files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}
This sets an alternative filename and content type, leaving out the optional headers.
If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files
parameter, just post the file directly as data
. You then may want to set a Content-Type
header too, as none will be set otherwise. See Python requests - POST data from a file.
This worked for me
$mail->SetFrom("[email protected]","my name", 0); //notice the third parameter
A slightly different approach is to create your formula from a string. In the formula
help page you will find the following example :
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
fmla <- as.formula(paste("y ~ ", paste(xnam, collapse= "+")))
Then if you look at the generated formula, you will get :
R> fmla
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
I am in the group that considers that the "scoped guard" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to std::terminate
since destructors are implicitly annotated with noexcept
.
Andrzej Krzemienski has a great post on the topic of destructors that throw:
He points out that C++11 has a mechanism to override the default noexcept
for destructors:
In C++11, a destructor is implicitly specified as
noexcept
. Even if you add no specification and define your destructor like this:class MyType { public: ~MyType() { throw Exception(); } // ... };
The compiler will still invisibly add specification
noexcept
to your destructor. And this means that the moment your destructor throws an exception,std::terminate
will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:
- Explicitly specify your destructor as
noexcept(false)
,- Inherit your class from another one that already specifies its destructor as
noexcept(false)
.- Put a non-static data member in your class that already specifies its destructor as
noexcept(false)
.
Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to std::terminate
and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using std::uncaught_exception()
.
What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.
// new answer
function justTesting() {
return new Promise((resolve, reject) => {
if (true) {
return resolve("testing");
} else {
return reject("promise failed");
}
});
}
justTesting()
.then(res => {
let test = res;
// do something with the output :)
})
.catch(err => {
console.log(err);
});
Hope this helps!
// old answer
function justTesting() {
return promise.then(function(output) {
return output + 1;
});
}
justTesting().then((res) => {
var test = res;
// do something with the output :)
}
You can use the to_records
method, but have to play around a bit with the dtypes if they are not what you want from the get go. In my case, having copied your DF from a string, the index type is string (represented by an object
dtype in pandas):
In [102]: df
Out[102]:
label A B C
ID
1 NaN 0.2 NaN
2 NaN NaN 0.5
3 NaN 0.2 0.5
4 0.1 0.2 NaN
5 0.1 0.2 0.5
6 0.1 NaN 0.5
7 0.1 NaN NaN
In [103]: df.index.dtype
Out[103]: dtype('object')
In [104]: df.to_records()
Out[104]:
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
(4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
(7, 0.1, nan, nan)],
dtype=[('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
In [106]: df.to_records().dtype
Out[106]: dtype([('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Converting the recarray dtype does not work for me, but one can do this in Pandas already:
In [109]: df.index = df.index.astype('i8')
In [111]: df.to_records().view([('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Out[111]:
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
(4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
(7, 0.1, nan, nan)],
dtype=[('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Note that Pandas does not set the name of the index properly (to ID
) in the exported record array (a bug?), so we profit from the type conversion to also correct for that.
At the moment Pandas has only 8-byte integers, i8
, and floats, f8
(see this issue).
It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.
Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.
Try this:
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
xS = w.innerWidth || e.clientWidth || g.clientWidth,
yS = w.innerHeight|| e.clientHeight|| g.clientHeight;
alert(xS + ' × ' + yS);
document.write('')
works for iframe and well.
you can copy this db file to somewhere in eclipse explorer (eg:sdcard or PC),and you can use sqlite to access and update this db file .
None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.
This worked for me:
exception_raised = False
try:
do_something_that_might_raise_an_exception()
except ValueError as e:
message = str(e)
exception_raised = True
if exception_raised:
message_to_prepend = "Custom text"
raise ValueError(message_to_prepend + message)
This worked for me when I encountered the same issue on my KitKat. Remove your account from the device (Settings > Accounts > Google > Remove Account)
Remove the following data: Settings> Applications > All> Downloads > delete data. Settings> Applications > All> Play Store> delete data. Settings> Apps > All> Google Services Framework (or if they have it in English: Google Service Framework) > delete data.
Log in again and it was fixed for me.
Like the other answers said, sp_reset_connection
indicates that connection pool is being reused. Be aware of one particular consequence!
Jimmy Mays' MSDN Blog said:
sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.
UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.
ref: SQL Server: Isolation level leaks across pooled connections
Here is some additional information:
What does sp_reset_connection do?
Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.
sp_reset_connection resets the following aspects of a connection:
All error states and numbers (like @@error)
Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query
Waits for any outstanding I/O operations that is outstanding
Frees any held buffers on the server by the connection
Unlocks any buffer resources that are used by the connection
Releases all allocated memory owned by the connection
Clears any work or temporary tables that are created by the connection
Kills all global cursors owned by the connection
Closes any open SQL-XML handles that are open
Deletes any open SQL-XML related work tables
Closes all system tables
Closes all user tables
Drops all temporary objects
Aborts open transactions
Defects from a distributed transaction when enlisted
Decrements the reference count for users in current database which releases shared database locks
Frees acquired locks
Releases any acquired handles
Resets all SET options to the default values
Resets the @@rowcount value
Resets the @@identity value
Resets any session level trace options using dbcc traceon()
Resets CONTEXT_INFO to
NULL
in SQL Server 2005 and newer [ not part of the original article ]sp_reset_connection will NOT reset:
Security context, which is why connection pooling matches connections based on the exact connection string
Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when
sp_setapprole
is executed.
Note: I am including the list here as I do not want it to be lost in the ever transient web.
You can use a bind variable at the SQLPlus level to do this. Of course you have little control over the formatting of the output.
VAR x REFCURSOR;
EXEC GetGrantListByPI(args, :x);
PRINT x;
This is actually a failure of design. You shouldn't be using a return value for anything not a primitive for anything that is not relatively trivial.
The ideal solution should be implemented through a return parameter with a decision on reference/pointer and the proper use of a "const\'y\'ness" as a descriptor.
On top of this, you should realise that the label on an array in C and C++ is effectively a pointer and its subscription are effectively an offset or an addition symbol.
So the label or ptr array_ptr === array label thus returning foo[offset] is really saying return element at memory pointer location foo + offset of type return type.
/Users/{user}/Library/Application Support/Sublime Text 2/Packages
Get to it quickly from within Sublime via the menu at Sublime Text 2... Preferences... Browse Packages
Its very simple if you use <MediaElement>
:
<MediaElement Height="113" HorizontalAlignment="Left" Margin="12,12,0,0"
Name="mediaElement1" VerticalAlignment="Top" Width="198" Source="C:\Users\abc.gif"
LoadedBehavior="Play" Stretch="Fill" SpeedRatio="1" IsMuted="False" />
That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries()
.
I ran into this problem too, a lot of people seem to recommend force reloading your page, which won't fix the issue in cases such as if you're running it on a server. I believe the optimal solution in this scenario is to timestamp your css.
<link rel="stylesheet" href="{% static 'home/radioStyles.css' %}?{% now 'U' %}" type="text/css"/>
Where adding ?{% now 'U' %} to the end of your css file would fix this issue.
<link rel="stylesheet" type="text/css" href="style.css?Wednesday 2nd February 2020 12PM" />
Where ?Wednesday 2nd February 2020 12PM
(current date) seems to fix the issue, I also noticed just putting the time fixes it too.
We can use IF condition in SELECT query as below:
Suppose that for anything with "ABC","ABC1","ABC2","ABC3",..., we want to replace with "ABC" then using REGEXP and IF() condition in the SELECT query, we can achieve this.
Syntax:
SELECT IF(column_name REGEXP 'ABC[0-9]$','ABC',column_name)
FROM table1
WHERE column_name LIKE 'ABC%';
Example:
SELECT IF('ABC1' REGEXP 'ABC[0-9]$','ABC','ABC1');
If they are from the same table, I think UNION
is the command you're looking for.
(If you'd ever need to select values from columns of different tables, you should look at JOIN
instead...)
If you were like me, running maven compile deploy from eclipse's maven run configuration, the issue could be related to eclipse's own embedded maven as described in https://bugs.eclipse.org/bugs/show_bug.cgi?id=562847
The workaround is to run mvn compile deploy from CLI such as bash, or to NOT use embedded maven in the eclipse's maven run configuration, and add an external maven (mine is in /usr/share/mvn), and voila, it'll say BUILD SUCCESS.
I know many of the solutions mentioned above works, you can as well try flex.
But my image was rectangular and not fitting properly. so this is what i did.
.parentDivClass {
position: relative;
height: 100px;
width: 100px;
overflow: hidden;
border-radius: 50%;
margin: 20px;
display: flex;
justify-content: center;
}
and for the image inside, you can use,
child Img {
display: block;
margin: 0 auto;
height: 100%;
width: auto;
}
This is helpful when you are using bootstrap 4 classes.
The other answers all contain significant omissions.
The is
operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:
class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.
But checking for type identity with reflection checks for identity, not for compatibility
bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal
or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an
If that's not what you want, then you probably want IsAssignableFrom:
bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.
or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A
Instead of removeClass and addClass, you can also do it like this:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
Since you don't care, I chose the max ID for each number.
select tbl.* from tbl
inner join (
select max(id) as maxID, number from tbl group by number) maxID
on maxID.maxID = tbl.id
Query Explanation
select
tbl.* -- give me all the data from the base table (tbl)
from
tbl
inner join ( -- only return rows in tbl which match this subquery
select
max(id) as maxID -- MAX (ie distinct) ID per GROUP BY below
from
tbl
group by
NUMBER -- how to group rows for the MAX aggregation
) maxID
on maxID.maxID = tbl.id -- join condition ie only return rows in tbl
-- whose ID is also a MAX ID for a given NUMBER
I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
try {
env.FILENAME = readFile 'output.txt'
echo "${env.FILENAME}"
}
catch(Exception e) {
//do something, e.g. echo 'File not found'
}
}
}
}
Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()
Extrapolating from Rolando's answer above, it is these that are blocking your query:
---TRANSACTION 0 620783788, not started, process no 29956, OS thread id 1196472640
MySQL thread id 5341773, query id 189708353 10.64.89.143 viget
If you need to execute your query and can not wait for the others to run, kill them off using the MySQL thread id:
kill 5341773 <replace with your thread id>
(from within mysql, not the shell, obviously)
You have to find the thread IDs from the:
show engine innodb status\G
command, and figure out which one is the one that is blocking the database.
This also works:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))
You need to push i
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i < yearEnd+1; i++) {
arr.push(i);
}
Then, your resulting array will be:
arr = [2000, 2001, 2003, ... 2039, 2040]
Hope this helps
Try position:fixed; bottom:0;
. This will make your div to stay fixed at the bottom.
The HTML:
<div id="bottom-stuff">
<div id="search"> MY DIV </div>
</div>
<div id="bottom"> MY DIV </div>
The CSS:
#bottom-stuff {
position: relative;
}
#bottom{
position: fixed;
background:gray;
width:100%;
bottom:0;
}
#search{height:5000px; overflow-y:scroll;}
Hope this helps.
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
//find duplicates:_x000D_
//sort, then reduce - concat values equal previous element, skip others_x000D_
_x000D_
//input_x000D_
var a = [1, 2, 3, 1, 2, 1, 2]_x000D_
_x000D_
//short version:_x000D_
var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]_x000D_
_x000D_
//readable version:_x000D_
var duplicates = a.sort().reduce((output, element, index, input) => {_x000D_
if ((index > 0) && (element === input[index - 1]))_x000D_
return output.concat(element)_x000D_
return output_x000D_
}, [])_x000D_
console.log(duplicates); //[1, 1, 2, 2]
_x000D_
Some of the answers here suggest using setTimeout
to delay the process of focusing on the target element. One of them mentions that the target is inside a modal dialog. I cannot comment further on the correctness of the setTimeout
solution without knowing the specific details of where it was used. However, I thought I should provide an answer here to help out people who run into this thread just as I did
The simple fact of the matter is that you cannot focus on an element which is not yet visible. If you run into this problem ensure that the target is actually visible when the attempt to focus it is made. In my own case I was doing something along these lines
$('#elementid').animate({left:0,duration:'slow'});
$('#elementid').focus();
This did not work. I only realized what was going on when I executed $('#elementid').focus()` from the console which did work. The difference - in my code above the target there is no certainty that the target will infact be visible since the animation may not be complete. And there lies the clue
$('#elementid').animate({left:0,duration:'slow',complete:focusFunction});
function focusFunction(){$('#elementid').focus();}
works just as expected. I too had initially put in a setTimeout
solution and it worked too. However, an arbitrarily chosen timeout is bound to break the solution sooner or later depending on how slowly the host device goes about the process of ensuring that the target element is visible.
<button>
<a href="https://accounts.google.com/ServiceLogin?continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Den-ha-apac-in-bk-refresh14&service=mail&dsh=-3966619600017513905"
style="cursor:default">sign in</a>
</button>
in my case problem was in web config. I just removed
<system.web>
<hostingEnvironment shadowCopyBinAssemblies="false" />
</system.web>
git branch --set-upstream <remote-branch>
sets the default remote branch for the current local branch.
Any future git pull
command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch>
into the current local branch.
One way to avoid having to explicitly type --set-upstream
is to use its shorthand flag -u
as follows:
git push -u origin local-branch
This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.
To avoid confusion, recent versions of
git
deprecate this somewhat ambiguous--set-upstream
option in favour of a more verbose--set-upstream-to
option with identical syntax and behaviourgit branch --set-upstream-to <origin/remote-branch>
Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.
See Wikipedia for more info.
In other words, use any colour from #000000 to #FFFFFF.
edit: Dear downvoters. Check the edit history for the question first.
How about like this:
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...
Integer val = null;
while( (val = queue.poll()) != null) {
System.out.println(val);
}
The Collections.reverseOrder()
provides a Comparator
that would sort the elements in the PriorityQueue
in a the oposite order to their natural order in this case.
Just use matrix
:
matrix(vec,nrow = 7,ncol = 7)
One advantage of using matrix
rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow
argument in matrix
.
Differences between IEnumerable and IEnumerator :
Whenever we pass an IEnumerable collection to another function, it doesn't know the current position of item/object (doesn't know which item its executing)
IEnumerable have one method GetEnumerator()
public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); }
IEnumerator has one property called Current and two methods, Reset() and MoveNext() (which is useful for knowing the current position of an item in a list).
public interface IEnumerator
{
object Current { get; }
bool MoveNext();
void Reset();
}
You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.
Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.
<script type="text/javascript">
$(document).ready(function(e) {
$(".mqimg").mouseover(function()
{
$("#imgprev").animate({height: "250px",width: "70%",left: "15%"},100).html("<img src='"+$(this).attr('src')+"' width='100%' height='100%' />");
})
$(".mqimg").mouseout(function()
{
$("#imgprev").animate({height: "0px",width: "0%",left: "50%"},100);
})
});
</script>
<style>
.mqimg{ cursor:pointer;}
</style>
<div style="position:relative; width:100%; height:1px; text-align:center;">`enter code here`
<div id="imgprev" style="position:absolute; display:block; box-shadow:2px 5px 10px #333; width:70%; height:0px; background:#999; left:15%; bottom:15px; "></div>
<img class='mqimg' src='spppimages/1.jpg' height='100px' />
<img class='mqimg' src='spppimages/2.jpg' height='100px' />
<img class='mqimg' src='spppimages/3.jpg' height='100px' />
<img class='mqimg' src='spppimages/4.jpg' height='100px' />
<img class='mqimg' src='spppimages/5.jpg' height='100px' />
You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.
But your best option is to use IntList from jacarta commons. (here)
It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).
If you're only interested in the keys, you can iterate through the keySet()
of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values()
:
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet()
:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry
).
Have your tried using the 'return' keyword?
def rps():
return True
from datetime import timedelta
(any_day.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
I have personally found pywinrm
library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.
Use the values
attribute to return the values as a np array and then use [0]
to get the first value:
In [4]:
df.loc[df.Letters=='C','Letters'].values[0]
Out[4]:
'C'
EDIT
I personally prefer to access the columns using subscript operators:
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
This avoids issues where the column names can have spaces or dashes -
which mean that accessing using .
.
For INNER
joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT *
to SELECT a.*, b.*, c.*
.
For (LEFT
, RIGHT
or FULL
) OUTER
joins, yes, the order matters - and (updated) things are much more complicated.
First, outer joins are not commutative, so a LEFT JOIN b
is not the same as b LEFT JOIN a
Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
is equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
but:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
AND c.bc_id = b.bc_id
is not equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
AND b.bc_id = c.bc_id
Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c
:
a LEFT JOIN b
ON b.ab_id = a.ab_id -- AB condition
LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
This is equivalent to a LEFT JOIN (b LEFT JOIN c)
:
a LEFT JOIN
b LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
ON b.ab_id = a.ab_id -- AB condition
only because we have "nice" ON
conditions. Both ON b.ab_id = a.ab_id
and c.bc_id = b.bc_id
are equality checks and do not involve NULL
comparisons.
You can even have conditions with other operators or more complex ones like: ON a.x <= b.x
or ON a.x = 7
or ON a.x LIKE b.x
or ON (a.x, a.y) = (b.x, b.y)
and the two queries would still be equivalent.
If however, any of these involved IS NULL
or a function that is related to nulls like COALESCE()
, for example if the condition was b.ab_id IS NULL
, then the two queries would not be equivalent.
This page is a neat summary, but is not entirely accurate:
You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.
You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.
You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.
Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.
My project is now behaving as I would expect.
In Your HTML
<input type="button" name="Release" onclick="hello();" value="Click to Release" />
In Your JavaScript
<script type="text/javascript">
function hello(){
alert('Your message here');
}
</script>
If you need to run PHP in JavaScript You need to use JQuery Ajax Function
<script type="text/javascript">
function hello(){
$.ajax(
{
type: 'post',
url: 'folder/my_php_file.php',
data: '&id=' + $('#id').val() + '&name=' + $('#name').val(),
dataType: 'json',
//alert(data);
success: function(data)
{
//alert(data);
}
});
}
</script>
Now in your my_php_file.php file
<?php
echo 'hello';
?>
Good Luck !!!!!
You can wrote **_bold and italic_**
and re-style it to underlined text, like this:
strong>em,
em>strong,
b>i,
i>b {
font-style:normal;
font-weight:normal;
text-decoration:underline;
}
I think best approach until Angular team add this feature to cli is first create angular (ng new something) in other place and then add what you want to delete. Using git to check witch files are changed or added by angular cli. then you can revert that changes.
Be careful of untracked files from .gitignore
.
In your custom array adapter, you override the getView() method, as you presumably familiar with. Then all you have to do is use a switch statement or an if statement to return a certain custom View depending on the position argument passed to the getView method. Android is clever in that it will only give you a convertView of the appropriate type for your position/row; you do not need to check it is of the correct type. You can help Android with this by overriding the getItemViewType() and getViewTypeCount() methods appropriately.
Be carefull (concerning the answer just below)...That's only true because 123 is between -5 and 256...
In [111]: q = 257
In [112]: id(q)
Out[112]: 140020248465168
In [113]: w = 257
In [114]: id(w)
Out[114]: 140020274622544
In [115]: id(257)
Out[115]: 140020274622768
String.Format("0,###.###"); also works with decimal places
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.
That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.
If C wants to offer P's functionality to other companies/systems, it does so with an API.
This is an interface to P. A way for external systems to interact with P.
If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.
In purpose, though, they are actually quite distinct.
You build something with an SDK and you use or consume something with an API.
Get the router from the container.
$router = $this->get('router');
Then use the router to generate the Url
$uri = $router->generate('blog_show', array('slug' => 'my-blog-post'));
What you are looking for is Dynamic Programming.
You don't actually have to enumerate all the possible combinations for every possible values, because you can build it on top of previous answers.
You algorithm need to take 2 parameters:
[1, 5, 10, 25]
[1, 99]
And the goal is to compute the minimal set of coins required for this range.
The simplest way is to proceed in a bottom-up fashion:
Range Number of coins (in the minimal set)
1 5 10 25
[1,1] 1
[1,2] 2
[1,3] 3
[1,4] 4
[1,5] 5
[1,5]* 4 1 * two solutions here
[1,6] 4 1
[1,9] 4 1
[1,10] 5 1 * experience tells us it's not the most viable one :p
[1,10] 4 2 * not so viable either
[1,10] 4 1 1
[1,11] 4 1 1
[1,19] 4 1 1
[1,20] 5 1 1 * not viable (in the long run)
[1,20] 4 2 1 * not viable (in the long run)
[1,20] 4 1 2
It is somewhat easy, at each step we can proceed by adding at most one coin, we just need to know where. This boils down to the fact that the range [x,y]
is included in [x,y+1]
thus the minimal set for [x,y+1]
should include the minimal set for [x,y]
.
As you may have noticed though, sometimes there are indecisions, ie multiple sets have the same number of coins. In this case, it can only be decided later on which one should be discarded.
It should be possible to improve its running time, when noticing that adding a coin usually allows you to cover a far greater range that the one you added it for, I think.
For example, note that:
[1,5] 4*1 1*5
[1,9] 4*1 1*5
we add a nickel to cover [1,5]
but this gives us up to [1,9]
for free!
However, when dealing with outrageous input sets [2,3,5,10,25]
to cover [2,99]
, I am unsure as how to check quickly the range covered by the new set, or it would be actually more efficient.
I like to use a NOT EXIST
-based solution for this problem:
SELECT
id,
rev
-- you can select other columns here
FROM YourTable t
WHERE NOT EXISTS (
SELECT * FROM YourTable t WHERE t.id = id AND rev > t.rev
)
This will select all records with max value within the group and allows you to select other columns.
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
If your JAR was from a Spring-boot
project and created using the command mvn package spring-boot:repackage
, the above "-cp" method won't work. You will get:
Error: Could not find or load main class your.alternative.class.path
even if you can see the class in the JAR by jar tvf yours.jar
.
In this case, run your alternative class by the following command:
java -cp yours.jar -Dloader.main=your.alternative.class.path org.springframework.boot.loader.PropertiesLauncher
As I understood, the Spring-boot's org.springframework.boot.loader.PropertiesLauncher
class serves as a dispatching entrance class, and the -Dloader.main
parameter tells it what to run.
Reference: https://github.com/spring-projects/spring-boot/issues/20404
Be very, very aware of this problem that can occur when using utf8_general_ci
.
MySQL will not distinguish between some characters in select statements, if the utf8_general_ci
collation is used. This can lead to very nasty bugs - especially for example, where usernames are involved. Depending on the implementation that uses the database tables, this problem could allow malicious users to create a username matching an administrator account.
This problem exposes itself at the very least in early 5.x versions - I'm not sure if this behaviour as changed later.
I'm no DBA, but to avoid this problem, I always go with utf8-bin
instead of a case-insensitive one.
The script below describes the problem by example.
-- first, create a sandbox to play in
CREATE DATABASE `sandbox`;
use `sandbox`;
-- next, make sure that your client connection is of the same
-- character/collate type as the one we're going to test next:
charset utf8 collate utf8_general_ci
-- now, create the table and fill it with values
CREATE TABLE `test` (`key` VARCHAR(16), `value` VARCHAR(16) )
CHARACTER SET utf8 COLLATE utf8_general_ci;
INSERT INTO `test` VALUES ('Key ONE', 'value'), ('Key TWO', 'valúe');
-- (verify)
SELECT * FROM `test`;
-- now, expose the problem/bug:
SELECT * FROM test WHERE `value` = 'value';
--
-- Note that we get BOTH keys here! MySQLs UTF8 collates that are
-- case insensitive (ending with _ci) do not distinguish between
-- both values!
--
-- collate 'utf8_bin' doesn't have this problem, as I'll show next:
--
-- first, reset the client connection charset/collate type
charset utf8 collate utf8_bin
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Note that we get just one key now, as you'd expect.
--
-- This problem appears to be specific to utf8. Next, I'll try to
-- do the same with the 'latin1' charset:
--
-- first, reset the client connection charset/collate type
charset latin1 collate latin1_general_ci
-- next, convert the values that we've previously inserted
-- in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_general_ci;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Again, only one key is returned (expected). This shows
-- that the problem with utf8/utf8_generic_ci isn't present
-- in latin1/latin1_general_ci
--
-- To complete the example, I'll check with the binary collate
-- of latin1 as well:
-- first, reset the client connection charset/collate type
charset latin1 collate latin1_bin
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET latin1 COLLATE latin1_bin;
-- now, re-check for the bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Again, only one key is returned (expected).
--
-- Finally, I'll re-introduce the problem in the exact same
-- way (for any sceptics out there):
-- first, reset the client connection charset/collate type
charset utf8 collate utf8_generic_ci
-- next, convert the values that we've previously inserted in the table
ALTER TABLE `test` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
-- now, re-check for the problem/bug
SELECT * FROM test WHERE `value` = 'value';
--
-- Two keys.
--
DROP DATABASE sandbox;