NSArray *array = mutableArray;
This [mutableArray copy]
antipattern is all over sample code. Stop doing so for throwaway mutable arrays that are transient and get deallocated at the end of the current scope.
There is no way the runtime could optimize out the wasteful copying of a mutable array that is just about to go out of scope, decrefed to 0 and deallocated for good.
Please! check below simple step by step tutorial to understand how Delegates works in iOS.
I have created two ViewControllers (for sending data from one to another)
Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.
iPhone format strings are in Unicode format. Behind the link is a table explaining what all the letters above mean so you can build your own.
And of course don't forget to release your date formatters when you're done with them. The above code leaks format
, now
, and inFormat
.
This is how you should initialize the NSString
:
Swift 2.X or older
let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)
Swift 3 or newer:
let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)
This doc explains the syntax.
Because you are asking the compiler to initialize a static variable with code that is inherently dynamic.
Using Apple's Reachability code, I created a function that'll check this correctly without you having to include any classes.
Include the SystemConfiguration.framework in your project.
Make some imports:
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
Now just call this function:
/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
*/
+(BOOL)hasConnectivity {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if (reachability != NULL) {
//NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// If target host is not reachable
return NO;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// If target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
return YES;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs.
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
return YES;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
return YES;
}
}
}
return NO;
}
And it's iOS 5 tested for you.
It's convenient to define a macro for get current timestamp
class Constant {
struct Time {
let now = { round(NSDate().timeIntervalSince1970) } // seconds
}
}
Then you can use let timestamp = Constant.Time.now()
Regarding [NSException raise:format:]
. For those coming from a Java background, you will recall that Java distinguishes between Exception and RuntimeException. Exception is a checked exception, and RuntimeException is unchecked. In particular, Java suggests using checked exceptions for "normal error conditions" and unchecked exceptions for "runtime errors caused by a programmer error." It seems that Objective-C exceptions should be used in the same places you would use an unchecked exception, and error code return values or NSError values are preferred in places where you would use a checked exception.
I found ${PODS_HEADERS_SEARCH_PATHS}
is missing and it is not defined in my develop git branch, So I added "$(SRCROOT)/Pods/Headers/"
for Header Search Paths with recursive
That is ok for me
NOTE: Under Xcode 4 this is now built into the IDE.
You use the Clang Static Analyzer to -- unsurprisingly -- analyse your C and Objective-C code (no C++ yet) on Mac OS X 10.5. It's trivial to install and use:
cd
to your project directory.scan-build -k -V xcodebuild
.(There are some additional constraints etc., in particular you should analyze a project in its "Debug" configuration -- see http://clang.llvm.org/StaticAnalysisUsage.html for details -- the but that's more-or-less what it boils down to.)
The analyser then produces a set of web pages for you that shows likely memory management and other basic problems that the compiler is unable to detect.
Probably not exactly your issue..
Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments
sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_xxx", referenced from: objc-class-ref in yyy.o
This generally means, you are calling "xxx" (it may be a framework or class) from the class "yyy". The compiler can not locate the "xxx" so this error occurs.
You need to add the missing files(in this case "xxx") by right click on your project folder in navigator window and tap on "Add files to "YourProjectName"" option.
A popup window will open your project files in Finder. There, you can see the missing files and just add them to your project. Don't forget to check the "Copy items if needed" box. Good luck!!
Add each
method in your NSArray category
, you gonna need it a lot
Code taken from ObjectiveSugar
- (void)each:(void (^)(id object))block {
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
block(obj);
}];
}
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
[Try this solution it's simple] You can create a static variable in a Swift class then call it from any Objective-C class.
Make sure you have the latest version of CocoaPods installed. $ pod update POD
was introduced recently.
See this issue thread for more information:
$ pod update
When you run
pod update SomePodName
, CocoaPods will try to find an updated version of the pod SomePodName, without taking into account the version listed inPodfile.lock
. It will update the pod to the latest version possible (as long as it matches the version restrictions in your Podfile).If you run pod update without any pod name, CocoaPods will update every pod listed in your Podfile to the latest version possible.
there are a couple of ways of using a timer:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:NO];
As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:
[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:@selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}
Since Stack Overflow’s broken RSS just resurrected this question for me, here’s my almost-general solution: JAValueToString
This lets you write JA_DUMP(cgPoint)
and get cgPoint = {0, 0}
logged.
page-break-inside: avoid; definitely does not work in webkit, in fact has been a known issue for 5+ years now https://bugs.webkit.org/show_bug.cgi?id=5097
As far as my research has gone, there is no known method to accomplish this (I am working on figuring out my own hack)
The advice I can give you is, to accomplish this functionality in FF, wrap the content that you don;t want to break ever inside a DIV (or any container) with overflow: auto (just be careful not to cause weird scroll bars to show up by sizing the container too small).
Sadly, FF is the only browser I managed to accomplish this in, and webkit is the one I am more worried about.
I've taken DLog
and ALog
from above, and added ULog
which raises a UIAlertView
message.
To summarize:
DLog
will output like NSLog
only when the DEBUG variable is set ALog
will always output like NSLog
ULog
will show the UIAlertView
only when the DEBUG variable is set
#ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif #define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #ifdef DEBUG # define ULog(fmt, ...) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } #else # define ULog(...) #endif
This is what it looks like:
+1 Diederik
In Cocoa, to compare dates, use one of isEqualToDate
, compare
, laterDate
, and earlierDate
methods on NSDate
objects, instantiated with the dates you need.
Documentation:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare:
One way of doing it is to draw the image to a bitmap context that is backed by a given buffer for a given colorspace (in this case it is RGB): (note that this will copy the image data to that buffer, so you do want to cache it instead of doing this operation every time you need to get pixel values)
See below as a sample:
// First get the image into your data buffer
CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
You could use blocks?
@implementation MyClass
id (^createTheObject)() = ^(){ return [[NSObject alloc] init];};
NSInteger (^addEm)(NSInteger, NSInteger) =
^(NSInteger a, NSInteger b)
{
return a + b;
};
//public methods, etc.
- (NSObject) thePublicOne
{
return createTheObject();
}
@end
I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this.
I won't pretend to be an expert on the topic, but you should have access to both the glob
and wordexp
function from objective-c, no?
The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex
contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex:
to delete the last character correctly.
DO NOT USE THIS ANSWER. I HAVE ONLY LEFT IT FOR HISTORICAL PURPOSES. SEE THE COMMENTS BELOW.
There is a simple trick if it is a BOOL parameter.
Pass nil for NO and self for YES. nil is cast to the BOOL value of NO. self is cast to the BOOL value of YES.
This approach breaks down if it is anything other than a BOOL parameter.
Assuming self is a UIView.
//nil will be cast to NO when the selector is performed
[self performSelector:@selector(setHidden:) withObject:nil afterDelay:5.0];
//self will be cast to YES when the selector is performed
[self performSelector:@selector(setHidden:) withObject:self afterDelay:10.0];
If you want to read space separated string, and immediately split the string into an array, you can do this:
var arr = readLine()!.characters.split(" ").map(String.init)
eg.
print("What is your full name?")
var arr = readLine()!.characters.split(" ").map(String.init)
var firstName = ""
var middleName = ""
var lastName = ""
if arr.count > 0 {
firstName = arr[0]
}
if arr.count > 2 {
middleName = arr[1]
lastName = arr[2]
} else if arr.count > 1 {
lastName = arr[1]
}
print("First Name: \(firstName)")
print("Middle Name: \(middleName)")
print("Last Name: \(lastName)")
NSPredicate
is nextstep's way of constructing condition to filter a collection (NSArray
, NSSet
, NSDictionary
).
For example consider two arrays arr
and filteredarr
:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"];
filteredarr = [NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
the filteredarr will surely have the items that contains the character c alone.
to make it easy to remember those who little sql background it is
*--select * from tbl where column1 like '%a%'--*
1)select * from tbl --> collection
2)column1 like '%a%' --> NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",@"c"];
3)select * from tbl where column1 like '%a%' -->
[NSMutableArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
I hope this helps
The accepted (and correct) answer says that "you can include this [Constants.h] file... in the pre-compiled header for the project."
As a novice, I had difficulty doing this without further explanation -- here's how: In your YourAppNameHere-Prefix.pch file (this is the default name for the precompiled header in Xcode), import your Constants.h inside the #ifdef __OBJC__
block.
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Constants.h"
#endif
Also note that the Constants.h and Constants.m files should contain absolutely nothing else in them except what is described in the accepted answer. (No interface or implementation).
I had the same issue when I was using the main storyboard as the launch screen file. I guess if you are using a storyboard as the launch screen file, it shouldn't be connected to the view controller as it won't have been loaded yet.
I'm not sure about the circumstances where you need to convert an NSInteger
to an int
.
NSInteger is just a typedef:
NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
You can use NSInteger
any place you use an int
without converting it.
I encountered this same problem today. As suggested in this answer, the problem was an unclean xib. In my case the unclean xib was the result of updating a xib that was being loaded by something other than the view controller it was associated with.
Xcode let me create and populate a new outlet and connected it to the file's owner even though I explicitly connected it to the source of the correct view controller. Here's the code generated by Xcode:
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="LoginViewController"]]>
<connections>
<outlet property="hostLabel" destination="W4x-T2-Mcm" id="c3E-1U-sVf"/>
</connections>
</placeholder>
When I ran my app it crashed with the same not key value coding-compliant
error. To correct the problem, I removed the outlet from the File's Owner in Interface Builder and connected it explicitly to the view controller object on the left outline instead of to the code in the assistant editor.
There is also good old POSIX system("echo -en '\007'");
I added the file Under Build Phase in Targets and the issue got resolved. For the steps to add the file, see my answer at:
This is an example scenario, where we need @class.
Consider if you wish to create a protocol within header file, which has a parameter with data type of the same class, then you can use @class. Please do remember that you can also declare protocols separately, this is just an example.
// DroneSearchField.h
#import <UIKit/UIKit.h>
@class DroneSearchField;
@protocol DroneSearchFieldDelegate<UITextFieldDelegate>
@optional
- (void)DroneTextFieldButtonClicked:(DroneSearchField *)textField;
@end
@interface DroneSearchField : UITextField
@end
NeXTSTEP or NeXTSTEP/Sun depending on who you are asking.
Sun had a fairly large investment in OpenStep for a while. Before Sun entered the picture most things in the foundation, even though it wasn't known as the foundation back then, was prefixed NX, for NeXT, and sometime just before Sun entered the picture everything was renamed to NS. The S most likely did not stand for Sun then but after Sun stepped in the general consensus was that it stood for Sun to honor their involvement.
I actually had a reference for this but I can't find it right now. I will update the post if/when I find it again.
frame = a view's location and size using the parent view's coordinate system
bounds = a view's location and size using its own coordinate system
To help me remember frame, I think of a picture frame on a wall. The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame's x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y.
To help me remember bounds, I think of a basketball court where sometimes the basketball gets knocked out of bounds. You are dribbling the ball all over the basketball court, but you don't really care where the court itself is. It could be in a gym, or outside at a high school, or in front of your house. It doesn't matter. You just want to play basketball. In the same way, the coordinate system for a view's bounds only cares about the view itself. It doesn't know anything about where the view is located in the parent view. The bounds' origin (point (0, 0) by default) is the top left corner of the view. Any subviews that this view has are laid out in relation to this point. It is like taking the basketball to the front left corner of the court.
Now the confusion comes when you try to compare frame and bounds. It actually isn't as bad as it seems at first, though. Let's use some pictures to help us understand.
In the first picture on the left we have a view that is located at the top left of its parent view. The yellow rectangle represents the view's frame. On the right we see the view again but this time the parent view is not shown. That's because the bounds don't know about the parent view. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds.
Frame
origin = (0, 0)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
So the frame and bounds were exactly the same in that picture. Let's look at an example where they are different.
Frame
origin = (40, 60) // That is, x=40 and y=60
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
So you can see that changing the x-y coordinates of the frame moves it in the parent view. But the content of the view itself still looks exactly the same. The bounds have no idea that anything is different.
Up to now the width and height of both the frame and the bounds have been exactly the same. That isn't always true, though. Look what happens if we rotate the view 20 degrees clockwise. (Rotation is done using transforms. See the the documentation and these view and layer examples for more information.)
Frame
origin = (20, 52) // These are just rough estimates.
width = 118
height = 187
Bounds
origin = (0, 0)
width = 80
height = 130
You can see that the bounds are still the same. They still don't know anything has happened! The frame values have all changed, though.
Now it is a little easier to see the difference between frame and bounds, isn't it? The article You Probably Don't Understand frames and bounds defines a view frame as
...the smallest bounding box of that view with respect to it’s parents coordinate system, including any transformations applied to that view.
It is important to note that if you transform a view, then the frame becomes undefined. So actually, the yellow frame that I drew around the rotated green bounds in the image above never actually exists. That means if you rotate, scale or do some other transformation then you shouldn't use the frame values any more. You can still use the bounds values, though. The Apple docs warn:
Important: If a view’s
transform
property does not contain the identity transform, the frame of that view is undefined and so are the results of its autoresizing behaviors.
Rather unfortunate about the autoresizing.... There is something you can do, though.
When modifying the
transform
property of your view, all transformations are performed relative to the center point of the view.
So if you do need to move a view around in the parent after a transformation has been done, you can do it by changing the view.center
coordinates. Like frame
, center
uses the coordinate system of the parent view.
Ok, let's get rid of our rotation and focus on the bounds. So far the bounds origin has always stayed at (0, 0). It doesn't have to, though. What if our view has a large subview that is too big to display all at once? We'll make it a UIImageView
with a large image. Here is our second picture from above again, but this time we can see what the whole content of our view's subview would look like.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Only the top left corner of the image can fit inside the view's bounds. Now look what happens if we change the bounds' origin coordinates.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (280, 70)
width = 80
height = 130
The frame hasn't moved in the superview but the content inside the frame has changed because the origin of the bounds rectangle starts at a different part of the view. This is the whole idea behind a UIScrollView
and it's subclasses (for example, a UITableView
). See Understanding UIScrollView for more explanation.
Since frame
relates a view's location in its parent view, you use it when you are making outward changes, like changing its width or finding the distance between the view and the top of its parent view.
Use the bounds
when you are making inward changes, like drawing things or arranging subviews within the view. Also use the bounds to get the size of the view if you have done some transfomation on it.
Apple docs
Related StackOverflow questions
Other resources
In addition to reading the above articles, it helps me a lot to make a test app. You might want to try to do something similar. (I got the idea from this video course but unfortunately it isn't free.)
Here is the code for your reference:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
// Labels
@IBOutlet weak var frameX: UILabel!
@IBOutlet weak var frameY: UILabel!
@IBOutlet weak var frameWidth: UILabel!
@IBOutlet weak var frameHeight: UILabel!
@IBOutlet weak var boundsX: UILabel!
@IBOutlet weak var boundsY: UILabel!
@IBOutlet weak var boundsWidth: UILabel!
@IBOutlet weak var boundsHeight: UILabel!
@IBOutlet weak var centerX: UILabel!
@IBOutlet weak var centerY: UILabel!
@IBOutlet weak var rotation: UILabel!
// Sliders
@IBOutlet weak var frameXSlider: UISlider!
@IBOutlet weak var frameYSlider: UISlider!
@IBOutlet weak var frameWidthSlider: UISlider!
@IBOutlet weak var frameHeightSlider: UISlider!
@IBOutlet weak var boundsXSlider: UISlider!
@IBOutlet weak var boundsYSlider: UISlider!
@IBOutlet weak var boundsWidthSlider: UISlider!
@IBOutlet weak var boundsHeightSlider: UISlider!
@IBOutlet weak var centerXSlider: UISlider!
@IBOutlet weak var centerYSlider: UISlider!
@IBOutlet weak var rotationSlider: UISlider!
// Slider actions
@IBAction func frameXSliderChanged(sender: AnyObject) {
myView.frame.origin.x = CGFloat(frameXSlider.value)
updateLabels()
}
@IBAction func frameYSliderChanged(sender: AnyObject) {
myView.frame.origin.y = CGFloat(frameYSlider.value)
updateLabels()
}
@IBAction func frameWidthSliderChanged(sender: AnyObject) {
myView.frame.size.width = CGFloat(frameWidthSlider.value)
updateLabels()
}
@IBAction func frameHeightSliderChanged(sender: AnyObject) {
myView.frame.size.height = CGFloat(frameHeightSlider.value)
updateLabels()
}
@IBAction func boundsXSliderChanged(sender: AnyObject) {
myView.bounds.origin.x = CGFloat(boundsXSlider.value)
updateLabels()
}
@IBAction func boundsYSliderChanged(sender: AnyObject) {
myView.bounds.origin.y = CGFloat(boundsYSlider.value)
updateLabels()
}
@IBAction func boundsWidthSliderChanged(sender: AnyObject) {
myView.bounds.size.width = CGFloat(boundsWidthSlider.value)
updateLabels()
}
@IBAction func boundsHeightSliderChanged(sender: AnyObject) {
myView.bounds.size.height = CGFloat(boundsHeightSlider.value)
updateLabels()
}
@IBAction func centerXSliderChanged(sender: AnyObject) {
myView.center.x = CGFloat(centerXSlider.value)
updateLabels()
}
@IBAction func centerYSliderChanged(sender: AnyObject) {
myView.center.y = CGFloat(centerYSlider.value)
updateLabels()
}
@IBAction func rotationSliderChanged(sender: AnyObject) {
let rotation = CGAffineTransform(rotationAngle: CGFloat(rotationSlider.value))
myView.transform = rotation
updateLabels()
}
private func updateLabels() {
frameX.text = "frame x = \(Int(myView.frame.origin.x))"
frameY.text = "frame y = \(Int(myView.frame.origin.y))"
frameWidth.text = "frame width = \(Int(myView.frame.width))"
frameHeight.text = "frame height = \(Int(myView.frame.height))"
boundsX.text = "bounds x = \(Int(myView.bounds.origin.x))"
boundsY.text = "bounds y = \(Int(myView.bounds.origin.y))"
boundsWidth.text = "bounds width = \(Int(myView.bounds.width))"
boundsHeight.text = "bounds height = \(Int(myView.bounds.height))"
centerX.text = "center x = \(Int(myView.center.x))"
centerY.text = "center y = \(Int(myView.center.y))"
rotation.text = "rotation = \((rotationSlider.value))"
}
}
If the string is very large then copy will affect performance and two copies of the large string will use more memory.
I prefer using regex like this:
NSString *myString = @"this is a test";
NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [myStringlength])];
//myNewString will be @"thisisatest"
You can make yourself a category on NSString to make life even easier:
- (NSString *) removeAllWhitespace
{
return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [self length])];
}
Here is a unit test method on it too:
- (void) testRemoveAllWhitespace
{
NSString *testResult = nil;
NSArray *testStringsArray = @[@""
,@" "
,@" basicTest "
,@" another Test \n"
,@"a b c d e f g"
,@"\n\tA\t\t \t \nB \f C \t ,d,\ve F\r\r\r"
,@" landscape, portrait, ,,,up_side-down ;asdf; lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & * * ()+ + "
];
NSArray *expectedResultsArray = @[@""
,@""
,@"basicTest"
,@"anotherTest"
,@"abcdefg"
,@"ABC,d,eF"
,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++"
];
for (int i=0; i < [testStringsArray count]; i++)
{
testResult = [testStringsArray[i] removeAllWhitespace];
STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"",
testStringsArray[i], expectedResultsArray[i], testResult);
}
}
Thanks for the post. I followed it and it worked for me. But I had another issue that was not mentioned in any of the replies. So I am not sure if it was just me.
Anyway, thought I would post here the problem and my way that solved it.
I had a few records in the database, I wanted to purge everything clean before write new data to the db, so I did everything including
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
and then used managedObjectContext
to access the database (supposed to be empty by now), somehow the data was still there.
After a while of troubleshooting, I found that I need to reset managedObjectContext
, managedObject
, managedObjectModel
and
persistentStoreCoordinator
, before I use managedObjectContext
to access the dabase. Now I have a clean database to write to.
to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.
essentially it will look something like this
^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$
Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?
It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.
So do the regular expression and validate the structure but forget about validating against a service.
Let's say you have a button with the text, "Click Me". What width should that button be?
First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.
Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [ Click Me ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
Replace this:
NSDate* now = [NSDate date];
int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];
With this:
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second];
As others have said, in general you use @synthesize to have the compiler generate the getters and/ or settings for you, and @dynamic if you are going to write them yourself.
There is another subtlety not yet mentioned: @synthesize will let you provide an implementation yourself, of either a getter or a setter. This is useful if you only want to implement the getter for some extra logic, but let the compiler generate the setter (which, for objects, is usually a bit more complex to write yourself).
However, if you do write an implementation for a @synthesize'd accessor it must still be backed by a real field (e.g., if you write -(int) getFoo();
you must have an int foo;
field). If the value is being produce by something else (e.g. calculated from other fields) then you have to use @dynamic.
cdespinosa's answer to Stack Overflow question How do I debug with NSLog(@“Inside of the iPhone Simulator”)? gives a method for a debugging-via-logging technique that requires no recompilation of source. An amazing trick that keeps code free of debugging cruft, has a quick turnaround, and would have saved me countless headaches had I known about it earlier.
Prefixing a comment with TODO:
will cause it to show up in the function "shortcut" dropdown menu, a la:
int* p(0); // TODO: initialize me!
I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.
First and foremost, objectForKey:
is an NSDictionary
method, while valueForKey:
is a KVC protocol method required of any KVC complaint class - including NSDictionary.
Furthermore, as @dreamlax wrote, documentation hints that NSDictionary
implements its valueForKey:
method USING its objectForKey:
implementation. In other words - [NSDictionary valueForKey:]
calls on [NSDictionary objectForKey:]
.
This implies, that valueForKey:
can never be faster than objectForKey:
(on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.
Next: KVC protocol only works with NSString *
keys, hence valueForKey:
will only accept an NSString *
(or subclass) as key, whilst NSDictionary
can work with other kinds of objects as keys - so that the "lower level" objectForKey:
accepts any copy-able (NSCopying protocol compliant) object as key.
Last, NSDictionary's
implementation of valueForKey:
deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException
for a key it can't find - unless this is a "special" key - one that begins with '@' - which usually means an "aggregation" function key (e.g. @"@sum, @"@avg"
). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:
Following is some test code to demonstrate and prove my notes.
- (void) dictionaryAccess {
NSLog(@"Value for Z:%@", [@{@"X":@(10), @"Y":@(20)} valueForKey:@"Z"]); // prints "Value for Z:(null)"
uint32_t testItemsCount = 1000000;
// create huge dictionary of numbers
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
// make new random key value pair:
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
NSNumber *value = @(arc4random_uniform(testItemsCount));
[d setObject:value forKey:key];
}
// create huge set of random keys for testing.
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
[keys addObject:key];
}
NSDictionary *dict = [d copy];
NSTimeInterval vtotal = 0.0, ototal = 0.0;
NSDate *start;
NSTimeInterval elapsed;
for (int i = 0; i<10; i++) {
start = [NSDate date];
for (NSString *key in keys) {
id value = [dict valueForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
vtotal+=elapsed;
NSLog (@"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);
start = [NSDate date];
for (NSString *key in keys) {
id obj = [dict objectForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
ototal+=elapsed;
NSLog (@"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
}
NSString *slower = (vtotal > ototal) ? @"valueForKey" : @"objectForKey";
NSString *faster = (vtotal > ototal) ? @"objectForKey" : @"valueForKey";
NSLog (@"%@ takes %3.1f percent longer then %@", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}
Contacts.add(objt.Data(name, address, contact));
This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.
The correct way is:
// object creation.
Data object1 = new Data(name, address, contact);
// adding Data object to ArrayList object Contacts.
Contacts.add(object1);
From the python docs on os.walk()
:
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
In my case, all modules were correctly set up (https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension is a good starter) & I had the redirection working for a base url, let's say /mysite/
but I got the errors for any child ULR, let's say /mysite/login/
http://reverse-proxy.dns.com/mysite/
was properly redirected to the remote servers while http://reverse-proxy.dns.com/mysite/login/
failed at the Apache2 reverse proxying with OP's error message.
The issue was the ending /
character in the proxypass directive "/mysite/". Working configuration for child URL is :
<Proxy balancer://mysite_cluster>
BalancerMember http://192.x.x.10:8080/mysite
BalancerMember http://192.x.x.11:8080/mysite
</Proxy>
<VirtualHost *:80>
[...]
ProxyRequests Off
ProxyPreserveHost On
ProxyPass "/mysite" "balancer://mysite_cluster"
ProxyPassReverse "/mysite" "balancer://mysite_cluster"
</VirtualHost>
Trailing /
truly are tricky.
With TypeScript, it is easy to find what you want with the right type.
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.com')
.then(response: AxiosResponse => {
// Handle response
})
.catch((reason: AxiosError) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
If its a maven project, add the below dependency in your pom file
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
Ah... the rationale for not having a straightforward method in Java to do that is file storage abstraction: some filesystems may not have the number of files in a directory readily available... that count may not even have any meaning at all (see for example distributed, P2P filesystems, fs that store file lists as a linked list, or database-backed filesystems...). So yes,
new File(<directory path>).list().length
is probably your best bet.
In Linux, Open the VIM configuration file
$ sudo -H gedit /etc/vim/vimrc
Added following lines:
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
set termencoding=utf-8
set encoding=utf-8
Save and exit, and terminal command:
$ source /etc/vim/vimrc
At this time VIM will correctly display Chinese.
Here is the easiest way of creating a splash screen:
First of all, add the following line of code before the namespace in Form1.cs code:
using System.Threading;
Now, follow the following steps:
Add a new form in you application
Name this new form as FormSplashScreen
In the BackgroundImage property, choose an image from one of your folders
Add a progressBar
In the Dock property, set it as Bottom
In MarksAnimationSpeed property, set as 50
In your main form, named as Form1.cs by default, create the following method:
private void StartSplashScreen()
{
Application.Run(new Forms.FormSplashScreen());
}
In the constructor method of Form1.cs, add the following code:
public Form1()
{
Thread t = new Thread(new ThreadStart(StartSplashScreen));
t.Start();
Thread.Sleep(5000);
InitializeComponent();//This code is automatically generated by Visual Studio
t.Abort();
}
Now, just run the application, it is going to work perfectly.
Based on this SO answer, I just had to change path="*."
to path="*"
for the added ExtensionlessUrlHandler-Integrated-4.0
in configuration>system.WebServer>handlers
in my web.config
Before:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
After:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
You have to override method handledType and everything will work
@Override
public Class<Item> handledType()
{
return Item.class;
}
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = {_x000D_
key1: "it ",_x000D_
key2: function() {_x000D_
return this.key1 + " works!";_x000D_
}_x000D_
};_x000D_
_x000D_
alert(obj.key2());
_x000D_
Thank you @Razvan who pointed me in the right direction. I was able to get it in one line and I successfully hunted down the imports for Hamcrest 1.3.
the imports:
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
the code:
assertThat( myClass.getMyItems(), contains(
hasProperty("name", is("foo")),
hasProperty("name", is("bar"))
));
I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...
$(".element").css( { marginLeft : "200px", marginRight : "200px" } );
as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...
$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );
without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.
EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];
There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).
The concrete code is by Michal Migurski and by Matt Knapp:
this should do it
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();
You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else.
By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment
in order to find the action.
Console example of MemoryCache, "How to save/get simple class objects"
Output after launching and pressing Any key except Esc :
Saving to cache!
Getting from cache!
Some1
Some2
class Some
{
public String text { get; set; }
public Some(String text)
{
this.text = text;
}
public override string ToString()
{
return text;
}
}
public static MemoryCache cache = new MemoryCache("cache");
public static string cache_name = "mycache";
static void Main(string[] args)
{
Some some1 = new Some("some1");
Some some2 = new Some("some2");
List<Some> list = new List<Some>();
list.Add(some1);
list.Add(some2);
do {
if (cache.Contains(cache_name))
{
Console.WriteLine("Getting from cache!");
List<Some> list_c = cache.Get(cache_name) as List<Some>;
foreach (Some s in list_c) Console.WriteLine(s);
}
else
{
Console.WriteLine("Saving to cache!");
cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
}
I found this thread on that there Interweb thing. Boils down to:
@echo off
setlocal enableextensions
for /f "tokens=*" %%a in (
'VER'
) do (
set myvar=%%a
)
echo/%%myvar%%=%myvar%
pause
endlocal
You can also redirect the output of a command to a temporary file, and then put the contents of that temporary file into your variable, likesuchashereby. It doesn't work with multiline input though.
cmd > tmpFile
set /p myvar= < tmpFile
del tmpFile
Credit to the thread on Tom's Hardware.
I think this may work.
public static byte[] StrToByteArray(string str)
{
Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
for (int i = 0; i <= 255; i++)
hexindex.Add(i.ToString("X2"), (byte)i);
List<byte> hexres = new List<byte>();
for (int i = 0; i < str.Length; i += 2)
hexres.Add(hexindex[str.Substring(i, 2)]);
return hexres.ToArray();
}
My solution:
#ifdef WIN32
#include <Windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif
void GetMachineName(char machineName[150])
{
char Name[150];
int i=0;
#ifdef WIN32
TCHAR infoBuf[150];
DWORD bufCharCount = 150;
memset(Name, 0, 150);
if( GetComputerName( infoBuf, &bufCharCount ) )
{
for(i=0; i<150; i++)
{
Name[i] = infoBuf[i];
}
}
else
{
strcpy(Name, "Unknown_Host_Name");
}
#else
memset(Name, 0, 150);
gethostname(Name, 150);
#endif
strncpy(machineName,Name, 150);
}
Execution Timeout is 90 seconds for .NET
Framework 1.0 and 1.1, 110 seconds otherwise.
If you need to change defult settings you need to do it in your web.config
under <httpRuntime>
<httpRuntime executionTimeout = "number(in seconds)"/>
But Remember:
This time-out applies only if the debug attribute in the compilation element is False.
Have look at in detail about compilation Element
Have look at this document about httpRuntime Element
If you prefer method call notation, you can force a left join using SelectMany
combined with DefaultIfEmpty
. At least on Entity Framework 6 hitting SQL Server. For example:
using(var ctx = new MyDatabaseContext())
{
var data = ctx
.MyTable1
.SelectMany(a => ctx.MyTable2
.Where(b => b.Id2 == a.Id1)
.DefaultIfEmpty()
.Select(b => new
{
a.Id1,
a.Col1,
Col2 = b == null ? (int?) null : b.Col2,
}));
}
(Note that MyTable2.Col2
is a column of type int
).
The generated SQL will look like this:
SELECT
[Extent1].[Id1] AS [Id1],
[Extent1].[Col1] AS [Col1],
CASE WHEN ([Extent2].[Col2] IS NULL) THEN CAST(NULL AS int) ELSE CAST( [Extent2].[Col2] AS int) END AS [Col2]
FROM [dbo].[MyTable1] AS [Extent1]
LEFT OUTER JOIN [dbo].[MyTable2] AS [Extent2] ON [Extent2].[Id2] = [Extent1].[Id1]
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
If you want to add plots to your Jupyter notebook, then %matplotlib inline
is a standard solution. And there are other magic commands will use matplotlib
interactively within Jupyter.
%matplotlib
: any plt
plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()
%matplotlib notebook
: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure
%matplotlib inline
: only draw static images in the notebook
A simpler approach to this
At the beginning of column B, type
=UNIQUE(A:A)
Then in column C, use
=COUNTIF(A:A, B1)
and copy them in all row column C.
Edit: If that doesn't work for you, try using semicolon instead of comma:
=COUNTIF(A:A; B1)
You can try this
click Help>Install New Software on the menu bar
To further explain Sheena's answer, I needed to have setup-tools installed as a dependency of another tool e.g. more-itertools.
Click the Clone or download button and choose your method. I placed these into a dev/py/libs
directory in my user home directory. It does not matter where they are saved, because they will not be installed there.
You will need to run the following inside the setup-tools directory.
python bootstrap.py
python setup.py install
Now you can navigate to the more-itertools direcotry and install it as normal.
cd ...
) into the directory containing setup.py
python setup.py install
You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:
File > New > Project...
Maven
and select Maven Project
and click Next
.Create a simple project
(to skip the archetype selection).jar
, and a Name.Run as > Maven install
.Here is a VBA approach:
Sub change()
toText Sheets(1).Range("A1:F20")
End Sub
Sub toText(target As Range)
Dim cell As Range
For Each cell In target
cell.Value = cell.Text
cell.NumberFormat = "@"
Next cell
End Sub
If you are looking for a solution without programming, the Question should be moved to SuperUser.
Using $resource
in AngularJS you can do:
task.service.js
$ngTask.factory("$taskService", [
"$resource",
function ($resource) {
var taskModelUrl = 'api/task/';
return {
rest: {
taskUpload: $resource(taskModelUrl, {
id: '@id'
}, {
save: {
method: "POST",
isArray: false,
headers: {"Content-Type": undefined},
transformRequest: angular.identity
}
})
}
};
}
]);
And then use it in a module:
task.module.js
$ngModelTask.controller("taskController", [
"$scope",
"$taskService",
function (
$scope,
$taskService,
) {
$scope.saveTask = function (name, file) {
var newTask,
payload = new FormData();
payload.append("name", name);
payload.append("file", file);
newTask = $taskService.rest.taskUpload.save(payload);
// check if exists
}
}
You have done it backwards, it should be:
amount = invest(amount,top_company(5,year,year+1),year)
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
Now you can upload your app binary with the Transporter app.
You can download Transporter from Mac AppStore Here
Here apple mentioned its used for uploading.
This question is very helpfully BUT Don't forget to mount SD Card in your emulator, if you don't do this its doesn't work.
I lose my time before discover this.
Yes, you're right. With the css()
method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/
But if you want to get its position you can check offset() and position() methods to get it's position.
You can always take the CTE, (Common Tabular Expression), approach.
;WITH updateCTE AS
(
SELECT ID, TITLE
FROM HOLD_TABLE
WHERE ID = 101
)
UPDATE updateCTE
SET TITLE = 'TEST';
Since the question is being tagged for mysql
, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:
select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age
from table
where ...
Don't worry...! Follow these below steps and you will get your signed .apk file. I was also worry about that, but these step get ride me off from the frustration. Steps to sign your application:
Right click on the project in Eclipse -> Android Tools -> Export Unsigned Application Package (like here we export our GoogleDriveApp.apk to Desktop)
Sign the application using your keystore and the jarsigner tool (follow below steps):
Open cmd-->change directory where your "jarsigner.exe" exist (like here in my system it exist at "C:\Program Files\Java\jdk1.6.0_17\bin"
Now enter belwo command in cmd:
jarsigner -verbose -keystore c:\users\android\debug.keystore c:\users\pir fahim\Desktops\GoogleDriveApp.apk my_keystore_alias
It will ask you to provide your password: Enter Passphrase for keystore: It will sign your apk.To verify that the signing is successful you can run:
jarsigner -verify c:\users\pir fahim\Desktops\GoogleDriveApp.apk
It should come back with: jar verified.
Method 2
If you are using eclipse with ADT, then it is simple to compiled, signed, aligned, and ready the file for distribution.what you have to do just follow this steps.
These steps will compiled, signed and zip aligned your project and now you are ready to distribute your project or upload at Google Play store.
This one shows how to print only selected element on the page with dpi/resolution
adjustments
HTML:
<html>
<body>
<header>This is the header</header>
<div id="content">
This is the element you only want to capture
</div>
<button id="print">Download Pdf</button>
<footer>This is the footer</footer>
</body>
</html>
CSS:
body {
background: beige;
}
header {
background: red;
}
footer {
background: blue;
}
#content {
background: yellow;
width: 70%;
height: 100px;
margin: 50px auto;
border: 1px solid orange;
padding: 20px;
}
JS:
$('#print').click(function() {
var w = document.getElementById("content").offsetWidth;
var h = document.getElementById("content").offsetHeight;
html2canvas(document.getElementById("content"), {
dpi: 300, // Set to 300 DPI
scale: 3, // Adjusts your resolution
onrendered: function(canvas) {
var img = canvas.toDataURL("image/jpeg", 1);
var doc = new jsPDF('L', 'px', [w, h]);
doc.addImage(img, 'JPEG', 0, 0, w, h);
doc.save('sample-file.pdf');
}
});
});
The easiest way to install latest pip2
/pip3
and corresponding packages:
curl https://bootstrap.pypa.io/get-pip.py | python2
pip2 install package-name
curl https://bootstrap.pypa.io/get-pip.py | python3
pip3 install package-name
Note: please run these commands as root
EUROPE:
declare @d datetime;
set @d=getdate();
set @dow=((datepart(dw,@d) + @@DATEFIRST-2) % 7+1);
However this question is seeking to find the last row using VBA, I think it would be good to include an array formula for worksheet function as this gets visited frequently:
{=ADDRESS(MATCH(INDEX(D:D,MAX(IF(D:D<>"",ROW(D:D)-ROW(D1)+1)),1),D:D,0),COLUMN(D:D))}
You need to enter the formula without brackets and then hit Shift + Ctrl + Enter to make it an array formula.
This will give you address of last used cell in the column D.
I have resolved above problem as follows:
Yes. The casts are redundant. In your expression:
true == 1
Integral promotion applies and the bool value will be promoted to an int
and this promotion must yield 1.
Reference: 4.7 [conv.integral] / 4: If the source type is bool
... true
is converted to one.
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import express = require('express');
or (depending on your module loader)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
Use the logging built-in library module instead of printing.
You create a Logger
object (say logger
), and then after that, whenever you insert a debug print, you just put:
logger.debug("Some string")
You can use logger.setLevel
at the start of the program to set the output level. If you set it to DEBUG, it will print all the debugs. Set it to INFO or higher and immediately all of the debugs will disappear.
You can also use it to log more serious things, at different levels (INFO, WARNING and ERROR).
Only works in IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
Use -B, -A or -C option
grep --help
...
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
...
The following ex commands will (re-)split any number of windows:
:vertical ball
:ball
If there are hidden buffers, issuing these commands will also make the hidden buffers visible.
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))
I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root
and modify the file /etc/php5/fpm/php.ini
.
To find the line with the always_populate_raw_post_data
I first run grep
:
grep -n 'always_populate_raw_post_data' php.ini
That returned the line 704
704:;always_populate_raw_post_data = -1
Then simply open php.ini
on that line with vi
editor:
vi +704 php.ini
Remove the semi colon to uncomment it and save the file :wq
Lastly reboot the server and the error went away.
With code like this:
const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
And in the configure.ac
AC_PROG_CC_C99
The compiler on my dev box was happy. The compiler on the server complained with:
error: variable-sized object may not be initialized
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
and
warning: excess elements in array initializer
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };
for each element
It doesn't complain at all about, for example:
int expected[] = { 1, 2, 3, 4, 5 };
however, I decided that I like the check on size.
Rather than fighting, I went with a varargs initializer:
#include <stdarg.h>
void int_array_init(int *a, const int ct, ...) {
va_list args;
va_start(args, ct);
for(int i = 0; i < ct; ++i) {
a[i] = va_arg(args, int);
}
va_end(args);
}
called like,
const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);
As such, the varargs support is more robust than the support for the array initializer.
Someone might be able to do something like this in a macro.
Find PR with sample code at https://github.com/wbreeze/davenport/pull/15/files
Regarding https://stackoverflow.com/a/3535455/608359 from @paxdiablo, I liked it; but, felt insecure about having the number of times the initializaion pointer advances synchronized with the number of elements allocated to the array. Worst case, the initializing pointer moves beyond the allocated length. As such, the diff in the PR contains,
int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);
The int_array_init
method will safely assign junk if the number of
arguments is fewer than the node_ct. The junk assignment ought to be easier
to catch and debug.
Just do
NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"];
This gives you
@"first part of string (foo) third part of string"
This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label
label{
display: block;
height: 35px;
line-height: 35px;
border: 1px solid #000;
}
input{margin-top:15px; height:20px}
<label for="name">Name: <input type="text" id="name" /></label>
The documentation has the complete answer. Anyway this is how it is done:
<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>
will filter only age
in data
array and true
is for exact match.
For deep filtering,
<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>
The $
is a special property for deep filter and the true
is for exact match like above.
There might be a reason that Typescript
is not installed globally, so install it
npm install -g typescript // installs typescript globally
If you want to convert .ts
files into .js
, do this as per your need
tsc file.ts // file.ts will be converted to file.js file
tsc // all .ts files will be converted to .js files in the directory
tsc --watch // converts all .ts files to .js, and watch changes in .ts files
In the Params I have added model.Email and model.Password, work for me well. Thanks for the question. I tried the same thing in headers did not work. But it worked on Body with form-data and x-www-form-urlencoded.
Postman version 6.4.4
Try this:
Sometimes #1 works and sometimes #2 for me. I am not sure why it reacts in this way
This problem is caused when including <windows.h>
before <winsock2.h>
. Try arrange your include list that <windows.h>
is included after <winsock2.h>
or define _WINSOCKAPI_
first:
#define _WINSOCKAPI_ // stops windows.h including winsock.h
#include <windows.h>
// ...
#include "MyClass.h" // Which includes <winsock2.h>
See also this.
There is no "better" but the more common one is ||
. They have different precedence and ||
would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
Well, if you really want to return a mapping from _id
to user
, you could always do:
server.get('/usersList', function(req, res) {
User.find({}, function(err, users) {
var userMap = {};
users.forEach(function(user) {
userMap[user._id] = user;
});
res.send(userMap);
});
});
find()
returns all matching documents in an array, so your last code snipped sends that array to the client.
Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
~ Quoted from Java 1.5.0 docs
(But why didn't you just try it and see for yourself?)
You could use imagemagick and write a script that fires everytime you load a webpage.
this will remove all the special character
str.replace(/[_\W]+/g, "");
this is really helpful and solve my issue. Please run the below code and ensure it works
var str="hello world !#to&you%*()";_x000D_
console.log(str.replace(/[_\W]+/g, ""));
_x000D_
Simply get all improtanat information with this below SQL in Mysql
SELECT t.TABLE_NAME , t.ENGINE , t.TABLE_ROWS ,t.AVG_ROW_LENGTH,
t.INDEX_LENGTH FROM
INFORMATION_SCHEMA.TABLES as t where t.TABLE_SCHEMA = 'YOURTABLENAMEHERE'
order by t.TABLE_NAME ASC limit 10000;
I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !
Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.
Went a step further...I thought this was cool...When I instead do this in Expts.py:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.
If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.
Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list locally-tracking branches that were merged in remote (you may consider to use -r flag to list all remote-tracking branches as suggested in other answers).
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^\*|master|main|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name
will not be deleted.
git branch --merged| egrep -v "(^\*|master|main|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^\*|master|main|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote use:
git push --delete origin branchname
git push origin :branchname # for really old git
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
There is another open-source tool which allows you to save all console.log
output in a file on your server - JS LogFlush (plug!).
JS LogFlush is an integrated JavaScript logging solution which include:
- cross-browser UI-less replacement of console.log - on client side.
- log storage system - on server side.
What is a CSS map file?
It is a JSON format file that links the CSS file to its source files, normally, files written in preprocessors (i.e., Less, Sass, Stylus, etc.), this is in order do a live debug to the source files from the web browser.
What is CSS preprocessor? Examples: Sass, Less, Stylus
It is a CSS generator tool that uses programming power to generate CSS robustly and quickly.
Add your icon as a Resource (Project > yourprojectname Properties > Resources > Pick "Icons from dropdown > Add Resource (or choose Add Existing File from dropdown if you already have the .ico)
Then:
this.Icon = Properties.Resources.youriconname;
For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # Example: <v>84</v>
value = el.text
if el.tag.endswith('}c'): # Example: <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # Example: AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.
def xlsx(fname,sheet):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Get shared strings
strings = [element.text for event, element
in iterparse(z.open('xl/sharedStrings.xml'))
if element.tag.endswith('}t')]
sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
if element.tag.endswith('}sheet') }
rows = []
row = {}
value = ''
if sheet in sheets:
sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
#print(sheet,sheetfile)
for event, element in iterparse(z.open(sheetfile)):
# get value or index to shared strings
if element.tag.endswith('}v') or element.tag.endswith('}t'):
value = element.text
# If value is a shared string, use value as an index
if element.tag.endswith('}c'):
if element.attrib.get('t') == 's':
value = strings[int(value)]
# split the row/col information so that the row leter(s) can be separate
letter = re.sub('\d','',element.attrib['r'])
row[letter] = value
value = ''
if element.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Just try $('.handle').css('left', '300px');
By using jquery ajax you can reload your page
$.ajax({
type: "POST",
url: "packtypeAdd.php",
data: infoPO,
success: function() {
location.reload();
}
});
Using Apache Commons-IO, it is following one-liner:
import org.apache.commons.io.FileUtils;
FileUtils.forceDelete(new File(destination));
This is (slightly) more performant than FileUtils.deleteDirectory
.
As the instruction said "might need gpg2"
In mac, you can try install it with homebrew
$ brew install gpg2
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
One could also use the JQuery filter for objects
var newobj = $(obj).filter(function(key) {
return $(this)[key]!== undefined;
})[0];
Demo here
Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.
df.sort_index(axis=1, inplace=True)
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
Whatever is assigned to the files
variable is incorrect. Use the following code.
import glob
import os
list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
You can try this to get infos like:
git config --get user.name
git config --get user.email
There's nothing like "first name" and "last name" for the user.
Hope this will help.
String.valueOf('X')
will create you a String "X"
"X".charAt(0)
will give you the character 'X'
Or you can just run power-shell command to append extra folder to the existing path:
$env:Path += ";C:\temp\terraform"
Personnally, I prefer:
var result = from entry in table
where (entry.something??0)==(value??0)
select entry;
over
var result = from entry in table
where (value == null ? entry.something == null : entry.something == value)
select entry;
because it prevents repetition -- though that's not mathematically exact, but it fits well most cases.
Remove column constraint: not null
to null
ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;
I ran into this problem while upgrading to WordPress 4.0. By default WordPress limits the maximum execution time to 30 seconds.
Add the following code to your .htaccess file on your root directory of your WordPress Installation to over-ride the default.
php_value max_execution_time 300 //where 300 = 300 seconds = 5 minutes
I know this may be a bit too late but the most efficient way of doing this through a CTE as follows:
WITH Months AS
(
SELECT 1 x
UNION all
SELECT x + 1
FROM Months
WHERE x < 12
)
SELECT x AS MonthNumber, DateName( month , DateAdd( month , x , -1 )) AS MonthName FROM Months
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
You can use for loop if you really want to.
char table[][] table = new char[row][col];
for(int i = 0; i < row * col ; ++i){
table[i/row][i % col] = char('a' + (i+1));
}
or do what bhesh said.
For removing the default 'blue-border' from button on button focus:
In Html:
<button class="new-button">New Button...</button>
And in Css
button.new-button:focus {
outline: none;
}
Hope it helps :)
The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.
Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""
Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Ikariam Autologin</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="s666.en.ikariam.com" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="PlayersName" class="" />
<input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.
Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:
Your Fragment can subclass ListFragment.
And onCreateView() from ListFragment
will return a ListView
you can then populate.
table_ex
id default nextval('table_id_seq'::regclass),
camp1 varchar
camp2 varchar
INSERT INTO table_ex(camp1,camp2) VALUES ('xxx','123') RETURNING id
I think the problem is that you load
isfar
data.frame but you overwrite it by value returned by load
.
Try either:
load("C:/Users/isfar.RData")
head(isfar)
Or more general way
load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex)
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.get("banner.html", function (data) {
$("#appendToThis").append(data);
});
});
</script>
</head>
<body>
<div id="appendToThis"></div>
</body>
</html>
Using Base64 string in JSON will be very heavy. The parser has to do a lot of heavy lifting. Currently, Fresco only supports base supports Base64. Better you put something on Amazon Cloud or Firebase Cloud. And get an image as a URL. So that you can use Picasso or Glide for caching.
Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.
Update 10 Nov 2017 SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:
We Made SFTP Net Drive FREE for Personal Use
They have paid options as well on the website.
Manually we can use the below method:
We can edit the migration manually like:
Open app/db/migrate/xxxxxxxxx_migration_file.rb
Update hased_password
to hashed_password
Run the below command
$> rake db:migrate:down VERSION=xxxxxxxxx
Then it will remove your migration:
$> rake db:migrate:up VERSION=xxxxxxxxx
It will add your migration with the updated change.
There isn't anything like that in standard Linq, but there is a ForEach operator in MoreLinq.
Open the file using vi or nano. and then press " i " ,
For save and quit
Enter Esc
and write the following command
:wq
without save and quit
:q!
I wanted to be able to specify which tab was shown by class rather than index as I thought it made for a robust solution that was less dependant on how you wire up IB. I didn't find either Disco's or Joped's solutions to work so i created this method:
-(void)setTab:(Class)class{
int i = 0;
for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
if ([controller isKindOfClass:class]){
break;
}
i++;
}
self.tabBarContontroller.selectedIndex = i;
}
you call it like this:
[self setTab:[YourClass class]];
Hope this is helpful to someone
Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.
Because 2
isn't an array, it's a number. Numbers have no length.
Perhaps you meant to write testvar.length
; this is also undefined, since objects (created using the { ... }
notation) do not have a length.
Only arrays have a length property:
var testvar = [ ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length); // 3
Note that Javascript arrays are indexed starting at 0
and are not necessarily sparse (hence why the result is 3 and not 2 -- see this answer for an explanation of when the array will be sparse and when it won't).
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
From your question it seems like you are using C99, as you have used %lf
for double.
To achieve the desired output replace:
sprintf(aa, "%lf", a);
with
sprintf(aa, "%0.7f", a);
The general syntax "%A.B"
means to use B digits after decimal point. The meaning of the A
is more complicated, but can be read about here.
<?php
function current_url()
{
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return $validURL;
}
//echo "page URL is : ".current_url();
$offer_url = current_url();
?>
<?php
if ($offer_url == "checking url name") {
?> <p> hi this is manip5595 </p>
<?php
}
?>
You can copy the contents of the export_graphviz file and you can paste the same in the webgraphviz.com site.
You can check out the article on How to visualize the decision tree in Python with graphviz for more information.
Using msbuild
as pointed out by others worked for me but I needed to do a bit more than just that. First of all, msbuild
needs to have access to the compiler. This can be done by running:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"
Then msbuild
was not in my $PATH so I had to run it via its explicit path:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" myproj.sln
Lastly, my project was making use of some variables like $(VisualStudioDir)
. It seems those do not get set by msbuild
so I had to set them manually via the /property
option:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" /property:VisualStudioDir="C:\Users\Administrator\Documents\Visual Studio 2013" myproj.sln
That line then finally allowed me to compile my project.
Bonus: it seems that the command line tools do not require a registration after 30 days of using them like the "free" GUI-based Visual Studio Community edition does. With the Microsoft registration requirement in place, that version is hardly free. Free-as-in-facebook if anything...
This is a fairly old question, but I'm going to put in my 2 cents as there are a lot of answers, but none showing all possible methods in a clear and concise manner (not sure about the concise bit, as this got a bit out of hand. TL;DR ).
I'm assuming that the OP wanted to return the array that was passed in without copying as some means of directly passing this to the caller to be passed to another function to make the code look prettier.
However, to use an array like this is to let it decay into a pointer and have the compiler treat it like an array. This can result in subtle bugs if you pass in an array like, with the function expecting that it will have 5 elements, but your caller actually passes in some other number.
There a few ways you can handle this better. Pass in a std::vector
or std::array
(not sure if std::array
was around in 2010 when the question was asked). You can then pass the object as a reference without any copying/moving of the object.
std::array<int, 5>& fillarr(std::array<int, 5>& arr)
{
// (before c++11)
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
// Note the following are for c++11 and higher. They will work for all
// the other examples below except for the stuff after the Edit.
// (c++11 and up)
for(auto it = std::begin(arr); it != std::end(arr); ++it)
{ /* do stuff */ }
// range for loop (c++11 and up)
for(auto& element : arr)
{ /* do stuff */ }
return arr;
}
std::vector<int>& fillarr(std::vector<int>& arr)
{
for(auto it = arr.begin(); it != arr.end(); ++it)
{ /* do stuff */ }
return arr;
}
However, if you insist on playing with C arrays, then use a template which will keep the information of how many items in the array.
template <size_t N>
int(&fillarr(int(&arr)[N]))[N]
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
Except, that looks butt ugly, and super hard to read. I now use something to help with that which wasn't around in 2010, which I also use for function pointers:
template <typename T>
using type_t = T;
template <size_t N>
type_t<int(&)[N]> fillarr(type_t<int(&)[N]> arr)
{
// N is easier and cleaner than specifying sizeof(arr)/sizeof(arr[0])
for(int* it = arr; it != arr + N; ++it)
{ /* do stuff */ }
return arr;
}
This moves the type where one would expect it to be, making this far more readable. Of course, using a template is superfluous if you are not going to use anything but 5 elements, so you can of course hard code it:
type_t<int(&)[5]> fillarr(type_t<int(&)[5]> arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
As I said, my type_t<>
trick wouldn't have worked at the time this question was asked. The best you could have hoped for back then was to use a type in a struct:
template<typename T>
struct type
{
typedef T type;
};
typename type<int(&)[5]>::type fillarr(typename type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Which starts to look pretty ugly again, but at least is still more readable, though the typename
may have been optional back then depending on the compiler, resulting in:
type<int(&)[5]>::type fillarr(type<int(&)[5]>::type arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
And then of course you could have specified a specific type, rather than using my helper.
typedef int(&array5)[5];
array5 fillarr(array5 arr)
{
// Prefer using the compiler to figure out how many elements there are
// as it reduces the number of locations where you have to change if needed.
for(int* it = arr; it != arr + sizeof(arr)/sizeof(arr[0]); ++it)
{ /* do stuff */ }
return arr;
}
Back then, the free functions std::begin()
and std::end()
didn't exist, though could have been easily implemented. This would have allowed iterating over the array in a safer manner as they make sense on a C array, but not a pointer.
As for accessing the array, you could either pass it to another function that takes the same parameter type, or make an alias to it (which wouldn't make much sense as you already have the original in that scope). Accessing a array reference is just like accessing the original array.
void other_function(type_t<int(&)[5]> x) { /* do something else */ }
void fn()
{
int array[5];
other_function(fillarr(array));
}
or
void fn()
{
int array[5];
auto& array2 = fillarr(array); // alias. But why bother.
int forth_entry = array[4];
int forth_entry2 = array2[4]; // same value as forth_entry
}
To summarize, it is best to not allow an array decay into a pointer if you intend to iterate over it. It is just a bad idea as it keeps the compiler from protecting you from shooting yourself in the foot and makes your code harder to read. Always try and help the compiler help you by keeping the types as long as possible unless you have a very good reason not to do so.
Oh, and for completeness, you can allow it to degrade to a pointer, but this decouples the array from the number of elements it holds. This is done a lot in C/C++ and is usually mitigated by passing the number of elements in the array. However, the compiler can't help you if you make a mistake and pass in the wrong value to the number of elements.
// separate size value
int* fillarr(int* arr, size_t size)
{
for(int* it = arr; it != arr + size; ++it)
{ /* do stuff */ }
return arr;
}
Instead of passing the size, you can pass the end pointer, which will point to one past the end of your array. This is useful as it makes for something that is closer to the std algorithms, which take a begin and and end pointer, but what you return is now only something that you must remember.
// separate end pointer
int* fillarr(int* arr, int* end)
{
for(int* it = arr; it != end; ++it)
{ /* do stuff */ }
return arr;
}
Alternatively, you can document that this function will only take 5 elements and hope that the user of your function doesn't do anything stupid.
// I document that this function will ONLY take 5 elements and
// return the same array of 5 elements. If you pass in anything
// else, may nazal demons exit thine nose!
int* fillarr(int* arr)
{
for(int* it = arr; it != arr + 5; ++it)
{ /* do stuff */ }
return arr;
}
Note that the return value has lost it's original type and is degraded to a pointer. Because of this, you are now on your own to ensure that you are not going to overrun the array.
You could pass a std::pair<int*, int*>
, which you can use for begin and end and pass that around, but then it really stops looking like an array.
std::pair<int*, int*> fillarr(std::pair<int*, int*> arr)
{
for(int* it = arr.first; it != arr.second; ++it)
{ /* do stuff */ }
return arr; // if you change arr, then return the original arr value.
}
void fn()
{
int array[5];
auto array2 = fillarr(std::make_pair(&array[0], &array[5]));
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
or
void other_function(std::pair<int*, int*> array)
{
// Can be done, but you have the original array in scope, so why bother.
int fourth_element = array2.first[4];
}
void fn()
{
int array[5];
other_function(fillarr(std::make_pair(&array[0], &array[5])));
}
Funny enough, this is very similar to how std::initializer_list
work (c++11), but they don't work in this context.
You can install vim/vi for windows and set windows PATH variable and open it in command line.
The widely-upvoted answer is fine, I've used it for quite some time in the form of this bat file:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET ROOT=%cd%
REM Get the tools.zip from the innards of the installer
7z e *.exe .rsrc/1033/JAVA_CAB10/111
7z e 111 7z x tools.zip
REM Extract all
7z x -aoa tools.zip -ojdk
del tools.zip
del 111
REM Searching directory structure from root for subfolders and zipfiles.
FOR /F "delims==" %%d IN ('dir /ogne /ad /b /s "%ROOT%"') DO (
echo Descending into %%d
FOR /F "delims==" %%f IN ('dir /b "%%d\*.pack"') DO (
echo Extracting "%%d\%%f"
REM Extract all packs into jars.
jdk\bin\unpack200 -r "%%d\%%f" "%%d\%%~nf.jar"
)
)
ENDLOCAL
pause;
It requires access on the path to 7zip, and must be run in a folder alongside the JDK of your choice (it'll find it because of the *.exe up here).
Works on 8u144, and I guess it worked from the 8u20 thing.
You can just use the method uniq
. Assuming your array is ary
, call:
ary.uniq{|x| x.user_id}
and this will return a set with unique user_id
s.
You can even develop your own split function (I know, little old-fashioned):
size_t split(const std::string &txt, std::vector<std::string> &strs, char ch)
{
size_t pos = txt.find( ch );
size_t initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
return strs.size();
}
Then you just need to invoke it with a vector<string> as argument:
int main()
{
std::vector<std::string> v;
split( "This is a test", v, ' ' );
dump( cout, v );
return 0;
}
Find the code for splitting a string in IDEone.
Hope this helps.
A)
String str = "a string";
int length = str.length( ); // length == 8
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29
edit
If you want to count the number of a specific type of characters in a String
, then a simple method is to iterate through the String
checking each index against your test case.
int charCount = 0;
char temp;
for( int i = 0; i < str.length( ); i++ )
{
temp = str.charAt( i );
if( temp.TestCase )
charCount++;
}
where TestCase
can be isLetter( )
, isDigit( )
, etc.
Or if you just want to count everything but spaces, then do a check in the if
like temp != ' '
B)
String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'
http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29
dplyr
packageIf the function that you want to apply is vectorized,
then you could use the mutate
function from the dplyr
package:
> library(dplyr)
> myf <- function(tens, ones) { 10 * tens + ones }
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mutate(x, value = myf(tens, ones))
hundreds tens ones value
1 7 1 4 14
2 8 2 5 25
3 9 3 6 36
plyr
packageIn my humble opinion,
the tool best suited to the task is mdply
from the plyr
package.
Example:
> library(plyr)
> x <- data.frame(tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
tens ones V1
1 1 4 14
2 2 5 25
3 3 6 36
Unfortunately, as Bertjan Broeksema pointed out,
this approach fails if you don't use all the columns of the data frame
in the mdply
call.
For example,
> library(plyr)
> x <- data.frame(hundreds = 7:9, tens = 1:3, ones = 4:6)
> mdply(x, function(tens, ones) { 10 * tens + ones })
Error in (function (tens, ones) : unused argument (hundreds = 7)
I have written a crontab deploy tool in python: https://github.com/monklof/deploycron
pip install deploycron
Install your crontab is very easy, this will merge the crontab into the system's existing crontab.
from deploycron import deploycron
deploycron(content="* * * * * echo hello > /tmp/hello")
Integer[] arrayInteger = {1,2,3,4,3,2,4,6,7,8,9,9,10};
Set set = new HashSet();
for(Integer i:arrayInteger)
set.add(i);
System.out.println(set);
After authentication is in place, JSON hijacking protection can take a variety of forms. Google appends while(1) into their JSON data, so that if any malicious script evaluates it, the malicious script enters an infinite loop.
Reference: Web Security Testing Cookbook: Systematic Techniques to Find Problems Fast
import csv
from collections import defaultdict
columns = defaultdict(list) # each value in each column is appended to a list
with open('file.txt') as f:
reader = csv.DictReader(f) # read rows into a dictionary format
for row in reader: # read a row as {column1: value1, column2: value2,...}
for (k,v) in row.items(): # go over each column name and value
columns[k].append(v) # append the value into the appropriate list
# based on column name k
print(columns['name'])
print(columns['phone'])
print(columns['street'])
With a file like
name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.
Will output
>>>
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']
Or alternatively if you want numerical indexing for the columns:
with open('file.txt') as f:
reader = csv.reader(f)
reader.next()
for row in reader:
for (i,v) in enumerate(row):
columns[i].append(v)
print(columns[0])
>>>
['Bob', 'James', 'Smithers']
To change the deliminator add delimiter=" "
to the appropriate instantiation, i.e reader = csv.reader(f,delimiter=" ")
I am a Linux guy. In Linux it is extremely easy with netstat -ltpn
or any combination of those letters. But in Mac OS X netstat -an | grep LISTEN
is the most humane. Others are very ugly and very difficult to remember when troubleshooting.
Did you check your Project Properties -> Project Facets
panel? (From that post)
A WTP project is composed of multiple units of functionality (known as facets).
The Java facet version needs to always match the java compiler compliance level.
The best way to change java level is to use the Project Facets properties panel as that will update both places at the same time.
The "
Project->Preferences->Project Facets
" stores its configuration in this file, "org.eclipse.wst.common.project.facet.core.xml
", under the ".settings
" directory.The content might look like this
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="WebSphere Application Server v6.1"/>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.java" version="5.0"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jsf.ibm" version="7.0"/>
<installed facet="jsf.base" version="7.0"/>
<installed facet="web.jstl" version="1.1"/>
</faceted-project>
Check also your Java compliance level:
SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp
you need to use a query like this:
select * from mytable where msisdn like '%7%'
or
select * from mytable where msisdn like '56655%'
Here is my several hours... Reading whole file line by line.
char * readline(FILE *fp, char *buffer)
{
int ch;
int i = 0;
size_t buff_len = 0;
buffer = malloc(buff_len + 1);
if (!buffer) return NULL; // Out of memory
while ((ch = fgetc(fp)) != '\n' && ch != EOF)
{
buff_len++;
void *tmp = realloc(buffer, buff_len + 1);
if (tmp == NULL)
{
free(buffer);
return NULL; // Out of memory
}
buffer = tmp;
buffer[i] = (char) ch;
i++;
}
buffer[i] = '\0';
// Detect end
if (ch == EOF && (i == 0 || ferror(fp)))
{
free(buffer);
return NULL;
}
return buffer;
}
void lineByline(FILE * file){
char *s;
while ((s = readline(file, 0)) != NULL)
{
puts(s);
free(s);
printf("\n");
}
}
int main()
{
char *fileName = "input-1.txt";
FILE* file = fopen(fileName, "r");
lineByline(file);
return 0;
}
I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:
query.exec(function (err, results){
if (err) res.writeHead(500, err.message)
else if (!results.length) res.writeHead(404);
else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
}
res.end();
});
A simply Python script that converts line endings from Unix to Windows that I stuck in my system32 directory. It's been lost to the ages for a few months, now, but basically it'd convert a list of known text-based file types to Windows line endings, and you could specify which files to convert, or all files, for a wildcard list.
strstr(request, "favicon") != NULL
I needed to apply a translation to the Ok and Cancel buttons. I modified the code to except dynamic text (calls my translation function)
$.extend({_x000D_
confirm: function(message, title, okAction) {_x000D_
$("<div></div>").dialog({_x000D_
// Remove the closing 'X' from the dialog_x000D_
open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },_x000D_
width: 500,_x000D_
buttons: [{_x000D_
text: localizationInstance.translate("Ok"),_x000D_
click: function () {_x000D_
$(this).dialog("close");_x000D_
okAction();_x000D_
}_x000D_
},_x000D_
{_x000D_
text: localizationInstance.translate("Cancel"),_x000D_
click: function() {_x000D_
$(this).dialog("close");_x000D_
}_x000D_
}],_x000D_
close: function(event, ui) { $(this).remove(); },_x000D_
resizable: false,_x000D_
title: title,_x000D_
modal: true_x000D_
}).text(message);_x000D_
}_x000D_
});
_x000D_
For some reason the android:textColor only seems to update the title color. You can change the message text color by using a
SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));
AlertDialog dialog = builder.create();
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dialog.setMessage(wordtoSpan);
dialog.show();
Thank you so much to @Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
The solution Bobince posted works perfectly for me. I wanted to offer an alternative method as well for future visitors:
if (typeof(jQuery) == 'undefined') {
(function() {
var sct = document.createElement('script');
sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
sct.type = 'text/javascript';
sct.async = 'true';
var domel = document.getElementsByTagName('script')[0];
domel.parentNode.insertBefore(sct, domel);
})();
}
In this example, I've included a conditional load for jQuery to demonstrate use case. Hope that's useful for someone!
I have met the same problem as I install it globally, then I try to install it locally, and it work.
This one get everything between the "." characters. Please note this won't work for more complex URLs like "www.somesite.co.uk" Ideally the function would check for how many instances of the "." character and choose the substring accordingly.
CREATE FUNCTION dbo.GetURL (@URL VARCHAR(250))
RETURNS VARCHAR(250)
AS BEGIN
DECLARE @Work VARCHAR(250)
SET @Work = @URL
SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, LEN(@work))
SET @Work = SUBSTRING(@work, 0, CHARINDEX('.', @work))
--Alternate:
--SET @Work = SUBSTRING(@work, CHARINDEX('.', @work) + 1, CHARINDEX('.', @work) + 1)
RETURN @work
END
In pseudocode:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
You can get mac address:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String mac = wInfo.getMacAddress();
Set Permission in Menifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<form id="thisForm" enctype='multipart/form-data'>
<input type="file" name="file" id="file">
</form>
<script>
$(document).on('ready', function(){
$('#file').on('change', function(){
$('#thisForm').submit();
});
});
</script>
To expand on Dennis's answer, use awk
's -v
option to pass the i
and j
values:
# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'
BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).
From here.
It is implemented using an int[]
:
110 /**
111 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
112 * zeroth element of this array is the most-significant int of the
113 * magnitude. The magnitude must be "minimal" in that the most-significant
114 * int ({@code mag[0]}) must be non-zero. This is necessary to
115 * ensure that there is exactly one representation for each BigInteger
116 * value. Note that this implies that the BigInteger zero has a
117 * zero-length mag array.
118 */
119 final int[] mag;
From the source
From the Wikipedia article Arbitrary-precision arithmetic:
Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.
HashMap
is implemented by Hash Table while TreeMap
is implemented by Red-Black tree
. The main difference between HashMap
and TreeMap
actually reflect the main difference between a Hash
and a Binary Tree
, that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.
Take a look at following diagram.
Referred link has correct answer, but there are written some libraries to make your work easy.
So don't write all code again, just use any of these library and get your work done in little time.
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
I've been searching for hours and no one could help me. I did a simple thing to solve this problem. (WINDOWS 10 x64)
Follow this:
1 - Go to your php_mysqli.dll path (in my case: C:/xampp/php/ext);
2 - Move the php_mysqli.dll to the previous folder (C:/xampp/php);
3 - Open php.ini and search the line: "extension: php_mysqli.dll";
4 - Change to the path where is your file: extension="C:\xampp\php\php_mysqli.dll";
5 - Restart your application (wampp, xampp, etc.) and start Apache Server;
The problem was the path ext/php_mysqli.dll, I've tried changing the line to extension="C:\xampp\php\ext\php_mysqli.dll" but doesn't worked.
Consider this example :
var array = new string[2]
{
"I like what I like",
"I like what you like"
};
//query1 returns two elements sth like this:
//fisrt element would be array[5] :[0] = "I" "like" "what" "I" "like"
//second element would be array[5] :[1] = "I" "like" "what" "you" "like"
IEnumerable<string[]> query1 = array.Select(s => s.Split(' ')).Distinct();
//query2 return back flat result sth like this :
// "I" "like" "what" "you"
IEnumerable<string> query2 = array.SelectMany(s => s.Split(' ')).Distinct();
So as you see duplicate values like "I" or "like" have been removed from query2 because "SelectMany" flattens and projects across multiple sequences. But query1 returns sequence of string arrays. and since there are two different arrays in query1 (first and second element), nothing would be removed.
Try interface{}
instead. To cast back as slice, try
func foo(bar interface{}) {
s := bar.([]string)
// ...
}
There is a new NuGet package that contains the System.Windows.Interactivity.dll that is compatible with:
To install Expression.Blend.Sdk, run the following command in the Package Manager Console
PM> Install-Package Expression.Blend.Sdk
Use $push
to update document and insert new value inside an array.
find:
db.getCollection('noti').find({})
result for find:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
update:
db.getCollection('noti').findOneAndUpdate(
{ _id: ObjectId("5bc061f05a4c0511a9252e88") },
{ $push: {
graph: {
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
}
})
result for update:
{
"_id" : ObjectId("5bc061f05a4c0511a9252e88"),
"count" : 1.0,
"color" : "green",
"icon" : "circle",
"graph" : [
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 2.0
},
{
"date" : ISODate("2018-10-24T08:55:13.331Z"),
"count" : 3.0
}
],
"name" : "online visitor",
"read" : false,
"date" : ISODate("2018-10-12T08:57:20.853Z"),
"__v" : 0.0
}
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
This is the one. The session will last for 1440 seconds (24 minutes).
session.gc_maxlifetime 1440 1440
--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----
For this you will need to use a Service or a Factory.
The services are the BEST PRACTICE to share data between not nested controllers.
A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.
I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!
A $scope element should be created like this:
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// best practice, always use a model
$scope.someModel = {
someValue: 'hello computer'
});
And not like this:
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// anti-pattern, bare value
$scope.someBareValue = 'hello computer';
};
});
This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as
<div ng-model="someModel.someValue"></div> //NOTICE THE DOT.
This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....
But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.
Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.
If from your controller you want to GET the objectC into your scope, is a mistake to say:
$scope.neededObjectInController = Factory.objectA.objectB.objectC;
That wont work... Instead use only one dot.
$scope.neededObjectInController = Factory.ObjectA;
Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.
If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.
I believe tuple()
takes a list as an argument
For example,
tuple([1,2,3]) # returns (1,2,3)
see what happens if you wrap your array with brackets
This is a quite old request to reply but I want to give a short answer for newcommers. I had the same problem while working on an eight-languaged site. The problem is IDE based. The solution is to use Komodo Edit as code-editor. I tried many editors until I found one which doesnt change charset-settings of my pages. Dreamweaver (or almost all of others) change all pages code-page/charset settings whenever you change it for page. When you have changes in more than one page and have changed charset of any file then clicked "Save all", all open pages (including unchanged but assumed changed by editor because of charset) are silently re-assigned the new charset and all mismatching pages are broken down. I lost months on re-translating messages again and again until I discovered that Komodo Edit keeps settings separately for each file.
As mentioned before, you can't use inline elements for styling pseudo classes. Before and after pseudo classes are states of elements, not actual elements. You could only possibly use JavaScript for this.
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
move you mouse over the "Hello, playground" on the right side bar, you will see an eye icon and a small circle icon next it. Just click on the circle one to show the detail page and console output!
$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.
example:
var self = 'some string';
var $self = 'another string';
These are declared as two different variables. It's like putting underscore before private variables.
A somewhat popular pattern is:
var foo = 'some string';
var $foo = $('.foo');
That way, you know $foo is a cached jQuery object later on in the code.
I believe this error message is due to a "zombie transaction".
Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?
It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.
Can you debug into the error code? Do you have a stack trace?
It is impossible for any program, in any language, to handle a SIGKILL. This is so it is always possible to terminate a program, even if the program is buggy or malicious. But SIGKILL is not the only means for terminating a program. The other is to use a SIGTERM. Programs can handle that signal. The program should handle the signal by doing a controlled, but rapid, shutdown. When a computer shuts down, the final stage of the shutdown process sends every remaining process a SIGTERM, gives those processes a few seconds grace, then sends them a SIGKILL.
The way to handle this for anything other than kill -9
would be to register a shutdown hook. If you can use (SIGTERM) kill -15
the shutdown hook will work. (SIGINT) kill -2
DOES cause the program to gracefully exit and run the shutdown hooks.
Registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
- The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.
I tried the following test program on OSX 10.6.3 and on kill -9
it did NOT run the shutdown hook, as expected. On a kill -15
it DOES run the shutdown hook every time.
public class TestShutdownHook
{
public static void main(String[] args) throws InterruptedException
{
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
while (true)
{
Thread.sleep(1000);
}
}
}
There isn't any way to really gracefully handle a kill -9
in any program.
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.
The only real option to handle a kill -9
is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled the ps
command looking for your program in the list and act accordingly when it disappeared.
#!/usr/bin/env bash
java TestShutdownHook
wait
# notify your other app that you quit
echo "TestShutdownHook quit"
The overall winner between using the np.sum, np.min, and all seems to be np.min in terms of speed for large arrays:
N = 1000000
def func_sum(x):
my_list = np.random.randn(N)
return np.sum(my_list < x )==0
def func_min(x):
my_list = np.random.randn(N)
return np.min(my_list) >= x
def func_all(x):
my_list = np.random.randn(N)
return all(i >= x for i in my_list)
(i need to put the np.array definition inside the function, otherwise the np.min function remembers the value and does not do the computation again when testing for speed with timeit)
The performance of "all" depends very much on when the first element that does not satisfy the criteria is found, the np.sum needs to do a bit of operations, the np.min is the lightest in terms of computations in the general case.
When the criteria is almost immediately met and the all loop exits fast, the all function is winning just slightly over np.min:
>>> %timeit func_sum(10)
10 loops, best of 3: 36.1 ms per loop
>>> %timeit func_min(10)
10 loops, best of 3: 35.1 ms per loop
>>> %timeit func_all(10)
10 loops, best of 3: 35 ms per loop
But when "all" needs to go through all the points, it is definitely much worse, and the np.min wins:
>>> %timeit func_sum(-10)
10 loops, best of 3: 36.2 ms per loop
>>> %timeit func_min(-10)
10 loops, best of 3: 35.2 ms per loop
>>> %timeit func_all(-10)
10 loops, best of 3: 230 ms per loop
But using
np.sum(my_list<x)
can be very useful is one wants to know how many values are below x.
As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.
I am using ubuntu 14.04.
The correct way in my system should be date +%s
.
The output of date +%T
is like 12:25:25
.
Came here looking for an answer to this question myself. The slice answer is probably best, but I went ahead and created a "last" function just to practice extending prototypes, so I thought I would go ahead and share it. It has the added benefit over some other ones of letting you optionally count backwards through the array, and pull out, say, the second to last or third to last item. If you don't specify a count it just defaults to 1 and pulls out the last item.
Array.prototype.last = Array.prototype.last || function(count) {
count = count || 1;
var length = this.length;
if (count <= length) {
return this[length - count];
} else {
return null;
}
};
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.last(); // returns 9
arr.last(4); // returns 6
arr.last(9); // returns 1
arr.last(10); // returns null
Try This..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="right" >
<TextView android:text="TextView" android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
It's quite simple actually if you're using PostgreSQL, just use distinct(columns)
(documentation).
Productorder.objects.all().distinct('category')
Note that this feature has been included in Django since 1.4
Use this code on button click in activity and When return back to another activity just finish previous activity by setting flag in intent then put only one Activity in the Stack and destroy the previous one.
Intent i=new Intent("this","YourClassName.Class");
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
please try this below command :
sudo php artisan cache:clear
sudo php artisan view:clear
sudo php artisan config:cache
If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.
Go to Search > Find in Files
(Ctrl+Shift+F for the keyboard addicted) and enter:
(test1|test2)
*.txt
Follow current doc.
to have the path of the current file to be filled.Regular Expression
Try a list comprehension:
l = [x * 2 for x in l]
This goes through l
, multiplying each element by two.
Of course, there's more than one way to do it. If you're into lambda functions and map
, you can even do
l = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2
to each element in l
. This is equivalent to:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map()
returns a map object, not a list, so if you really need a list afterwards you can use the list()
function afterwards, for instance:
l = list(map(timesTwo, l))
Thanks to Minyc510 in the comments for this clarification.
Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.
I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.
here is a copy of the script I made for your solution but have dos2unix installed.
#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"
this script has been tested on 3 machines with no errors.
this solution gets rid of the pesky 2nd click when showing the popover for the second time
tested with with Bootstrap v3.3.7
$('body').on('click', function (e) {
$('.popover').each(function () {
var popover = $(this).data('bs.popover');
if (!popover.$element.is(e.target)) {
popover.inState.click = false;
popover.hide();
}
});
});
It will return 18 results starting on record #9 and finishing on record #26.
Start by reading the query from offset
. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.
Check this out.
And also the official documentation.
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
Using org.apache.commons.lang3.time.DateUtils
Date pDate = new Date();
DateUtils.truncate(pDate, Calendar.DAY_OF_MONTH);
If you are using Lotus Notes V9.X, it is better to drag the mail to desktop as .eml and then attach it to the mail. Safest way so far.
Square brackets are meant for character class, and you're actually trying to match any one of: s
, |
, s
(again), e
, a
, s
(again), o
and n
.
Use parentheses instead for grouping:
(s|season)
or non-capturing group:
(?:s|season)
Note: Non-capture groups tell the engine that it doesn't need to store the match, while the other one (capturing group does). For small stuff, either works, for 'heavy duty' stuff, you might want to see first if you need the match or not. If you don't, better use the non-capture group to allocate more memory for calculation instead of storing something you will never need to use.
check your image cmd
using the command docker inspect image_name
. The output might be like this:
"Cmd": [
"/bin/bash",
"-c",
"#(nop) ",
"CMD [\"/bin/bash\"]"
],
So use the command docker exec -it container_id /bin/bash
. If your cmd
output is different like this:
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"/bin/sh\"]"
],
Use /bin/sh
instead of /bin/bash
in the command above.
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
tl;dr for folks looking here for an ISO formatted date:
instead of using something like '%Y-%m-%d %H:%M:%S.%03d%z', create your own class as @unutbu indicated. Here's one for iso date format:
import logging
from time import gmtime, strftime
class ISOFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
t = strftime("%Y-%m-%dT%H:%M:%S", gmtime(record.created))
z = strftime("%z",gmtime(record.created))
s = "%s.%03d%s" % (t, record.msecs,z)
return s
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = ISOFormatter(fmt='%(asctime)s - %(module)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logger.debug('Jackdaws love my big sphinx of quartz.')
#2020-10-23T17:25:48.310-0800 - <stdin> - DEBUG - Jackdaws love my big sphinx of quartz.
XML is so versatile...
<DATA>
<BINARY>
<BIT index="0">0</BIT>
<BIT index="1">0</BIT>
<BIT index="2">1</BIT>
...
<BIT index="n">1</BIT>
</BINARY>
</DATA>
XML is like violence - If it doesn't solve your problem, you're not using enough of it.
EDIT:
BTW: Base64 + CDATA is probably the best solution
(EDIT2:
Whoever upmods me, please also upmod the real answer. We don't want any poor soul to come here and actually implement my method because it was the highest ranked on SO, right?)
Not sure I'm further contributing to the subject but still thought I'd share: I once found this blog post to have some quite helpful (though very basic) explanations & examples on Big O:
Via examples, this helped get the bare basics into my tortoiseshell-like skull, so I think it's a pretty descent 10-minute read to get you headed in the right direction.
Be careful with the 'while(!feof ... fgets()' stuff, fgets can get an error (returnfing false) and loop forever without reaching the end of file. codaddict was closest to being correct but when your 'while fgets' loop ends, check feof; if not true, then you had an error.
Another difference not pointed out is that giving the struct a name (i.e. struct myStruct) also enables you to provide forward declarations of the struct. So in some other file, you could write:
struct myStruct;
void doit(struct myStruct *ptr);
without having to have access to the definition. What I recommend is you combine your two examples:
typedef struct myStruct{
int one;
int two;
} myStruct;
This gives you the convenience of the more concise typedef name but still allows you to use the full struct name if you need.
Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as
This will be inserted \n This will not be
or
This will be inserted
This will not be
Also, what interface are you using? Is it possible that something along the way is eating your backslashes?
Use Split() function to slice them and ToList() to return them as a list.
var names = "Brian,Joe,Chris";
List<string> nameList = names.Split(',').ToList();
You can use AngularJS build-in service $rootScope
and inject this service in both of your controllers.
You can then listen for events that are fired on $rootScope object.
$rootScope provides two event dispatcher called $emit and $broadcast
which are responsible for dispatching events(may be custom events) and use $rootScope.$on
function to add event listener.
I would definitely advise you to have a look at System.Diagnostics.Stopwatch
And when I looked around for more about Stopwatch I found this site;
There mentioned another possibility
Process.TotalProcessorTime
Just put an empty string in the radix place, because parseInt() take two arguments:
parseInt(string, radix);
string The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.
radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above-mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.
imageIndex = parseInt(id.substring(id.length - 1))-1;
imageIndex = parseInt(id.substring(id.length - 1), '')-1;
In Webdriver, you should use driver.switchTo().defaultContent();
to get out of a frame.
You need to get out of all the frames first, then switch into outer frame again.
// between step 4 and step 5
// remove selenium.selectFrame("relative=up");
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("cq-cf-frame");
// now continue step 6
driver.findElement(By.xpath("//button[text()='OK']")).click();
If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.
If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.
public void fixedAdd(List<Integer> list, int val, int size) {
list.add(val);
if(list.size() > size) list.remove(0);
}
LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.
Give it a display:inline-block
in CSS - that should let it do what you want.
In terms of compatibility: IE6/7 will work with this, as quirks mode suggests:
IE 6/7 accepts the value only on elements with a natural display: inline.
You can simply do conditional check before doing map like
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
})
}
Now a days .map can be done in two different ways but still the conditional check is required like
.map with return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
return <li key={player.championId}>{player.summonerName}</li>
})
}
.map without return
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
return <li key={player.championId}>{player.summonerName}</li>
))
}
both the above functionalities does the same
Your command is right, but the error shows that you didn't create your ssh key yet. To generate new ssh key enter the following command into the terminal.
ssh-keygen
After entering the command then you will be asked to enter file name and passphrase. Normally you don't need to change this. Just press enter. Then your key will be generated in ~/.ssh
directory. After this, you can copy your key by the following command.
pbcopy < ~/.ssh/id_rsa.pub
or
cat .ssh/id_rsa.pub | pbcopy
You can find more about this here ssh.
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
echo "matched";
else
echo "no match";
fi
Add this function at the beginning of your script :
import sys, os
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
Refer to your data files by calling the function resource_path()
, like this:
resource_path('myimage.gif')
Then use this command:
pyinstaller --onefile --windowed --add-data todo.ico;. script.py
For more information visit this documentation page.
You have to add an OnItemClickListener to the listview to determine which item was clicked, then find the checkbox.
mListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox_id);
}
});
If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:
Boolean var= new anonymousClass(){
private String myVar; //String for example
@Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);
If you don't know the position of the item, you may need to find the index first:
old_index = list1.index(item)
then move it:
list1.insert(new_index, list1.pop(old_index))
or IMHO a cleaner way:
try:
list1.remove(item)
list1.insert(new_index, item)
except ValueError:
pass
Check the "/Applications/XAMPP/xamppfiles/var/mysql" file's owner.
If you see different user and group instead of "_mysql".
sudo chown -R _mysql:_mysql mysql