It is really bad idea, but...
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
and then for example:
print(string3)
will give you:
Hello
However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.
Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml
@Path("/customer")
public class CustomerService {
private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();
@POST
@Path("save")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SaveResult save(Customer c) {
customers.put(c.getId(), c);
SaveResult sr = new SaveResult();
sr.sucess = true;
return sr;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Customer getCustomer(@PathParam("id") int id) {
Customer c = customers.get(id);
if (c == null) {
c = new Customer();
c.setId(id * 3);
c.setName("unknow " + id);
}
return c;
}
}
And in the pom.xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
_x000D_
document.body.onload = function () {_x000D_
var textcontrol = document.getElementById("page");_x000D_
textcontrol.style.height = (window.innerHeight) + 'px';_x000D_
}
_x000D_
<html>_x000D_
<head><title></title></head>_x000D_
<body>_x000D_
_x000D_
<div id="page" style="background:green;">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Like this.
import java.util.Date;
import java.util.GregorianCalendar;
/**
* DateDiff -- compute the difference between two dates.
*/
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
Here is an article on Java date arithmetic.
To uninstalling existing MongoDB packages. I think this link will helpful.
Use the SQLCMD utility.
http://technet.microsoft.com/en-us/library/ms162773.aspx
There is a connect statement that allows you to swing from database server A to server B in the same batch.
:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]] Connects to an instance of SQL Server. Also closes the current connection.
On the other hand, if you are familiar with PowerShell, you can programmatic do the same.
http://technet.microsoft.com/en-us/library/cc281954(v=sql.105).aspx
I feel I need to clarify one very important thing, for others (like my co-worker) who came across this thread and got the wrong information.
The answer given ("Try decimal(9,2) or decimal(10,2) or whatever.") is correct, but the reason ("increase the number of digits before the decimal") is wrong.
decimal(p,s) and numeric(p,s) both specify a Precision and a Scale. The "precision" is not the number of digits to the left of the decimal, but instead is the total precision of the number.
For example: decimal(2,1) covers 0.0 to 9.9, because the precision is 2 digits (00 to 99) and the scale is 1. decimal(4,1) covers 000.0 to 999.9 decimal(4,2) covers 00.00 to 99.99 decimal(4,3) covers 0.000 to 9.999
Matt's answer is fine, but just to avoid this to propagate to other elements inside the navbar (like when you also have a dropdown), use
.navbar-nav > li > a {
line-height: 50px;
}
Neither. You set the isolation level to READ UNCOMMITTED
which is always better than giving individual lock hints. Or, better still, if you care about details like consistency, use snapshot isolation.
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use sum()
:
>>> sum([True, True, False, False, False, True])
3
there are 600 million ticks per minute. ticksperminute
I want to update the answer for exception handling in Psr-7 Guzzle, Guzzle7 and HTTPClient(expressive, minimal API around the Guzzle HTTP client provided by laravel).
Using RequestException, RequestException catches any exception that can be thrown while transferring requests.
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->get('/foobar');
// or can use
// $guzzleResponse = $client->request('GET', '/foobar')
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// You can either use logs here use Illuminate\Support\Facades\Log;
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
//other errors
}
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', '/foo');
} catch (RequestException $e) {
$error['error'] = $e->getMessage();
$error['request'] = Psr7\Message::toString($e->getRequest());
if ($e->hasResponse()) {
$error['response'] = Psr7\Message::toString($e->getResponse());
}
Log::error('Error occurred in get request.', ['error' => $error]);
}
use Illuminate\Support\Facades\Http;
try{
$response = Http::get('http://api.foo.com');
if($response->successful()){
$reply = $response->json();
}
if($response->failed()){
if($response->clientError()){
//catch all 400 exceptions
Log::debug('client Error occurred in get request.');
$response->throw();
}
if($response->serverError()){
//catch all 500 exceptions
Log::debug('server Error occurred in get request.');
$response->throw();
}
}
}catch(Exception $e){
//catch the exception here
}
You can use the javascript in the second link provided by Ravi Khakhkhar or you are going to have to perform some string manipulation to convert your orginal string (as some of the special characters in your original format aren't being recognised as valid delimeters) but once you do that, you can use "new"
training:PRIMARY> Date()
Fri Jun 08 2012 13:53:03 GMT+0100 (IST)
training:PRIMARY> new Date()
ISODate("2012-06-08T12:53:06.831Z")
training:PRIMARY> var start = new Date("21/May/2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012 16:35:33 -0400") => works
training:PRIMARY> start
ISODate("2012-05-21T20:35:33Z")
Here's some links that you may find useful (regarding modification of the data within the mongo shell) -
http://cookbook.mongodb.org/patterns/date_range/
http://www.mongodb.org/display/DOCS/Dates
http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell
While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable))
. Using the example from @X.X:
> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)
> freq_t
gear
cyl 3 4 5
4 1 8 2
6 2 4 1
8 12 0 2
> data.frame(rbind(freq_t))
X3 X4 X5
4 1 8 2
6 2 4 1
8 12 0 2
If the column names do not start with numbers, the X
won't get added to the front of them.
I am updating a simple solution. First add an id to your segue which presents modal. Than in properties change it's presentation style to "Over Current Context". Than add this code in presenting view controller (The controller which is presenting modal).
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let Device = UIDevice.currentDevice()
let iosVersion = NSString(string: Device.systemVersion).doubleValue
let iOS8 = iosVersion >= 8
let iOS7 = iosVersion >= 7 && iosVersion < 8
if((segue.identifier == "chatTable")){
if (iOS8){
}
else {
self.navigationController?.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
}
}
}
Make sure you change segue.identifier to your own id ;)
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
try this
<div id="login_div" runat="server">
and on the code behind.
login_div.Style.Add("display", "none");
I'm not certain when this was implemented, but currently you can use http://api.jquery.com/jQuery.isNumeric/
if($('#Field').val() != "")
{
if($.isNumeric($('#Field').val()) {
errors+= "Field must be numeric.<br/>";
success = false;
}
}
You only need one INSERT:
INSERT INTO table4 ( name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
INNER JOIN table3 n ON p.Id = n.Id
With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).
We can solve this by using modulus operator (%)
26 % 7 = 5;
but 26 / 7 = 3 because it will give quotient but % operator will give remainder.
Depending on your version of Eclipse ( I am using Kepler). Go to Windows> Preferences>Android> Build.
You'll find the location path of your debug keystore as well as the SHA1 fingerprint (which you can just copy and use)
Haven't seen any fully-native solutions, so here's one:
return str == null || str.chars().allMatch(Character::isWhitespace);
Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):
return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
Or, to be really optimal (but hecka ugly):
int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;
One thing I like to do:
Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}
...
notBlank(myStr).orElse("some default")
Swift 4.2 & 5
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = Calendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date))
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents([.hour, .year, .minute], from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
Swift 3.0
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = NSCalendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date))
// *** define calendar components to use as well Timezone to UTC ***
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents(unitFlags, from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
In my case, I noticed that the routing logic was kicking in if I modified the $location.hash()
. The following trick worked..
$scope.scrollTo = function(id) {
var old = $location.hash();
$location.hash(id);
$anchorScroll();
//reset to old to keep any additional routing logic from kicking in
$location.hash(old);
};
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
You could create a function that reads an integer between 1 and 23 or returns 0 if non-int
e.g.
int getInt()
{
int n = 0;
char buffer[128];
fgets(buffer,sizeof(buffer),stdin);
n = atoi(buffer);
return ( n > 23 || n < 1 ) ? 0 : n;
}
In your Laravel deployment it would be
/vendor/laravel/framework/src/Illuminate/Foundation/Application.php
to see who changed your Laravel version look at what's defined in composer.json. If you have "laravel/framework": "5.4.*", then it will update to the latest after composer update is run. Composer.lock is the file that results from running a composer update, so really see who last one to modify the composer.json file was (hopefully you have that in version control). You can read more about it here https://getcomposer.org/doc/01-basic-usage.md
Actually, you have to use the anchor # to play with this. If you reverse engineer the Gmail url system, you'll find
https://mail.google.com/mail/u/0/#inbox
https://mail.google.com/mail/u/0/#inbox?compose=new
Everything after # is the part your want to load in your page, then you just have to chose where to load it.
By the way, using document.location by adding a #something won't refresh your page.
There is another way without Promise.all() to do it in parallel:
First, we have 2 functions to print numbers:
function printNumber1() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log("Number1 is done");
resolve(10);
},1000);
});
}
function printNumber2() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log("Number2 is done");
resolve(20);
},500);
});
}
This is sequential:
async function oneByOne() {
const number1 = await printNumber1();
const number2 = await printNumber2();
}
//Output: Number1 is done, Number2 is done
This is parallel:
async function inParallel() {
const promise1 = printNumber1();
const promise2 = printNumber2();
const number1 = await promise1;
const number2 = await promise2;
}
//Output: Number2 is done, Number1 is done
Each DOMElement.constructor returns function HTML...Element() or [Object HTML...Element] so...
function isDOM(getElem){
if(getElem===null||typeof getElem==="undefined") return false;
var c = getElem.constructor.toString();
var html = c.search("HTML")!==-1;
var element = c.search("Element")!==-1;
return html&&element;
}
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Me - nothing was helping in changing the v11.0 value of VisualStudioVersion variable to v10.0. Changing variable in .csproj file didn't. Setting it through command promt didn't. Etc...
Ended up copying my local folder of that specific version (v11.0) to my build server.
You can put a shadow behind the text, which can often help readability. Try experimenting with 50% translucent black shadows on your green text. Details on how to do this are over here: Android - shadow on text?
To really add a stroke around the text, you need to do something a bit more involved, like this: How do you draw text with a border on a MapView in Android?
That's your jQuery API problem, not your script. There is not much to worry about.
Reversing a ArrayList in a recursive way and without creating a new list for adding elements :
public class ListUtil {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
System.out.println("Reverse Order: " + reverse(arrayList));
}
public static <T> List<T> reverse(List<T> arrayList) {
return reverse(arrayList,0,arrayList.size()-1);
}
public static <T> List<T> reverse(List<T> arrayList,int startIndex,int lastIndex) {
if(startIndex<lastIndex) {
T t=arrayList.get(lastIndex);
arrayList.set(lastIndex,arrayList.get(startIndex));
arrayList.set(startIndex,t);
startIndex++;
lastIndex--;
reverse(arrayList,startIndex,lastIndex);
}
return arrayList;
}
}
If there are only two arrays to concat, and you actually need to append one of arrays rather than create a new one, push or loop is the way to go.
Benchmark: https://jsperf.com/concat-small-arrays-vs-push-vs-loop/
Workaround to pass variable like by reference:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
And yup, actually you can do it without access a global variable:
inc = (function () {
var variableName = 0;
var init = function () {
variableName += 1;
alert(variableName);
}
return init;
})();
inc();
At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)
Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.
Actual tested Solution for this.In my example I need my whole app should be in portrait mode, but only one screen's orientation should be in landscape mode.
Code in AppDelegate as above answers described.
var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
{
return self.orientationLock
}
struct AppUtility {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
Then write down this code before your landscape orientation viewcontroller will be presented/push.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
}
Then write down this code in actual viewcontroller(For landscape view)
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.landscape, andRotateTo: UIInterfaceOrientation.landscape)
}
There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses
, OpenProcess
, EnumProcessModules
, and GetModuleBaseName
.
The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot
to get a snapshot of the process list, walk over it with Process32First
and Process32Next
, which provides module name and process ID, until you find the one you want, and then call OpenProcess
to get a handle.
Try this:
(select * from T1 minus select * from T2) -- all rows that are in T1 but not in T2
union all
(select * from T2 minus select * from T1) -- all rows that are in T2 but not in T1
;
No external tool. No performance issues with union all
.
As I suggested here I recommend you roll your own. It's actually not that difficult and I suspect that's the reason there aren't better Python SOAP libraries out there.
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
In pandas 0.16.1+ you can drop columns only if they exist per the solution posted by @eiTanLaVi. Prior to that version, you can achieve the same result via a conditional list comprehension:
df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df],
axis=1, inplace=True)
It also works with Bitbucket:
pip install git+ssh://[email protected]/username/projectname.git
Pip will use your SSH keys in this case.
Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:
_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);
And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set<>. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:
private static void Main(string[] args)
{
var userProfiles = GenerateUserProfiles();
var idList = GenerateIds();
var stopWatch = new Stopwatch();
stopWatch.Start();
userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
stopWatch.Restart();
userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
Console.ReadLine();
}
private static IEnumerable<int> GenerateIds()
{
// var result = new List<int>();
for (int i = 100000; i > 0; i--)
{
yield return i;
}
}
private static IEnumerable<UserProfile> GenerateUserProfiles()
{
for (int i = 0; i < 100000; i++)
{
yield return new UserProfile {ID = i};
}
}
Console output:
Elapsed .Join time: 00:00:00.0322546
Elapsed .Where .Contains time: 00:02:19.4072107
Use the following command from Linux
find $JBOSS_HOME -name run.sh -exec {} -V \; | grep '^JBoss'
You will see it only when the file is open. When you'll close the file in Visual Studio the warnings goes away
or just study /etc/groups (ok this does probably not work if it uses pam with ldap)
Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.
csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv
Replacing 2 with the column number will effectively extract the column data you are looking for.
For Java 9 :
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.
If you work without the JSON library, maybe this will help you out:
Object.prototype.equals = function(b) {
var a = this;
for(i in a) {
if(typeof b[i] == 'undefined') {
return false;
}
if(typeof b[i] == 'object') {
if(!b[i].equals(a[i])) {
return false;
}
}
if(b[i] != a[i]) {
return false;
}
}
for(i in b) {
if(typeof a[i] == 'undefined') {
return false;
}
if(typeof a[i] == 'object') {
if(!a[i].equals(b[i])) {
return false;
}
}
if(a[i] != b[i]) {
return false;
}
}
return true;
}
var a = {foo:'bar', bar: {blub:'bla'}};
var b = {foo:'bar', bar: {blub:'blob'}};
alert(a.equals(b)); // alert's a false
I used .eslintrc.js and I have added following code.
module.exports = {
"parserOptions": {
"ecmaVersion": 6
}
};
I like the namespace better for this kind of purpose.
Option 1 :
#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
// File Name : LibConstants.hpp Purpose : Global Constants for Lib Utils
namespace LibConstants
{
const int CurlTimeOut = 0xFF; // Just some example
...
}
#endif
// source.cpp
#include <LibConstants.hpp>
int value = LibConstants::CurlTimeOut;
Option 2 :
#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
// File Name : LibConstants.hpp Purpose : Global Constants for Lib Utils
namespace CurlConstants
{
const int CurlTimeOut = 0xFF; // Just some example
...
}
namespace MySQLConstants
{
const int DBPoolSize = 0xFF; // Just some example
...
}
#endif
// source.cpp
#include <LibConstants.hpp>
int value = CurlConstants::CurlTimeOut;
int val2 = MySQLConstants::DBPoolSize;
And I would never use a Class to hold this type of HardCoded Const variables.
#!/bin/bash
read -p "Enter a directory: " BASEPATH
SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2
echo "I will create $SUBFOLD1 and $SUBFOLD2"
# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2
And if you want to use readline so you get completion and all that, add a -e
to the call to read
:
read -e -p "Enter a directory: " BASEPATH
One way to debug this (and to make sure it is the protocol violation that is causing the problem), is to use Fiddler (Http Web Proxy) and see if the same error occurs. If it doesn't (i.e. Fiddler handled the issue for you) then you should be able to fix it using the UseUnsafeHeaderParsing flag.
If you are looking for a way to set this value programatically see the examples here: http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/
If you don't want to install Java or you just want to get started writing queries quickly, then use SQL*Plus, which is the command line too.
It's not pretty, but will get you started quickly and there is Oracle documentation on it.
a = if true then 5 else 10
a = if false then 5 else 10
See documentation.
You can use the following code.
public static class TimeSpanExtensions
{
public static String Verbose(this TimeSpan timeSpan)
{
var hours = timeSpan.Hours;
var minutes = timeSpan.Minutes;
if (hours > 0) return String.Format("{0} hours {1} minutes", hours, minutes);
return String.Format("{0} minutes", minutes);
}
}
I have always wanted Visual Studio to include an option to just collapse / expand the regions. I have the following macros which will do just that.
Imports EnvDTE
Imports System.Diagnostics
' Macros for improving keyboard support for "#region ... #endregion"
Public Module CollapseExpandRegions
' Expands all regions in the current document
Sub ExpandAllRegions()
Dim objSelection As TextSelection ' Our selection object
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.StartOfDocument() ' Shoot to the start of the document
' Loop through the document finding all instances of #region. This action has the side benefit
' of actually zooming us to the text in question when it is found and ALSO expanding it since it
' is an outline.
Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
' This next command would be what we would normally do *IF* the find operation didn't do it for us.
'DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
Loop
objSelection.StartOfDocument() ' Shoot us back to the start of the document
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
' Collapses all regions in the current document
Sub CollapseAllRegions()
Dim objSelection As TextSelection ' Our selection object
ExpandAllRegions() ' Force the expansion of all regions
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.EndOfDocument() ' Shoot to the end of the document
' Find the first occurence of #region from the end of the document to the start of the document. Note:
' Note: Once a #region is "collapsed" .FindText only sees it's "textual descriptor" unless
' vsFindOptions.vsFindOptionsMatchInHiddenText is specified. So when a #region "My Class" is collapsed,
' .FindText would subsequently see the text 'My Class' instead of '#region "My Class"' for the subsequent
' passes and skip any regions already collapsed.
Do While (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards))
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion") ' Collapse this #region
'objSelection.EndOfDocument() ' Shoot back to the end of the document for
' another pass.
Loop
objSelection.StartOfDocument() ' All done, head back to the start of the doc
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
End Module
EDIT: There is now a shortcut called Edit.ToggleOutliningExpansion (Ctrl+M, Ctrl+M) for doing just that.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
If you just want to execute the shell command in your c program, you could use,
#include <stdlib.h>
int system(const char *command);
In your case,
system("pwd");
The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.
What do you mean by this? You should be able to find the mentioned packages in /bin/
sudo find / -executable -name pwd
sudo find / -executable -name echo
# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)
Explanation. All dataframes are lists and the results of [
used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply
. The above assignment will create a set of lists that the function data.frame.[<-
should successfully stick back into into the dataframe, df
Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:
cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)
Am I missing something in the question or why else nobody mentioned reviver
parameter of JSON.parse
since 2011?
Here is simplistic code for solution that works: https://jsfiddle.net/Ldr2utrr/
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse(`{"a":4, "b": 3}`, function(key,value){
if(key!=="") return value; //logic of course should be more complex for handling nested objects etc.
let res = new Foo();
res.a = value.a;
res.b = value.b;
return res;
});
// Here you already get Foo object back
alert(fooJSON.test() ); //Prints 12
PS: Your question is confusing: >>That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)? contradicts to the title, where you ask about JSON parsing, but the quoted paragraph asks about JS runtime object prototype replacement.
One of the biggest problems with delivering live events on Internet is 'scale', and TCP doesn’t scale well. For example when you are beaming a live football match -as opposed to an on demand movie playback- the number of people watching can easily be 1000 times more. In such a scenario using TCP is a death sentence for the CDNs (content delivery networks).
There are a couple of main reasons why TCP doesn't scale well:
One of the largest tradeoffs of TCP is the variability of throughput achievable between the sender and the receiver. When streaming video over the Internet the video packets must traverse multiple routers over the Internet, each of these routers is connected with different speed connections. The TCP algorithm starts with TCP window off small, then grows until packet loss is detected, the packet loss is considered a sign of congestion and TCP responds to it by drastically reducing the window size to avoid congestion. Thus in turn reducing the effective throughput immediately. Now imagine a network with TCP transmission using 6-7 router hops to the client (a very normal scenario), if any of the intermediate router looses any packet, the TCP for that link will reduce the transmission rate. In-fact The traffic flow between routers follow an hourglass kind of a shape; always gong up and down in-between one of the intermediate routers. Rendering the effective through put much lower compared to best-effort UDP.
As you may already know TCP is an acknowledgement-based protocol. Lets for example say a sender is 50ms away (i.e. latency btw two points). This would mean time it takes for a packet to be sent to a receiver and receiver to send an acknowledgement would be 100ms; thus maximum throughput possible as compared to UDP based transmission is already halved.
The TCP doesn’t support multicasting or the new emerging standard of multicasting AMT. Which means the CDNs don’t have the opportunity to reduce network traffic by replicating the packets -when many clients are watching the same content. That itself is a big enough reason for CDNs (like Akamai or Level3) to not go with TCP for live streams.
So does C99.
The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).
All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.
just use \xb0 (in a string);
python will convert it automatically
Use to_datetime
, there is no need for a format string the parser is man/woman enough to handle it:
In [51]:
pd.to_datetime(df['I_DATE'])
Out[51]:
0 2012-03-28 14:15:00
1 2012-03-28 14:17:28
2 2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]
To access the date/day/time component use the dt
accessor:
In [54]:
df['I_DATE'].dt.date
Out[54]:
0 2012-03-28
1 2012-03-28
2 2012-03-28
dtype: object
In [56]:
df['I_DATE'].dt.time
Out[56]:
0 14:15:00
1 14:17:28
2 14:50:50
dtype: object
You can use strings to filter as an example:
In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]
Out[59]:
date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09
I offen manage css/js plugin with composer which install it under vendor. I symlink those to the web/bundles directory, that's let composer update bundles as needed.
exemple:
1 - symlink once at all (use command fromweb/bundles/
ln -sf vendor/select2/select2/dist/ select2
2 - use asset where needed, in twig template :
{{ asset('bundles/select2/css/fileinput.css) }}
Regards.
You need formulas to convert latitude and longitude to rectangular coordinates. There are a great number to choose from and each will distort the map in a different way. Wolfram MathWorld has a good collection:
http://mathworld.wolfram.com/MapProjection.html
Follow the "See Also" links.
The easier solution for me was:
Considerations:
DrawerItem
, CustomDrawerAdapter
and layout custom_drawer_item.xml
were taken from this tutorial.1. Create this class for wrap the custom drawer item:
public class DrawerItem {
String ItemName;
int imgResID;
public DrawerItem(String itemName, int imgResID) {
super();
ItemName = itemName;
this.imgResID = imgResID;
}
public String getItemName() {
return ItemName;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
public int getImgResID() {
return imgResID;
}
public void setImgResID(int imgResID) {
this.imgResID = imgResID;
}
}
2. Create custom layout (custom_drawer_item.xml) for your drawer items:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/itemLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="vertical"
android:layout_marginTop="0dp"
android:background="?android:attr/activatedBackgroundIndicator">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="55dp">
<ImageView
android:id="@+id/drawer_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/drawer_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="1dp"
android:layout_marginTop="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#DADADC">
</View>
</LinearLayout>
</RelativeLayout>
3. Create your custom adapter:
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {
Context context;
List<DrawerItem> drawerItemList;
int layoutResID;
public CustomDrawerAdapter(Context context, int layoutResourceID, List<DrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
DrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new DrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView)view.findViewById(R.id.drawer_itemName);
drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
view.setTag(drawerHolder);
} else {
drawerHolder = (DrawerItemHolder) view.getTag();
}
DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
dItem.getImgResID()));
drawerHolder.ItemName.setText(dItem.getItemName());
return view;
}
private static class DrawerItemHolder {
TextView ItemName;
ImageView icon;
}
}
4. In autogenerated NavigationDrawerFragment
class onCreateView
method, replace the autogenerated adapter for this:
ArrayList<DrawerItem> dataList = new ArrayList<DrawerItem>();
dataList.add(new DrawerItem(getString(R.string.title_section1), R.drawable.ic_action_1));
dataList.add(new DrawerItem(getString(R.string.title_section2), R.drawable.ic_action_2));
dataList.add(new DrawerItem(getString(R.string.title_section3), R.drawable.ic_action_3));
mDrawerListView.setAdapter(new CustomDrawerAdapter(
getActivity(),
R.layout.custom_drawer_item,
dataList));
Remember replace R.string.title_sectionN
and R.drawable.ic_action_N
for your own resources.
The JAX-WS way for basic authentication is
Service s = new Service();
Port port = s.getPort();
BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
port.call();
I've got some subprojects.
I solved this problem via adding xib file to Copy Bundle Resources build phase of main project.
You can use one of this two options:
1) Add data-dismiss to the submit button i.e.
<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>
2) Do it in JS like
$('#frmStudent').submit(function() {
$('#StudentModal').modal('hide');
});
Building a HashMap of these objects based on the field value as a key could be worthwhile from the performance perspective, e.g. populate Maps once and find objects very efficiently
android:inputMethod
is deprecated, instead use inputType
:
android:inputType="numberPassword"
//To select name of employee whose salary is second highest
SELECT name
FROM employee WHERE salary =
(SELECT MIN(salary) FROM
(SELECT TOP (2) salary
FROM employee
ORDER BY salary DESC) )
Testing this Javascript:
var arr = [1234563995.721, 12345691212.718, 1234568421.5891, 12345677093.49284];
var sum = 0;
for( var i = 0; i < arr.length; i++ ) {
sum += arr[i];
}
alert( "fMath(sum) = " + Math.round( sum * 1e12 ) / 1e12 );
alert( "fFixed(sum) = " + sum.toFixed( 5 ) );
Dont use Math.round( (## + ## + ... + ##) * 1e12) / 1e12
Instead, use ( ## + ## + ... + ##).toFixed(5) )
In IE 9, toFixed
works very well.
public class Book
{
public int number;
public String title;
public String language;
public int price;
// Add constructor, get, set, as needed.
}
then declare your array as:
Book[] books = new Book[3];
EDIT: In response to O.P.'s confusion, Book should be an object, not an array. Each book should be created on it's own (via a properly designed constructor) and then added to the array. In fact, I wouldn't use an array, but an ArrayList. In other words, you are trying to force data into containers that aren't suitable for the task at hand.
I would venture that 50% of programming is choosing the right data structure for your data. Algorithms naturally follow if there is a good choice of structure.
When properly done, you get your UI class to look like: Edit: Generics added to the following code snippet.
...
ArrayList<Book> myLibrary = new ArrayList<Book>();
myLibrary.add(new Book(1, "Thinking In Java", "English", 4999));
myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);
etc.
now you can use the Collections interface and do something like:
int total = 0;
for (Book b : myLibrary)
{
total += b.price;
System.out.println(b); // Assuming a valid toString in the Book class
}
System.out.println("The total value of your library is " + total);
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
Use the following command at command prompt:
java -jar jenkins.war --httpPort=9090
If you want to use https use the following command:
java -jar jenkins.war --httpsPort=9090
Details are here
You must run git fetch
before you can compare your local repository against the files on your remote server.
This command only updates your remote tracking branches and will not affect your worktree until you call git merge
or git pull
.
To see the difference between your local branch and your remote tracking branch once you've fetched you can use git diff or git cherry as explained here.
You also want to say, that strings in your code are utf-8. See Why does modern Perl avoid UTF-8 by default?. So set not only PERL_UNICODE=SDAL
but also PERL5OPT=-Mutf8
.
The value of st
at st = datetime.strptime(st, '%A %d %B')
line something like 01 01 2013 02:05
and the strptime
can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M
at your strptime.
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
There are cases when you want to restart a specific container instead of deleting the pod and letting Kubernetes recreate it.
Doing a kubectl exec POD_NAME -c CONTAINER_NAME /sbin/killall5
worked for me.
(I changed the command from reboot
to /sbin/killall5
based on the below recommendations.)
If you are using JPA to hibernate make sure the Entity has the correct data type for a field defined against a date column like use java.util.Date instead of String.
You could use setInterval
for this.
<script type="text/javascript">
function myFunction () {
console.log('Executed!');
}
var interval = setInterval(function () { myFunction(); }, 60000);
</script>
Disable the timer by setting clearInterval(interval)
.
See this Fiddle: http://jsfiddle.net/p6NJt/2/
There seems to be a confusion about the declaration.
When strategy
comes before {RANDOM, IMMEDIATE, SEARCH}
as in the following,
enum strategy {RANDOM, IMMEDIATE, SEARCH};
you are creating a new type named enum strategy
. However, when declaring the variable, you need to use enum strategy
itself. You cannot just use strategy
. So the following is invalid.
enum strategy {RANDOM, IMMEDIATE, SEARCH};
strategy a;
While, the following is valid
enum strategy {RANDOM, IMMEDIATE, SEARCH};
enum strategy queen = RANDOM;
enum strategy king = SEARCH;
enum strategy pawn[100];
When strategy
comes after {RANDOM, IMMEDIATE, SEARCH}
, you are creating an anonymous enum and then declaring strategy
to be a variable of that type.
So now, you can do something like
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = RANDOM;
However, you cannot declare any other variable of type enum {RANDOM, IMMEDIATE, SEARCH}
because you have never named it. So the following is invalid
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
enum strategy a = RANDOM;
You can combine both the definitions too
enum strategy {RANDOM, IMMEDIATE, SEARCH} a, b;
a = RANDOM;
b = SEARCH;
enum strategy c = IMMEDIATE;
Typedef
as noted before is used for creating a shorter variable declaration.
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;
Now you have told compiler that enum {RANDOM, IMMEDIATE, SEARCH}
is synonomous to strategy
. So now you can freely use strategy
as variable type. You don't need to type enum strategy
anymore. The following is valid now
strategy x = RANDOM;
You can also combine Typedef along with enum name to get
typedef enum strategyName {RANDOM, IMMEDIATE, SEARCH} strategy;
There's not much advantage of using this method apart from the fact that you can now use strategy
and enum strategyName
interchangeably.
typedef enum strategyName {RANDOM, IMMEDIATE, SEARCH} strategy;
enum strategyName a = RANDOM;
strategy b = SEARCH;
curl_getinfo
— Get information regarding a specific transfer
Check curl_getinfo
<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}
// Close handle
curl_close($ch);
The official support page should answer your question.
So in your .gitignore
you might ignore the files ending with .iws
, and the workspace.xml
and tasks.xml
files.
setTimeout(() => { // your code here }, 0);
I wrapped my code in setTimeout and it worked
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
Try this :
val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = sdf.format(Date())
System.out.println(" C DATE is "+currentDate)
Sort by picture and then by activity:
SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;
The simple way I use is
app.controller("Back2Square1Controller", function($scope, $location) {
window.location.assign(basePath + "/index.html");
});
Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information - Yes you can actually do, List list = new List(); But at the cost of writing implementations of all the methods of Interfaces. The notion is not simply List list = new List(); but
List<Integer> list = new List<Integer>(){
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
..... and So on (Cant write all methods.)
This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.
You are exceeding the length of int datatype. You can use UNSIGNED attribute to support that value.
SIGNED INT can support till 2147483647 and with UNSIGNED INT allows double than this. After this you still want to save data than use CHAR or VARCHAR with length 10
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
I need to select every production with a category that doesn't contain "Business"
Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as
//production[category[not(contains(., 'Business'))]]
rather than
//production[not(contains(category, 'Business'))]
The latter selects every production whose first category
child doesn't contain "Business". The two XPath expressions will behave differently when a production
has no category
children, or more than one.
It doesn't make any difference in practice as long as every <production>
has exactly one <category>
child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').
Inspired by Steve answer, I wrote simple function that toggles between vertical and horizontal splits for all windows in current tab. You can bind it to mapping like in the last line below.
function! ToggleWindowHorizontalVerticalSplit()
if !exists('t:splitType')
let t:splitType = 'vertical'
endif
if t:splitType == 'vertical' " is vertical switch to horizontal
windo wincmd K
let t:splitType = 'horizontal'
else " is horizontal switch to vertical
windo wincmd H
let t:splitType = 'vertical'
endif
endfunction
nnoremap <silent> <leader>wt :call ToggleWindowHorizontalVerticalSplit()<cr>
Straight out of the documentation for collections.OrderedDict
:
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
Adapted to the example in the original post:
>>> l=[2,3,1,4,5]
>>> OrderedDict(sorted(enumerate(l), key=lambda x: x[1])).keys()
[2, 0, 1, 3, 4]
See http://docs.python.org/library/collections.html#collections.OrderedDict for details.
If someone works with IBM Rational Application Developer then XSD browser is built in it.
It looks like you need a MySQL server installed, there is install packages on mysql's site, or you can install through macports (I assume from the darwin11 line). I installed mine via ports, and the socket lives in /opt/local/var/run/mysql5/.
If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
then just create a Util object
Util u = new Util();
and have something for the return System.out.println( u.flip(bool) );
If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)
['LS', 'TO', 'VBN', "''", 'WP', 'UH', 'VBG', 'JJ', 'VBZ', '--', 'VBP', 'NN', 'DT', 'PRP', ':', 'WP$', 'NNPS', 'PRP$', 'WDT', '(', ')', '.', ',', '``', '$', 'RB', 'RBR', 'RBS', 'VBD', 'IN', 'FW', 'RP', 'JJR', 'JJS', 'PDT', 'MD', 'VB', 'WRB', 'NNP', 'EX', 'NNS', 'SYM', 'CC', 'CD', 'POS']
Based on Doug Shore's method but make it more copy-paste friendly
You can continue using WebClient to POST (instead of GET, which is the HTTP verb you're currently using with DownloadString), but I think you'll find it easier to work with the (slightly) lower-level classes WebRequest and WebResponse.
There are two parts to this - the first is to post the login form, the second is recovering the "Set-cookie" header and sending that back to the server as "Cookie" along with your GET request. The server will use this cookie to identify you from now on (assuming it's using cookie-based authentication which I'm fairly confident it is as that page returns a Set-cookie header which includes "PHPSESSID").
POSTing to the login form
Form posts are easy to simulate, it's just a case of formatting your post data as follows:
field1=value1&field2=value2
Using WebRequest and code I adapted from Scott Hanselman, here's how you'd POST form data to your login form:
string formUrl = "http://www.mmoinn.com/index.do?PageModule=UsersAction&Action=UsersLogin"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
string formParams = string.Format("email_address={0}&password={1}", "your email", "your password");
string cookieHeader;
WebRequest req = WebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
WebResponse resp = req.GetResponse();
cookieHeader = resp.Headers["Set-cookie"];
Here's an example of what you should see in the Set-cookie header for your login form:
PHPSESSID=c4812cffcf2c45e0357a5a93c137642e; path=/; domain=.mmoinn.com,wowmine_referer=directenter; path=/; domain=.mmoinn.com,lang=en; path=/;domain=.mmoinn.com,adt_usertype=other,adt_host=-
GETting the page behind the login form
Now you can perform your GET request to a page that you need to be logged in for.
string pageSource;
string getUrl = "the url of the page behind the login";
WebRequest getRequest = WebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
WebResponse getResponse = getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
EDIT:
If you need to view the results of the first POST, you can recover the HTML it returned with:
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
Place this directly below cookieHeader = resp.Headers["Set-cookie"];
and then inspect the string held in pageSource.
I use with (nolock) hint particularly in SQLServer 2000 databases with high activity. I am not certain that it is needed in SQL Server 2005 however. I recently added that hint in a SQL Server 2000 at the request of the client's DBA, because he was noticing a lot of SPID record locks.
All I can say is that using the hint has NOT hurt us and appears to have made the locking problem solve itself. The DBA at that particular client basically insisted that we use the hint.
By the way, the databases I deal with are back-ends to enterprise medical claims systems, so we are talking about millions of records and 20+ tables in many joins. I typically add a WITH (nolock) hint for each table in the join (unless it is a derived table, in which case you can't use that particular hint)
Sounds like you probably want a simple method like this:
public String getValueOrDefault(String value, String defaultValue) {
return isNotNullOrEmpty(value) ? value : defaultValue;
}
Then:
String result = getValueOrDefault(System.getProperty("XYZ"), "default");
At this point, you don't need temp
... you've effectively used the method parameter as a way of initializing the temporary variable.
If you really want temp
and you don't want an extra method, you can do it in one statement, but I really wouldn't:
public class Test {
public static void main(String[] args) {
String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
System.out.println("result: " + result);
System.out.println("temp: " + temp);
}
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
}
A simple example loading images into the tiles.
import 'package:flutter/material.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white30,
child: GridView.count(
crossAxisCount: 4,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: <String>[
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
].map((String url) {
return GridTile(
child: Image.network(url, fit: BoxFit.cover));
}).toList()),
);
}
}
The Flutter Gallery app contains a real world example, which can be found here.
You have a parent element, you want to get all child of specific attribute
1. get the parent
2. get the parent nodename by using parent.nodeName.toLowerCase()
convert the nodename to lower case e.g DIV will be div
3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id")
. this will give you id
of the parent
4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " );
if you want input children of the parent node
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
parent_clas_arr.forEach(e=>{_x000D_
parent_clas_str +=e+'.';_x000D_
})_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1) //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
It seems to work:
substring_index ( substring_index ( context,',',1 ), ',', -1)
substring_index ( substring_index ( context,',',2 ), ',', -1)
substring_index ( substring_index ( context,',',3 ), ',', -1)
substring_index ( substring_index ( context,',',4 ), ',', -1)
it means 1st value, 2nd, 3rd, etc.
The inner substring_index
returns the first n values that are comma separated. So if your original string is "34,7,23,89", substring_index( context,',', 3)
returns "34,7,23".
The outer substring_index
takes the value returned by the inner substring_index
and the -1
allows you to take the last value. So you get "23" from the "34,7,23".
Instead of -1
if you specify -2
, you'll get "7,23", because it took the last two values.
select * from MyTable where substring_index(substring_index(prices,',',1),',',-1)=3382;
Here, prices
is the name of a column in MyTable
.
To detect both positive and negative peaks, PeakDetect is helpful.
from peakdetect import peakdetect
peaks = peakdetect(data, lookahead=20)
# Lookahead is the distance to look ahead from a peak to determine if it is the actual peak.
# Change lookahead as necessary
higherPeaks = np.array(peaks[0])
lowerPeaks = np.array(peaks[1])
plt.plot(data)
plt.plot(higherPeaks[:,0], higherPeaks[:,1], 'ro')
plt.plot(lowerPeaks[:,0], lowerPeaks[:,1], 'ko')
Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.
Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:
public interface IMyApi
{
IList<int> GetReadOnlyValues();
}
public class MyApiImplementation : IMyApi
{
public IList<int> GetReadOnlyValues()
{
List<int> myList = new List<int>();
... populate list
return myList.AsReadOnly();
}
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
public IList<int> GetReadOnlyValues()
{
IList<int> testValues = new int[] { 1, 2, 3 };
return testValues;
}
}
You can do that with a single statement and a subquery in nearly all relational databases.
INSERT INTO targetTable(field1)
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))
Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE
syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE
syntax.
Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
A very easy kind of event you can wait for is the ManualResetEvent
, and even better, the ManualResetEventSlim
.
They have a WaitOne()
method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).
You fire them calling Set()
.
Here is the doc.
You can do exactly that via the various sizeWithFont:
methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):
NSString *someString = @"Hello World";
UIFont *yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];
There are several variations of this method, eg. some consider line break modes or maximum sizes.
Looks like you use %p: Print Pointers
I'm late, but:
BufferReader.java:
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
(...)
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
In case it helps, I've ran into this problem when passing null
into a parameter for a generic TValue
, to get around this you have to cast your null values:
(string)null
(int)null
etc.
setting the img to display:inline-block while having set the superior div to text-align:center will do the job too
EDIT: to those folks who are playing with display:inline-block >>> don't forget that e.g. two divs like
<div>Div1 content</div>NOSPACEHERE<div>Div2 content</div>
really have no spaces between them (as seen here).
Just basic to avoid these (inline block inherent) gaps between them. These gaps can be seen between every two words I'm writing right now! :-) So .. hope this helps some of you.
You can also use DB::unprepared
for ALTER TABLE
queries.
DB::unprepared
is meant to be used for queries like CREATE TRIGGER
. But essentially it executes raw sql queries directly. (without using PDO prepared
statements)
If they all have the same extension (for example .jpg), you can use this:
for picture in *.jpg ; do
echo "the next file is $picture"
done
(This solution also works if the filename has spaces)
check the above image(static directory) for dir structure
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
// or
app.use("/", express.static(publicDirectoryPath))
app.use((req, res, next) => {
res.sendFile(path.join(publicDirectoryPath,'index.html'))
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
Pure Virtual Function
try this code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()=0;
};
class anotherClass:aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"hellow World";
}
};
int main()
{
//aClassWithPureVirtualFunction virtualObject;
/*
This not possible to create object of a class that contain pure virtual function
*/
anotherClass object;
object.sayHellow();
}
In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.
Virtual function
try another code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()
{
cout<<"from base\n";
}
};
class anotherClass:public aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"from derived \n";
}
};
int main()
{
aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
baseObject->sayHellow();///call base one
baseObject=new anotherClass;
baseObject->sayHellow();////call the derived one!
}
Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks
To avoid duplicate rows for some columns, use user_type_id instead of system_type_id.
SELECT
c.name 'Column Name',
t.Name 'Data type',
c.max_length 'Max Length',
c.precision ,
c.scale ,
c.is_nullable,
ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('YourTableName')
Just replace YourTableName
with your actual table name - works for SQL Server 2005 and up.
In case you are using schemas, replace YourTableName
by YourSchemaName.YourTableName
where YourSchemaName
is the actual schema name and YourTableName
is the actual table name.
What also works and is even nicer for long, multiline texts, is putting your text indented on the next line, after a pipe or greater-than sign:
text: >
Op dit plein stond het hoofdkantoor van de NIROM: Nederlands Indische
Radio Omroep
A pipe preserves newlines, a gt-sign turns all the following lines into one long string.
if you really want an array instead you can use:
$getvidids->result_array()
which would return the same information as an associative array.
Perhaps unintentional, but moving my docker file to the solution folder instead of the project eliminated the error. This was helpful when I still wanted to run the solution independently of docker
If you're using the variable result:
result = result == "true";
startActivity(new Intent(this, Katra_home.class));
try this one it will be work
The array you created by Dim s(0) As String
IS NOT EMPTY
In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.
You should instead try using System.Collections.Specialized.StringCollection
or (even better) System.Collections.Generic.List(Of String)
. They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.
If you really want an empty string array, declare it like this:
Dim s As String()
or
Dim t() As String
See these answers:
Connecting to wi-fi using adb shell
However, I'm pretty sure that Google actually stores your email and password (at the time of saving to the device) for times like these. So when it needs to be unlocked, it won't require an internet connection.
I could be wrong. Either way, when I had this issue, I had internet connectivity, and I knew my username and password and it didn't care, kept saying they were wrong (even though I was logging into my email). Had to format the phone at the time!
Good luck.
To support SDK version >= 26, you also should build NotificationChanel and set a vibration pattern and sound there. There is a Kotlin code sample:
val vibrationPattern = longArrayOf(500)
val soundUri = "<your sound uri>"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val attr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
val channelName: CharSequence = Constants.NOTIFICATION_CHANNEL_NAME
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel =
NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, channelName, importance)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationChannel.setSound(soundUri, attr)
notificationChannel.vibrationPattern = vibrationPattern
notificationManager.createNotificationChannel(notificationChannel)
}
And this is the builder:
with(NotificationCompat.Builder(applicationContext, Constants.NOTIFICATION_CHANNEL_ID)) {
setContentTitle("Some title")
setContentText("Some content")
setSmallIcon(R.drawable.ic_logo)
setAutoCancel(true)
setVibrate(vibrationPattern)
setSound(soundUri)
setDefaults(Notification.DEFAULT_VIBRATE)
setContentIntent(
// this is an extension function of context you should build
// your own pending intent and place it here
createNotificationPendingIntent(
Intent(applicationContext, target).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
)
)
return build()
}
Be sure your AudioAttributes
are chosen right to read more here.
I encountered this as well and the solution is simple, dont hardcode the array index position in your code.
Instead of
$data[0]['somekey']
do
foreach($data as $data_item)
{
echo $data_item['somekey'];
}
If there is an array or more you can perform your desired action inside the loop, but if it's undefined it will not bring an error. you can also add other checks on top of that.
You could also add a variable and increment it in a for in loop to limit your looping if you want only the first positions or something.
New to python so I don't know if this is advisable, but it works great for not re-writing boilerplate.
Your project must have an init.py so it can be loaded as a module
# Put this in your module's __init__.py
import logging.config
import sys
# I used this dictionary test, you would put:
# logging.config.fileConfig('logging.conf')
# The "" entry in loggers is the root logger, tutorials always
# use "root" but I can't get that to work
logging.config.dictConfig({
"version": 1,
"formatters": {
"default": {
"format": "%(asctime)s %(levelname)s %(name)s %(message)s"
},
},
"handlers": {
"console": {
"level": 'DEBUG',
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"": {
"level": "DEBUG",
"handlers": ["console"]
}
}
})
def logger():
# Get the name from the caller of this function
return logging.getLogger(sys._getframe(1).f_globals['__name__'])
sys._getframe(1)
suggestion comes from here
Then to use your logger in any other file:
from [your module name here] import logger
logger().debug("FOOOOOOOOO!!!")
Caveats:
import [your module]
won't work:
python -m [your module name].[your filename without .py]
__main__
, but any solution using __name__
will have that issue.$product->get_categories()
is deprecated since version 3.0! Use wc_get_product_category_list
instead.
https://docs.woocommerce.com/wc-apidocs/function-wc_get_product_category_list.html
SET SCAN OFF is obsolete http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm
In addition to Nick's answer about Xcode 4.2, you may also need to review your info.plist file. It seems as if new projects started in Xcode 4.2 by default specify 'armv7' in the 'Required Device Capabilities'. You'll need to remove this if wanting to support devices that run armv6 (e.g. the iPhone 3G).
Delete armv7 from the 'Required device capabilities' in yourProjectName-Info.plist
sometime you missed some file like I missed my one file rt.java
so better to check yours .........
C:\Program Files\Java\jdk1.8.0_112\jre\lib
Actually, em.flush()
, do more than just sends the cached SQL commands. It tries to synchronize the persistence context to the underlying database. It can cause a lot of time consumption on your processes if your cache contains collections to be synchronized.
Caution on using it.
You can use filter
in the Java 8 Stream
library
List<String> aList = List.of("l","e","t","'","s");
List<String> bList = List.of("g","o","e","s","t");
List<String> difference = aList.stream()
.filter(aObject -> {
return ! bList.contains(aObject);
})
.collect(Collectors.toList());
//more reduced: no curly braces, no return
List<String> difference2 = aList.stream()
.filter(aObject -> ! bList.contains(aObject))
.collect(Collectors.toList());
Result of System.out.println(difference);
:
[e, t, s]
I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on type hinting.
In a nutshell: Type hinting is literally what the words mean. You hint the type of the object(s) you're using.
Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard. This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs (PyCharm and PyDev come to mind) that are limited due to the fact that they don't have any indicator of what type the objects are. As a result they resort to trying to infer the type with (as mentioned in the presentation) around 50% success rate.
To take two important slides from the type hinting presentation:
TypeErrors
..
and having methods/attributes pop up which aren't defined for an object.As a closing note for this small introduction: This is an optional feature and, from what I understand, it has been introduced in order to reap some of the benefits of static typing.
You generally do not need to worry about it and definitely don't need to use it (especially in cases where you use Python as an auxiliary scripting language). It should be helpful when developing large projects as it offers much needed robustness, control and additional debugging capabilities.
In order to make this answer more complete, I think a little demonstration would be suitable. I'll be using mypy
, the library which inspired Type Hints as they are presented in the PEP. This is mainly written for anybody bumping into this question and wondering where to begin.
Before I do that let me reiterate the following: PEP 484 doesn't enforce anything; it is simply setting a direction for function annotations and proposing guidelines for how type checking can/should be performed. You can annotate your functions and hint as many things as you want; your scripts will still run regardless of the presence of annotations because Python itself doesn't use them.
Anyways, as noted in the PEP, hinting types should generally take three forms:
# type: type
comments that complement the first two forms. (See: What are variable annotations? for a Python 3.6 update for # type: type
comments)Additionally, you'll want to use type hints in conjunction with the new typing
module introduced in Py3.5
. In it, many (additional) ABCs (abstract base classes) are defined along with helper functions and decorators for use in static checking. Most ABCs in collections.abc
are included, but in a generic form in order to allow subscription (by defining a __getitem__()
method).
For anyone interested in a more in-depth explanation of these, the mypy documentation
is written very nicely and has a lot of code samples demonstrating/describing the functionality of their checker; it is definitely worth a read.
First, it's interesting to observe some of the behavior we can get when using special comments. Special # type: type
comments
can be added during variable assignments to indicate the type of an object if one cannot be directly inferred. Simple assignments are
generally easily inferred but others, like lists (with regard to their contents), cannot.
Note: If we want to use any derivative of containers and need to specify the contents for that container we must use the generic types from the typing
module. These support indexing.
# Generic List, supports indexing.
from typing import List
# In this case, the type is easily inferred as type: int.
i = 0
# Even though the type can be inferred as of type list
# there is no way to know the contents of this list.
# By using type: List[str] we indicate we want to use a list of strings.
a = [] # type: List[str]
# Appending an int to our list
# is statically not correct.
a.append(i)
# Appending a string is fine.
a.append("i")
print(a) # [0, 'i']
If we add these commands to a file and execute them with our interpreter, everything works just fine and print(a)
just prints
the contents of list a
. The # type
comments have been discarded, treated as plain comments which have no additional semantic meaning.
By running this with mypy
, on the other hand, we get the following response:
(Python3)jimmi@jim: mypy typeHintsCode.py
typesInline.py:14: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
Indicating that a list of str
objects cannot contain an int
, which, statically speaking, is sound. This can be fixed by either abiding to the type of a
and only appending str
objects or by changing the type of the contents of a
to indicate that any value is acceptable (Intuitively performed with List[Any]
after Any
has been imported from typing
).
Function annotations are added in the form param_name : type
after each parameter in your function signature and a return type is specified using the -> type
notation before the ending function colon; all annotations are stored in the __annotations__
attribute for that function in a handy dictionary form. Using a trivial example (which doesn't require extra types from the typing
module):
def annotated(x: int, y: str) -> bool:
return x < y
The annotated.__annotations__
attribute now has the following values:
{'y': <class 'str'>, 'return': <class 'bool'>, 'x': <class 'int'>}
If we're a complete newbie, or we are familiar with Python 2.7 concepts and are consequently unaware of the TypeError
lurking in the comparison of annotated
, we can perform another static check, catch the error and save us some trouble:
(Python3)jimmi@jim: mypy typeHintsCode.py
typeFunction.py: note: In function "annotated":
typeFunction.py:2: error: Unsupported operand types for > ("str" and "int")
Among other things, calling the function with invalid arguments will also get caught:
annotated(20, 20)
# mypy complains:
typeHintsCode.py:4: error: Argument 2 to "annotated" has incompatible type "int"; expected "str"
These can be extended to basically any use case and the errors caught extend further than basic calls and operations. The types you
can check for are really flexible and I have merely given a small sneak peak of its potential. A look in the typing
module, the
PEPs or the mypy
documentation will give you a more comprehensive idea of the capabilities offered.
Stub files can be used in two different non mutually exclusive cases:
What stub files (with an extension of .pyi
) are is an annotated interface of the module you are making/want to use. They contain
the signatures of the functions you want to type-check with the body of the functions discarded. To get a feel of this, given a set
of three random functions in a module named randfunc.py
:
def message(s):
print(s)
def alterContents(myIterable):
return [i for i in myIterable if i % 2 == 0]
def combine(messageFunc, itFunc):
messageFunc("Printing the Iterable")
a = alterContents(range(1, 20))
return set(a)
We can create a stub file randfunc.pyi
, in which we can place some restrictions if we wish to do so. The downside is that
somebody viewing the source without the stub won't really get that annotation assistance when trying to understand what is supposed
to be passed where.
Anyway, the structure of a stub file is pretty simplistic: Add all function definitions with empty bodies (pass
filled) and
supply the annotations based on your requirements. Here, let's assume we only want to work with int
types for our Containers.
# Stub for randfucn.py
from typing import Iterable, List, Set, Callable
def message(s: str) -> None: pass
def alterContents(myIterable: Iterable[int])-> List[int]: pass
def combine(
messageFunc: Callable[[str], Any],
itFunc: Callable[[Iterable[int]], List[int]]
)-> Set[int]: pass
The combine
function gives an indication of why you might want to use annotations in a different file, they some times clutter up
the code and reduce readability (big no-no for Python). You could of course use type aliases but that sometime confuses more than it
helps (so use them wisely).
This should get you familiarized with the basic concepts of type hints in Python. Even though the type checker used has been
mypy
you should gradually start to see more of them pop-up, some internally in IDEs (PyCharm,) and others as standard Python modules.
I'll try and add additional checkers/related packages in the following list when and if I find them (or if suggested).
Checkers I know of:
Related Packages/Projects:
The typeshed
project is actually one of the best places you can look to see how type hinting might be used in a project of your own. Let's take as an example the __init__
dunders of the Counter
class in the corresponding .pyi
file:
class Counter(Dict[_T, int], Generic[_T]):
@overload
def __init__(self) -> None: ...
@overload
def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
@overload
def __init__(self, iterable: Iterable[_T]) -> None: ...
Where _T = TypeVar('_T')
is used to define generic classes. For the Counter
class we can see that it can either take no arguments in its initializer, get a single Mapping
from any type to an int
or take an Iterable
of any type.
Notice: One thing I forgot to mention was that the typing
module has been introduced on a provisional basis. From PEP 411:
A provisional package may have its API modified prior to "graduating" into a "stable" state. On one hand, this state provides the package with the benefits of being formally part of the Python distribution. On the other hand, the core development team explicitly states that no promises are made with regards to the the stability of the package's API, which may change for the next release. While it is considered an unlikely outcome, such packages may even be removed from the standard library without a deprecation period if the concerns regarding their API or maintenance prove well-founded.
So take things here with a pinch of salt; I'm doubtful it will be removed or altered in significant ways, but one can never know.
** Another topic altogether, but valid in the scope of type-hints: PEP 526
: Syntax for Variable Annotations is an effort to replace # type
comments by introducing new syntax which allows users to annotate the type of variables in simple varname: type
statements.
See What are variable annotations?, as previously mentioned, for a small introduction to these.
One way is by creating a FullScreenActivity/EmptyActivity (say SplashScreenActivity) and set it as the first Activity that shows up when you open your app. Add the following to your Activity in the AndroidManifest.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
You can then set a handler to dismiss this activity after a few seconds.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i= new Intent(SplashScreenActivity.this,MainActivity.class);
startActivity(i); //start new activity
finish();
}
}, 3000); //time in milliseconds
Secondly, if you don't wish to create a separate activity, you can inflate a layout over your MainActivity
and set the layout visibility to GONE
or inflate the main layout over the existing splash screen layout after a few milliseconds.
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class.
HttpClient.PostAsJsonAsync("http://Server/WebService/Controller/ServiceMethod?number=" + number + "&name" + name, Tuple.Create(args1, args2, args3, args4));
[HttpPost]
[Route("ServiceMethod")]
[ResponseType(typeof(void))]
public IHttpActionResult ServiceMethod(int number, string name, Tuple<Class1, Class2, Class3, Class4> args)
{
Class1 c1 = (Class1)args.Item1;
Class2 c2 = (Class2)args.Item2;
Class3 c3 = (Class3)args.Item3;
Class4 c4 = (Class4)args.Item4;
/* do your actions */
return Ok();
}
No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.
You need to use IFS to stop space as element delimiter.
FILES=("2011-09-04 21.43.02.jpg"
"2011-09-05 10.23.14.jpg"
"2011-09-09 12.31.16.jpg"
"2011-09-11 08.43.12.jpg")
IFS=""
for jpg in ${FILES[*]}
do
echo "${jpg}"
done
If you want to separate on basis of . then just do IFS="." Hope it helps you:)
The below code is working,
<style>
.PanelFloat {
position: fixed;
overflow: hidden;
z-index: 2400;
opacity: 0.70;
right: 30px;
top: 0px !important;
-webkit-transition: all 0.5s ease-in-out;
-moz-transition: all 0.5s ease-in-out;
-ms-transition: all 0.5s ease-in-out;
-o-transition: all 0.5s ease-in-out;
transition: all 0.5s ease-in-out;
}
</style>
<script>
//The below script will keep the panel float on normal state
$(function () {
$(document).on('scroll', function () {
//Multiplication value shall be changed based on user window
$('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
});
});
//To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
$(document).on('click', '.btnSearchView', function () {
$('#MyFloatPanel').addClass('PanelFloat');
});
$(document).on('click', '.btnSearchClose', function () {
$('#MyFloatPanel').removeClass('PanelFloat');
});
</script>
<div class="col-lg-12 col-md-12">
<div class="col-lg-8 col-md-8" >
//My scrollable content is here
</div>
//This below panel will float while scrolling the above div content
<div class="col-lg-4 col-md-4" id="MyFloatPanel">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">Panel Head </div>
<div class="panel-body ">//Your panel content</div>
</div>
</div>
</div>
</div>
you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
.myDiv {
background-color: red;
width: 100%;
min-height: 100vh;
max-height: 100%;
position: absolute;
top: 0;
left: 0;
margin: 0 auto;
}
Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.
Since C++11, there's a safe alternative to new[]
and delete[]
which is zero-overhead unlike std::vector
:
std::unique_ptr<int[]> array(new int[size]);
In C++14:
auto array = std::make_unique<int[]>(size);
Both of the above rely on the same header file, #include <memory>
If you are deliberately displaying it for the end user, wrap the JSON text in <PRE>
and <CODE>
tags, e.g.:
<html>
<body>
<pre>
<code>
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
</code>
</pre>
</body>
</html>
Otherwise I would use JSON Viewer.
slice
works just fine in IE and other browsers, it's part of the specification and it's the most efficient method too:
alert("xxx_456".slice(-3));
//-> 456
slice Method (String) - MSDN
slice - Mozilla Developer Center
That is so basic that I am wondering what book you are using to study? Try
data[1, "V1"] # row first, quoted column name second, and case does matter
Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.
I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html
From the command line, enter this:
php -f filename.php
Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.
Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).
Reference: https://secure.php.net/manual/en/features.commandline.usage.php
UPDATE
Angular offers now the two scope methods $watchGroup (since 1.3) and $watchCollection. Those have been mentioned by @blazemonger and @kargold.
This should work independent of the types and values:
$scope.$watch('[age,name]', function () { ... }, true);
You have to set the third parameter to true in this case.
The string concatenation 'age + name'
will fail in a case like this:
<button ng-init="age=42;name='foo'" ng-click="age=4;name='2foo'">click</button>
Before the user clicks the button the watched value would be 42foo
(42
+ foo
) and after the click 42foo
(4
+ 2foo
). So the watch function would not be called. So better use an array expression if you cannot ensure, that such a case will not appear.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet" />
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="//cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular-mocks.js"></script>
<script>
angular.module('demo', []).controller('MainCtrl', function ($scope) {
$scope.firstWatchFunctionCounter = 0;
$scope.secondWatchFunctionCounter = 0;
$scope.$watch('[age, name]', function () { $scope.firstWatchFunctionCounter++; }, true);
$scope.$watch('age + name', function () { $scope.secondWatchFunctionCounter++; });
});
describe('Demo module', function () {
beforeEach(module('demo'));
describe('MainCtrl', function () {
it('watch function should increment a counter', inject(function ($controller, $rootScope) {
var scope = $rootScope.$new();
scope.age = 42;
scope.name = 'foo';
var ctrl = $controller('MainCtrl', { '$scope': scope });
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(1);
expect(scope.secondWatchFunctionCounter).toBe(1);
scope.age = 4;
scope.name = '2foo';
scope.$digest();
expect(scope.firstWatchFunctionCounter).toBe(2);
expect(scope.secondWatchFunctionCounter).toBe(2); // This will fail!
}));
});
});
(function () {
var jasmineEnv = jasmine.getEnv();
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body></body>
</html>
http://plnkr.co/edit/2DwCOftQTltWFbEDiDlA?p=preview
PS:
As stated by @reblace in a comment, it is of course possible to access the values:
$scope.$watch('[age,name]', function (newValue, oldValue) {
var newAge = newValue[0];
var newName = newValue[1];
var oldAge = oldValue[0];
var oldName = oldValue[1];
}, true);
A "REST service" and a "RESTful service" are one and the same.
A RESTful system is any system that follows the REST conventions as defined in the original document that created the idea of RESTful networked applications.
It's worth noting there are varying levels of RESTfulness. Overall, REST is a style, not a standard, so there is room for interpretation based on needs. one example is hierarchical resource URLs (e.g. /things/ID/relatedthings
) vs flat URLs (e.g. /things/ID
and /relatedthings?thing=ID
)
This is old question but still my answer may help someone
For checking Java version in android studio version , simply open Terminal of Android Studio and type
java -version
This will display java version installed in android studio
If you want to validate your date(YYYY-MM-DD)
along with the comparison it will be use full for you...
function validateDate()
{
var newDate = new Date();
var presentDate = newDate.getDate();
var presentMonth = newDate.getMonth();
var presentYear = newDate.getFullYear();
var dateOfBirthVal = document.forms[0].dateOfBirth.value;
if (dateOfBirthVal == null)
return false;
var validatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
dateValues = dateOfBirthVal.match(validatePattern);
if (dateValues == null)
{
alert("Date of birth should be null and it should in the format of yyyy-mm-dd")
return false;
}
var birthYear = dateValues[1];
birthMonth = dateValues[3];
birthDate= dateValues[5];
if ((birthMonth < 1) || (birthMonth > 12))
{
alert("Invalid date")
return false;
}
else if ((birthDate < 1) || (birthDate> 31))
{
alert("Invalid date")
return false;
}
else if ((birthMonth==4 || birthMonth==6 || birthMonth==9 || birthMonth==11) && birthDate ==31)
{
alert("Invalid date")
return false;
}
else if (birthMonth == 2){
var isleap = (birthYear % 4 == 0 && (birthYear % 100 != 0 || birthYear % 400 == 0));
if (birthDate> 29 || (birthDate ==29 && !isleap))
{
alert("Invalid date")
return false;
}
}
else if((birthYear>presentYear)||(birthYear+70<presentYear))
{
alert("Invalid date")
return false;
}
else if(birthYear==presentYear)
{
if(birthMonth>presentMonth+1)
{
alert("Invalid date")
return false;
}
else if(birthMonth==presentMonth+1)
{
if(birthDate>presentDate)
{
alert("Invalid date")
return false;
}
}
}
return true;
}
Prism's InvokeCommandAction
will pass the event args by default if CommandParameter
is not set.
Here is an example. Note the use of prism:InvokeCommandAction
instead of i:InvokeCommandAction
.
<i:Interaction.Triggers>
<i:EventTrigger EventName="Sorting">
<prism:InvokeCommandAction Command="{Binding SortingCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
The ViewModel
private DelegateCommand<EventArgs> _sortingCommand;
public DelegateCommand<EventArgs> SortingCommand => _sortingCommand ?? (_sortingCommand = new DelegateCommand<EventArgs>(OnSortingCommand));
private void OnSortingCommand(EventArgs obj)
{
//do stuff
}
There is a new version of the Prismlibrary documentation.
Try this:
Use back-ticks for NAME
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`addr` varchar(255) NOT NULL,
`phone` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
You could also use the php native funcion get_browser()
IMPORTANT NOTE: You should have a browscap.ini file.
Use regular expression no need to convert it to char array
if(Regex.IsMatch("yourString",".*?[a-zA-Z].*?"))
{
errorCounter++;
}
I found this question after seeing the 'more than one device' error, with 2 offline phones showing:
C:\Program Files (x86)\Android\android-sdk\android-tools>adb devices
List of devices attached
SH436WM01785 offline
SH436WM01785 offline
SH436WM01785 sideload
If you only have one device connected, run the following commands to get rid of the offline connections:
adb kill-server
adb devices
New in Matplotlib v3.4 (not available in pip yet, clone from source)
supxlabel, supylabel
See example:
import matplotlib.pyplot as plt
for tl, cl in zip([True, False, False], [False, False, True]):
fig = plt.figure(constrained_layout=cl, tight_layout=tl)
gs = fig.add_gridspec(2, 3)
ax = dict()
ax['A'] = fig.add_subplot(gs[0, 0:2])
ax['B'] = fig.add_subplot(gs[1, 0:2])
ax['C'] = fig.add_subplot(gs[:, 2])
ax['C'].set_xlabel('Booger')
ax['B'].set_xlabel('Booger')
ax['A'].set_ylabel('Booger Y')
fig.suptitle(f'TEST: tight_layout={tl} constrained_layout={cl}')
fig.supxlabel('XLAgg')
fig.supylabel('YLAgg')
plt.show()
I think you cant remove column names, only reset them by range
with shape
:
print df.shape[1]
2
print range(df.shape[1])
[0, 1]
df.columns = range(df.shape[1])
print df
0 1
0 23 12
1 21 44
2 98 21
This is same as using to_csv
and read_csv
:
print df.to_csv(header=None,index=False)
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
0 1
0 23 12
1 21 44
2 98 21
Next solution with skiprows
:
print df.to_csv(index=False)
A,B
23,12
21,44
98,21
print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
0 1
0 23 12
1 21 44
2 98 21
You can use DataBinding and ViewModel for Switch Checked Change event
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.example.ui.ViewModel" />
</data>
<Switch
android:id="@+id/on_off_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onCheckedChanged="@{(button, on) -> viewModel.onCheckedChange(on)}"
/>
You can use this utility:
c:\Windows\system32\fsutil.exe create hardlink
Try an LL
suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See http://gcc.gnu.org/onlinedocs/gcc/Long-Long.html
long long int i2 = 0x0000444400004444LL;
Additionally, the the compiler is discarding the leading zeros, so 0x000044440000
is becoming 0x44440000
, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2
).
I didn't try all these. I restarted by laptop/machine . And everything was back to normal after that.
Just include this script
http://code.jquery.com/jquery-migrate-1.0.0.js
after you include your jquery javascript file.
try
lstCountry.SelectedItem.Text
Here is the solution:
show full processlist;
to get the process id with status and query itself which causes the database hanging;KILL <pid>;
to kill that process.Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:
Select concat('KILL ',id,';') from information_schema.processlist where user='user';
to print all processes with KILL
command;|
sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.You can use that style of comment across multiple lines (which exists also in HTML)
<detail>
<band height="20">
<!--
Hello,
I am a multi-line XML comment
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
-->
</band>
</detail>
Running JMeter in command line mode:
1.Navigate to JMeter’s bin directory
Now enter following command,
jmeter -n –t test.jmx
-n: specifies JMeter is to run in non-gui mode
-t: specifies name of JMX file that contains the Test Plan
always make sure to have set your default timezone
date_default_timezone_set('Europe/Berlin');
create DateTime instance, holding the current datetime
$datetime = new DateTime();
create one day interval
$interval = new DateInterval('P1D');
modify the DateTime instance
$datetime->sub($interval);
display the result, or print_r($datetime);
for more insight
echo $datetime->format('Y-m-d');
TIP:
If you don't want to change the default timezone, use the DateTimeZone
class instead.
$myTimezone = new DateTimeZone('Europe/Berlin');
$datetime->setTimezone($myTimezone);
or just include it inside the constructor in this form new DateTime("now", $myTimezone);
Not possible, I believe ie has a content changed event but it is certainly not x-browser
Should I say not possible without some nasty interval chugging away in the background!
You can create a class in Typescript as follows:
export class coordinate {
static x: number;
static y: number;
static gradient() {
return y/x;
}
}
and reference it's properties and methods "without" instantiation so:
coordinate.x = 10;
coordinate.y = 10;
console.log(`x of ${coordinate.x} and y of ${coordinate.y} has gradient of ${coordinate.gradient()}`);
Fyi using backticks `` in conjunction with interpolation syntax ${} allows ease in mixing code with text :-)
It's available many, many places, depending upon what is installed: On my box, every one except the v6.0A SDK version supports the /fd option.
Every method in Web API will return data (JSON) without serialization.
However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.
According to pip documentation at
http://pip.readthedocs.org/en/stable/user_guide/#configuration
You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows
On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf
On Windows, the configuration file is: %HOME%\pip\pip.ini
The %HOME% is located in C:\Users\Bob
on windows assuming your name is Bob
On linux the $HOME
directory can be located by using cd ~
You may have to create the pip.ini
file when you find your pip directory. Within your pip.ini
or pip.config
you will then need to put (assuming your on windows) something like
[global]
target=C:\Users\Bob\Desktop
Except that you would replace C:\Users\Bob\Desktop
with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path
After saving the command would then be
pip install pandas
However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.
You can always wrap Double.parseDouble() in a try catch block.
try
{
Double.parseDouble(number);
}
catch(NumberFormatException e)
{
//not a double
}
Alternatively, if you want to specify expected parameters in action signature, but pass them as arbitrary GET
arguments. Use filters, for example:
Create a route without parameters:
$Route::get('/history', ['uses'=>'ExampleController@history']);
Specify action with two parameters and attach the filter:
class ExampleController extends BaseController
{
public function __construct($browser)
{
$this->beforeFilter('filterDates', array(
'only' => array('history')
));
}
public function history($fromDate, $toDate)
{
/* ... */
}
}
Filter that translates GET
into action's arguments :
Route::filter('filterDates', function($route, Request $request) {
$notSpecified = '_';
$fromDate = $request->get('fromDate', $notSpecified);
$toDate = $request->get('toDate', $notSpecified);
$route->setParameter('fromDate', $fromDate);
$route->setParameter('toDate', $toDate);
});
The truly terrible way to do it is to execute each INSERT
statement as its own batch:
Batch 1:
INSERT INTO Entries (id, name) VALUES (1, 'Ian Boyd);
Batch 2:
INSERT INTO Entries (id, name) VALUES (2, 'Bottlenecked);
Batch 3:
INSERT INTO Entries (id, name) VALUES (3, 'Marek Grzenkowicz);
Batch 4:
INSERT INTO Entries (id, name) VALUES (4, 'Giorgi);
Batch 5:
INSERT INTO Entries (id, name) VALUES (5, 'AMissico);
Note: Parameterization, error checking, and any other nit-picks elided for expoistory purposes.
This is truly, horrible, terrible way to do things. It gives truely awful performance, because you suffer the network round-trip-time every time.
A much better solution is to batch all the INSERT
statements into one batch:
Batch 1:
INSERT INTO Entries (id, name) VALUES (1, 'Ian Boyd');
INSERT INTO Entries (id, name) VALUES (2, 'Bottlenecked');
INSERT INTO Entries (id, name) VALUES (3, 'Marek Grzenkowicz');
INSERT INTO Entries (id, name) VALUES (4, 'Giorgi');
INSERT INTO Entries (id, name) VALUES (5, 'AMissico');
This way you only suffer one-round trip. This version has huge performance wins; on the order of 5x faster.
Even better is to use the VALUES
clause:
INSERT INTO Entries (id, name)
VALUES
(1, 'Ian Boyd'),
(2, 'Bottlenecked'),
(3, 'Marek Grzenkowicz'),
(4, 'Giorgi'),
(5, 'AMissico');
This gives you some performance improvements over the 5 separate INSERT
s version; it lets the server do what it's good at: operating on sets:
SQL Sever loves to operate on sets of data; it's where it's a viking!
The above T-SQL examples have all the parameteriztion stuff removed for clarity. But in reality you want to parameterize queries
But Bruno has an important point; SQL Server's driver only lets you include 2,100 parameters in a batch. The above query has two values:
@id, @name
If you import 1,051 rows in a single batch, that's 2,102 parameters - you'll get the error:
Too many parameters were provided in this RPC request
That is why i generally insert 5 or 10 rows at a time. Adding more rows per batch doesn't improve performance that much - there's diminishing returns.
It keeps the number of parameters low, it doesn't get anywhere near the T-SQL batch size limit. There's also the fact that a VALUES
clause is limited to 1000 tuples anyway.
Your first approach is good, but you do have the issues of:
So the goal is to generate a string such as:
INSERT INTO Entries (id, name) VALUES
(@p1, @p2),
(@p3, @p4),
(@p5, @p6),
(@p7, @p8),
(@p9, @p10)
I'll change your code by the seat of my pants
IEnumerable<Entry> entries = GetStuffToInsert();
SqlCommand cmd = new SqlCommand();
StringBuilder sql = new StringBuilder();
Int32 batchSize = 0; //how many rows we have build up so far
Int32 p = 1; //the current paramter name (i.e. "@p1") we're going to use
foreach(var entry in entries)
{
//Build the names of the parameters
String pId = String.Format("@p{0}", p); //the "Id" parameter name (i.e. "p1")
String pName = String.Format("@p{0}", p+1); //the "Name" parameter name (i.e. "p2")
p += 2;
//Build a single "(p1, p2)" row
String row = String.Format("({0}, {1})", pId, pName); //a single values tuple
//Add the row to our running SQL batch
if (batchSize > 0)
sb.AppendLine(",");
sb.Append(row);
batchSize += 1;
//Add the parameter values for this row
cmd.Parameters.Add(pID, System.Data.SqlDbType.Int ).Value = entry.Id;
cmd.Parameters.Add(pName, System.Data.SqlDbType.String).Value = entry.Name;
if (batchSize >= 5)
{
String sql = "INSERT INTO Entries (id, name) VALUES"+"\r\n"+
sb.ToString();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
sb.Clear();
batchSize = 0;
p = 1;
}
}
//handle the last few stragglers
if (batchSize > 0)
{
String sql = "INSERT INTO Entries (id, name) VALUES"+"\r\n"+
sb.ToString();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
My problem was similar but I overcame me without keeping the fragment alive. Suppose you have an activity that has 2 fragments - F1 and F2. F1 is started initially and lets say in contains some user info and then upon some condition F2 pops on asking user to fill in additional attribute - their phone number. Next, you want that phone number to pop back to F1 and complete signup but you realize all previous user info is lost and you don't have their previous data. The fragment is recreated from scratch and even if you saved this information in onSaveInstanceState
the bundle comes back null in onActivityCreated
.
Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
// this will be null the first time F1 is created.
// it will be populated once you replace fragment and provide bundle data
if (args != null) {
if (args.get("your_info") != null) {
// do what you want with restored information
}
}
}
So following on with my example: before I display F2 I save user data in the instance variable using a callback. Then I start F2, user fills in phone number and presses save. I use another callback in activity, collect this information and replace my fragment F1, this time it has bundle data that I can use.
@Override
public void onPhoneAdded(String phone) {
//replace fragment
F1 f1 = new F1 ();
Bundle args = new Bundle();
yourInfo.setPhone(phone);
args.putSerializable("you_info", yourInfo);
f1.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, f1).addToBackStack(null).commit();
}
}
More information about callbacks can be found here: https://developer.android.com/training/basics/fragments/communicating.html
You can set the fontsize directly in the call to set_xticklabels
and set_yticklabels
(as noted in previous answers). This will only affect one Axes
at a time.
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
You can also set the ticklabel
font size globally (i.e. for all figures/subplots in a script) using rcParams
:
import matplotlib.pyplot as plt
plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)
Or, equivalently:
plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8
Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams
in your matplotlibrc
file:
xtick.labelsize : 8 # fontsize of the x tick labels
ytick.labelsize : 8 # fontsize of the y tick labels
Just use com.google.common.io.Resources class. Example:
URL url = Resources.getResource("file name")
After that you have methods like: .getContent(), .getFile(), .getPath() etc
Using only the keyboard at least for Windows 10:
Despite the fact that this question has been asked long time ago but I feel a comprehensive description would clarify why there is no need to use public abstract before methods and public static final before constants of an interface.
First of all Interfaces are used to specify common methods for a set of unrelated classes for which every class will have a unique implementation. Therefore it is not possible to specify the access modifier as private since it cannot be accessed by other classes to be overridden.
Second, Although one can initiate objects of an interface type but an interface is realized by the classes which implement it and not inherited. And since an interface might be implemented (realized) by different unrelated classes which are not in the same package therefore protected access modifier is not valid as well. So for the access modifier we are only left with public choice.
Third, an interface does not have any data implementation including the instance variables and methods. If there is logical reason to insert implemented methods or instance variables in an interface then it must be a superclass in an inheritance hierarchy and not an interface. Considering this fact, since no method can be implemented in an interface therefore all the methods in interface must be abstract.
Fourth, Interface can only include constant as its data members which means they must be final and of course final constants are declared as static to keep only one instance of them. Therefore static final also is a must for interface constants.
So in conclusion although using public abstract before methods and public static final before constants of an interface is valid but since there is no other options it is considered redundant and not used.