open
is a new access level in Swift 3, introduced with the implementation
of
It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6.
In short:
open
class is accessible and subclassable outside of the
defining module. An open
class member is accessible and
overridable outside of the defining module.public
class is accessible but not subclassable outside of the
defining module. A public
class member is accessible but
not overridable outside of the defining module.So open
is what public
used to be in previous
Swift releases and the access of public
has been restricted.
Or, as Chris Lattner puts it in
SE-0177: Allow distinguishing between public access and public overridability:
“open” is now simply “more public than public”, providing a very simple and clean model.
In your example, open var hashValue
is a property which is accessible and can be overridden in NSObject
subclasses.
For more examples and details, have a look at SE-0117.
Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?
My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:
At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "{{.URL}}",
dom_id: '#swagger-ui',
validatorUrl: null,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
,
layout: "StandaloneLayout",
requestInterceptor: (req) => {
req.headers.Authorization = "Bearer " + req.headers.Authorization
return req
}
})
window.ui = ui
}
Did you set the OS_ACTIVITY_MODE variable by any chance? To check if you have this variable set (and turn it off), in Xcode 9, do the following:
Select from Xcode menu Product -> Scheme -> Edit Scheme..
Select the Run scheme and look under Arguments.
If you see the OS_ACTIVITY_MODE variable checked, deselect it
Swift 4 Version
If you want to create a name for NotificationCenter:
extension Notification.Name {
static let updateDataList1 = Notification.Name("updateDataList1")
}
Subscribe to notifications:
NotificationCenter.default.addObserver(self, selector: #selector(youFunction), name: .updateDataList1, object: nil)
Send notification:
NotificationCenter.default.post(name: .updateDataList1, object: nil)
If you just want a class with variables to use:
class Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
Or:
struct Keys {
static let key1 = "YOU_KEY"
static let key2 = "YOU_KEY"
}
At this point in your code the view controller's view has only been created but not added to any view hierarchy. If you want to present from that view controller as soon as possible you should do it in viewDidAppear
to be safest.
This has already been answered by @Craig Otis, but the issue is caused when the classes in question do not belong to the same targets, usually the test target is missing. Just make sure the following check boxes are ticked.
To see the target membership. Select your file then open the file inspector (? + ? + 1) [option] + [command] + 1
I am calling the json on login button click
@IBAction func loginClicked(sender : AnyObject){
var request = NSMutableURLRequest(URL: NSURL(string: kLoginURL)) // Here, kLogin contains the Login API.
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(self.criteriaDic(), options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err1: NSError?
var json2 = NSJSONSerialization.JSONObjectWithData(strData.dataUsingEncoding(NSUTF8StringEncoding), options: .MutableLeaves, error:&err1 ) as NSDictionary
println("json2 :\(json2)")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json2["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
Here, I have made a seperate dictionary for the parameters.
var params = ["format":"json", "MobileType":"IOS","MIN":"f8d16d98ad12acdbbe1de647414495ec","UserName":emailTxtField.text,"PWD":passwordTxtField.text,"SigninVia":"SH"]as NSDictionary
return params
}
I had issues in that I would add classes to my objective-c bridging header, and in those objective-c headers that were imported, they were trying to import the swift header. It didn't like that.
So in all my objective-c classes that use swift, but are also bridged, the key was to make sure that you use forward class declarations in the headers, then import the "*-Swift.h" file in the .m file.
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
You could do this:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
This usually means that something is trying to access the @property "givenName".
If you were doing something with Interface Builder(IB)
, the usual cause is that you either:
SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.
FWIW, I got this error when I was implementing core data in to an existing project. It turned out I forgot to link CoreData.h to my project. I had already added the CoreData framework to my project but solved the issue by linking to the framework in my pre-compiled header just like Apple's templates do:
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#endif
Swift 4 answer:
// Define paragraph style - you got to pass it along to NSAttributedString constructor
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
// Define attributed string attributes
let attributes = [NSAttributedStringKey.paragraphStyle: paragraphStyle]
let attributedString = NSAttributedString(string:"Test", attributes: attributes)
Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project
QuartzCore.framework
For the bug
Undefined symbols for architecture i386:
You can try SDWebImage, it provides:
Quick example:
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults
to save and retrieve custom objects:
@interface NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;
@end
@implementation NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[self setObject:encodedObject forKey:key];
[self synchronize];
}
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
NSData *encodedObject = [self objectForKey:key];
id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
Usage:
[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];
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];
1) Is the synthesize within @implementation
block?
2) Should you refer to self.classA = [[ClassA alloc] init];
and self.classA.downloadUrl = @"..."
instead of plain classA
?
3) In your myApp.m
file you need to import ClassA.h
, when it's missing it will default to a number, or pointer? (in C variables default to int if not found by compiler):
#import "ClassA.h"
.
Like lucius said, it's not possible to have a C array property. Using an NSArray
is the way to go. An array only stores objects, so you'd have to use NSNumber
s to store your ints. With the new literal syntax, initialising it is very easy and straight-forward:
NSArray *doubleDigits = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @10 ];
Or:
NSMutableArray *doubleDigits = [NSMutableArray array];
for (int n = 1; n <= 10; n++)
[doubleDigits addObject:@(n)];
For more information: NSArray Class Reference, NSNumber Class Reference, Literal Syntax
Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:
p.name = [someName copy];
Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:
"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:
//person object has details of an individual you're assigning to a contact list.
Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;
//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.
In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.
I see that people have already talked about class path. Since there is no accepted answer, I assume it is not related to class path. So I would like to add that, not having package directive can also lead to class not found errors.
I do agree that perceived performance is really all that matters. But sometimes I just want to find out which method of doing something is faster. Sometimes the difference is HUGE and worth knowing.
You could just use javascript timers. But I typically get much more consistent results using the native Chrome (now also in Firefox and Safari) devTool methods console.time()
& console.timeEnd()
var iterations = 1000000;
console.time('Function #1');
for(var i = 0; i < iterations; i++ ){
functionOne();
};
console.timeEnd('Function #1')
console.time('Function #2');
for(var i = 0; i < iterations; i++ ){
functionTwo();
};
console.timeEnd('Function #2')
Chrome canary recently added Line Level Profiling the dev tools sources tab which let's you see exactly how long each line took to execute!
How and where is
app.run()
used? After module definition or afterapp.config()
, afterapp.controller()
?
In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js
Make it look like this
var app = angular.module('mean.dashboard', ['ui.bootstrap']);
app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
function($scope, Global, Dashboard) {
$scope.global = Global;
$scope.package = {
name: 'dashboard'
};
// ...
}
]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:
myLong = CLng(rs!AutoNumberField)
returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.
myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.
Configure the pivot table so that it is like this:
Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub
Add this to your CSS:
.menu i.large.icon,
.menu i.large.basic.icon {
vertical-align:baseline;
}
This is (of course) totally VM-dependent.
Browsing through the source code of OpenJDK 7 and 8 java.util.ArrayList
, .Hashtable
, .AbstractCollection
, .PriorityQueue
, and .Vector
, you can see this claim being repeated:
/** * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
which is added by Martin Buchholz (Google) on 2010-05-09; reviewed by Chris Hegarty (Oracle).
So, probably we can say that the maximum "safe" number would be 2 147 483 639 (Integer.MAX_VALUE - 8
) and "attempts to allocate larger arrays may result in OutOfMemoryError".
(Yes, Buchholz's standalone claim does not include backing evidence, so this is a calculated appeal to authority. Even within OpenJDK itself, we can see code like return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
which shows that MAX_ARRAY_SIZE
does not yet have a real use.)
The documentation from Github is really explanatory.
https://help.github.com/en/articles/adding-a-new-ssh-key-to-your-github-account https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
I think you must do the lasts steps from the guide to proper configure your keys
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa
Who needs trig when you have complex numbers:
#include <complex.h>
#include <math.h>
#define PI 3.14159265358979323846
typedef complex double Point;
Point point_on_circle ( double radius, double angle_in_degrees, Point centre )
{
return centre + radius * cexp ( PI * I * ( angle_in_degrees / 180.0 ) );
}
Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
If you have a border or padding, then the solution
html, body {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
}_x000D_
body {_x000D_
border: solid red 5px;_x000D_
border-radius: 2em;_x000D_
}
_x000D_
produces the imperfect rendering
To get it right in the presence of a border or padding
use instead
html, body {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
}_x000D_
body {_x000D_
box-sizing: border-box;_x000D_
border: solid red 5px;_x000D_
border-radius: 2em;_x000D_
}
_x000D_
as Martin pointed out, although overflow: hidden
is not needed.
(2018 - tested with Chrome 69 and IE 11)
You will need to use any javascript html calendar widget.
try this calendar view widget, just copy-paste some code shown in example there and thats it what you want.
Here is the link to Jquery Mobile date box - JQM datebox
I had the same issue was everyone else and tried all the above tricks, nothing worked. I even deleted and started fresh with a different developer account.
What worked for me in the end was
I don't know if you can enable that for a wildcard app, but after trying at least 12 different suggestions and losing a few days I hope this helps someone
For me, the cause was using a specific Zookeeper that was not part of the Kafka package. That Zookeeper was already installed on the machine for other purposes. Apparently Kafka does not work with just any Zookeeper. Switching to the Zookeeper that came with Kafka solved it for me. To not conflict with the existing Zookeeper, I had to modify my confguration to have the Zookeeper listen on a different port:
[root@host /opt/kafka/config]# grep 2182 *
server.properties:zookeeper.connect=localhost:2182
zookeeper.properties:clientPort=2182
SELECT name, GROUP_CONCAT( section )
FROM `tmp`
GROUP BY name
Select *
From Table
Where (col is null or col = '')
Or
Select *
From Table
Where IsNull(col, '') = ''
Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:
const profiles = await Profile.find({ user: {$exists: true, $ne: null }}) .select("-gallery") .sort( {_id: -1} ) .skip( skip ) .limit(10) .select(exclude) .populate({ path: 'user', match: { role: {$eq: customer}}, select: '-password -verified -_id -__v' }) .exec(); And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match). { "code": 200, "profiles": [ { "description": null, "province": "West Midlands", "country": "UK", "postal_code": "83000", "user": null }, { "description": null, "province": "Madrid", "country": "Spain", "postal_code": "43000", "user": { "role": "customer", "name": "pedrita", "email": "[email protected]", "created_at": "2020-06-05T11:05:36.450Z" } } ], "page": 1 }
Thanks in advance.
Also make sure the aspx page has AutoEventWireup="true"
and not AutoEventWireup="false"
To improve Darin's answer, it can be bit shorter:
public class UniqueFileName : ValidationAttribute
{
private readonly NewsService _newsService = new NewsService();
public override bool IsValid(object value)
{
if (value == null) { return false; }
var file = (HttpPostedFile) value;
return _newsService.IsFileNameUnique(file.FileName);
}
}
Model:
[UniqueFileName(ErrorMessage = "This file name is not unique.")]
Do note that an error message is required, otherwise the error will be empty.
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
Check out this code :-
/* Create Date Object */
Date date = new Date();
XMLGregorianCalendar xmlDate = null;
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
try{
xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("XMLGregorianCalendar :- " + xmlDate);
You can see complete example here
The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).
I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):
private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
if (width <= maxWidth && height <= maxHeight)
return { width, height };
else if (width / maxWidth > height / maxHeight)
return { width: maxWidth, height: height * maxWidth / width};
else
return { width: width * maxHeight / height, height: maxHeight };
}
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:
result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:
>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
I just had the same issue and this helped me:
html {
height: auto;
min-height: 100%;
background-size:cover;
}
If your input string could be less than five characters long then you should be aware that string.Substring
will throw an ArgumentOutOfRangeException
if the startIndex
argument is negative.
To solve this potential problem you can use the following code:
string sub = input.Substring(Math.Max(0, input.Length - 5));
Or more explicitly:
public static string Right(string input, int length)
{
if (length >= input.Length)
{
return input;
}
else
{
return input.Substring(input.Length - length);
}
}
SWIFT 3 Version of Alex Reynolds' Answer
let image = UIImage(named: "name") as UIImage?
let button = UIButton(type: UIButtonType.custom) as UIButton
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setImage(image, for: .normal)
button.addTarget(self, action: Selector("btnTouched:"), for:.touchUpInside)
self.view.addSubview(button)
My solution to this error was to update the typescript version with this command:
npm install -g typescript@latest
as I was using Windows.
However on Mac this can also be doable by sudo npm install -g typescript@latest
What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:
Exec sp_defaultdb @loginame='login', @defdb='master'
When you install Kafka in Centos7 with confluent :
yum install confluent-platform-oss-2.11
You can see the version of Kafka with :
yum deplist confluent-platform-oss-2.11
You can read : confluent-kafka-2.11 >= 0.10.2.1
I guess this is what you need. Try this .
<form action="" method="get">
<input name="search" type="text">
<input type="button" value="Search" onclick="return updateTable();">
</form>
and your javascript code is the same
function updateTable()
{
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
Different mouse buttons are used on each platform:
Left Mouse Button + Option
OR: Middle Mouse Button
Add to selection: Command
Subtract from selection: Command+Shift
Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
Subtract from selection: Alt
Right Mouse Button + Shift
Add to selection: Ctrl
Subtract from selection: Alt
ctrl + shift + ↑
ctrl + shift + ↓
ctrl + alt + ↑
ctrl + alt + ↓
ctrl + alt + ↑
ctrl + alt + ↓
Source: SublimeText2 Documentation
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
Based on the answer here by @Hendy Irawan
Show database sizes:
\l+
e.g.
=> \l+
berbatik_prd_commerce | berbatik_prd | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 19 MB | pg_default |
berbatik_stg_commerce | berbatik_stg | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 8633 kB | pg_default |
bursasajadah_prd | bursasajadah_prd | UTF8 | en_US.UTF-8 | en_US.UTF-8 | | 1122 MB | pg_default |
Show table sizes:
\d+
e.g.
=> \d+
public | tuneeca_prd | table | tomcat | 8192 bytes |
public | tuneeca_stg | table | tomcat | 1464 kB |
Only works in psql
.
One of the most memorable bugs I had was to do with an inline function that used alloca
. It manifested itself as a stack overflow (because it allocates on the stack) at random points of the program's execution.
In the header file:
void DoSomething() {
wchar_t* pStr = alloca(100);
//......
}
In the implementation file:
void Process() {
for (i = 0; i < 1000000; i++) {
DoSomething();
}
}
So what happened was the compiler inlined DoSomething
function and all the stack allocations were happening inside Process()
function and thus blowing the stack up. In my defence (and I wasn't the one who found the issue; I had to go and cry to one of the senior developers when I couldn't fix it), it wasn't straight alloca
, it was one of ATL string conversion macros.
So the lesson is - do not use alloca
in functions that you think might be inlined.
To fix the overlap, you only need modify the .navbar-toggle in your own css styles
something like this, it works for me:
.navbar-toggle{
z-index: 10;
}
Not need to change all config in file /opt/lampp/etc/extra/httpd-xampp.conf.
The only thing you need to change is the Require local
It's kinda obvious what Require local means so just change to Require all granted
Require all granted
Solution
from Require local
to Require all granted
if you use the JQuery library use this instruction:
$("#imageID").attr('src', 'srcImage.jpg');
In your specific case you can use the following bash
command (bash
is the default shell on macOS):
for f in *.png; do echo mv "$f" "${f/_*_/_}"; done
Note: If there's a chance that your filenames start with -
, place --
before them[1]:
mv -- "$f" "${f/_*_/_}"
Note: echo
is prepended to mv
so as to perform a dry run. Remove it to perform actual renaming.
You can run it from the command line or use it in a script.
"${f/_*_/_}"
is an application of bash
parameter expansion: the (first) substring matching pattern _*_
is replaced with literal _
, effectively cutting the middle token from the name._*_
is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash
and search for Pattern Matching
).If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename
utility.
On macOS you can install it using popular package manager Homebrew as follows:
brew install rename
Here's the equivalent of the command at the top using rename
:
rename -n -e 's/_.*_/_/' *.png
Again, this command performs a dry run; remove -n
to perform actual renaming.
bash
solution, s/.../.../
performs text substitution, but - unlike in bash
- true regular expressions are used.[1] The purpose of special argument --
, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -
, as Jacob C. notes.
If you have access to a database, you can create and use a sequence in the file name.
select mySequence.nextval from dual;
It will be guaranteed to be unique and shouldn't get too large (unless you are pumping out a ton of files).
You can be guided by this example. On your css file:
.deskContent {
background-image: url(../img/big-pic.png);
width: 100%;
height: 400px;
background-repeat: no-repeat;
background-size: contain;
}
.phoneContent {
background-image: url(../img/small-pic.png);
width: 100%;
height: 100px;
background-repeat: no-repeat;
background-size: contain;
}
@media all and (max-width: 959px) {
.deskContent {display:block;}
.phoneContent {display:none;}
}
@media all and (max-width: 479px) {
.deskContent {display:none;}
.phoneContent {display:block;}
}
On your html file:
<div class="deskContent">Content for desktop</div>
<div class="phoneContent">Content for mobile</div>
Once you set your Global Jenkins credentials, you can apply this step:
stage('Update GIT') {
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
withCredentials([usernamePassword(credentialsId: 'example-secure', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
def encodedPassword = URLEncoder.encode("$GIT_PASSWORD",'UTF-8')
sh "git config user.email [email protected]"
sh "git config user.name example"
sh "git add ."
sh "git commit -m 'Triggered Build: ${env.BUILD_NUMBER}'"
sh "git push https://${GIT_USERNAME}:${encodedPassword}@github.com/${GIT_USERNAME}/example.git"
}
}
}
}
}
Can be fixed after the fact by zip -d filename.zip __MACOSX/\*
Just adding an example that worked fine for me:
$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg
without using regex, using isdigit() built-in function, only works if starting part is text and latter part is number
def text_num_split(item):
for index, letter in enumerate(item, 0):
if letter.isdigit():
return [item[:index],item[index:]]
print(text_num_split("foobar12345"))
OUTPUT :
['foobar', '12345']
It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.
Main file with environment variables definition:
$ ls -la /etc/environment
-r-xr-xr-x 1 root wheel 369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh
set -e
syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"
launchctl setenv JAVA_HOME /usr/local/jdk1.7
launchctl setenv MAVEN_HOME /opt/local/share/java/maven3
if [ -x /usr/libexec/path_helper ]; then
export PATH=""
eval `/usr/libexec/path_helper -s`
launchctl setenv PATH $PATH
fi
osascript -e 'tell app "Dock" to quit'
syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"
Service definition to load environment variables for user applications (terminal, IDE, ...):
$ ls -la /Library/LaunchAgents/environment.user.plist
-rw------- 1 root wheel 504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>environment.user</string>
<key>ProgramArguments</key>
<array>
<string>/etc/environment</string>
</array>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>WatchPaths</key>
<array>
<string>/etc/environment</string>
</array>
</dict>
</plist>
The same service definition for root user applications:
$ ls -la /Library/LaunchDaemons/environment.plist
-rw------- 1 root wheel 499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>environment</string>
<key>ProgramArguments</key>
<array>
<string>/etc/environment</string>
</array>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>WatchPaths</key>
<array>
<string>/etc/environment</string>
</array>
</dict>
</plist>
And finally we should register these services:
$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist
What we get:
Issues / problems:
In order your env variables were correctly taken by applications after system reboot you will need:
This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".
But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.
REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple
< a href="" style="text-decoration: none" > < /a>
... thats the way html pages used to be
Throw needs an object instantiated by \Exception
. Just the $e
catched can play the trick.
throw $e
jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
Use like so:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
Yes, in AndroidManifest.xml
, declare your Activity
like so: <activity ... android:screenOrientation="landscape" .../>
I believe you can accomplish it by just having single ng-view
. In the main template you can have ng-include
sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include
sections. This is same as having multiple ng-view
You can check the example given in ng-include
documentation
in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view
and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.
the class attribute contains disabled
when the element is not clickable.
WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
webElement.click();
}
string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
I created my own functions which work really nicely:
def writeDict(dict, filename, sep):
with open(filename, "a") as f:
for i in dict.keys():
f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")
It will store the keyname first, followed by all values. Note that in this case my dict contains integers so that's why it converts to int
. This is most likely the part you need to change for your situation.
def readDict(filename, sep):
with open(filename, "r") as f:
dict = {}
for line in f:
values = line.split(sep)
dict[values[0]] = {int(x) for x in values[1:len(values)]}
return(dict)
this was my solution:
i was looking for how to display the result not to calculate...
so. in this case. there is no column TOTAL in the database, but there is a total on the webpage...
<td><?php echo $row['amount1'] * $row['amount2'] ?></td>
also this was needed first...
<?php
$conn=mysql_connect('localhost','testbla','adminbla');
mysql_select_db("testa",$conn);
$query1 = "select * from info2";
$get=mysql_query($query1);
while($row=mysql_fetch_array($get)){
?>
taking @rijul's answer forward, it doesn't work in marshmallow and above versions:
//for pre-marshmallow versions
String path = System.getenv("SECONDARY_STORAGE");
// For Marshmallow, use getExternalCacheDirs() instead of System.getenv("SECONDARY_STORAGE")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
File[] externalCacheDirs = mContext.getExternalCacheDirs();
for (File file : externalCacheDirs) {
if (Environment.isExternalStorageRemovable(file)) {
// Path is in format /storage.../Android....
// Get everything before /Android
path = file.getPath().split("/Android")[0];
break;
}
}
}
// Android avd emulator doesn't support this variable name so using other one
if ((null == path) || (path.length() == 0))
path = Environment.getExternalStorageDirectory().getAbsolutePath();
double quotes worked in oracle when I had the keyword as one of the column name.
eg:
select t."size" from table t
On the Button:
CommandArgument='<%# Eval("myKey")%>'
On the Server Event
e.CommandArgument
Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-
vscode:extension/vscjava.vscode-java-pack
and then clicking on the green Install button after it opens in VS Code.mvn archetype:generate -DgroupId=
com.companyname.appname-DartifactId=
appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname
and src/main/test/com/companyname/appname
to begin with and a sample "Hello World!" Java file named appname.java
and associated unit test named appnameTest.java
).*Tasks: Configure task
then select Create tasks.json from template
.Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:
{
"label": "compile",
"type": "shell",
"command": "mvn -B compile",
"group": "build"
},
Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target
folder at the same level as the src
folder with the compiled class files in the target\classes
folder.
Addendum: How to run/debug a class
Following a question in the comments, here are some steps for running/debugging:-
I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).
con = file("pathtotargetfile", "r")
readsizeof<-2 # read size for one step to caculate number of lines in file
nooflines<-0 # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file
nooflines<-nooflines+linesread
con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
print(is.vector(tmp))
print(tmp)
}
close(con)
Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.
Done.
The project no longer needs the stdafx. It is added automatically when you create projects with installed templates.
I found out that my back-up project worked well if I precompile without bundle update
. Maybe something went wrong with gem updated but I don't know which gem has an error.
If you want to do with ImageButton, use the following. It will create round ImageButton with material ripples.
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_settings_6"
android:background="?selectableItemBackgroundBorderless"
android:padding="10dp"
/>
ast.literal_eval()
only considers a small subset of Python's syntax to be valid:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and
None
.
Passing __import__('os').system('rm -rf /a-path-you-really-care-about')
into ast.literal_eval()
will raise an error, but eval()
will happily delete your files.
Since it looks like you're only letting the user input a plain dictionary, use ast.literal_eval()
. It safely does what you want and nothing more.
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:
$('#exampleBtn').click(function() {
function();
});
It exits the function and returns nothing.
Something like return 1;
would be incorrect since it returns integer 1.
GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".
Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:
CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;
because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:
CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;
I usually use :r! cat
and then paste ( shift + insert )
the content, and CTRL+D
.
No need to enable & disable, direct usage.
I know I am late but hope this helps.
Following are the values for the position property.
position : static
This is default. It means the element will occur at a position that it normally would.
#myelem {
position : static;
}
position : fixed
This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls.
(Ideal if you want scroll-to-top button at the bottom right corner of the page).
#myelem {
position : fixed;
bottom : 30px;
right : 30px;
}
position : relative
To place an element at a new location relative to its original position.
#myelem {
position : relative;
left : 30px;
top : 30px;
}
The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location.
position : absolute
If we want an element to be placed at an exact position in the page.
#myelem {
position : absolute;
top : 30px;
left : 300px;
}
The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page.
And finally...
position relative + absolute
We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position.
#container {
position : relative;
}
#div-2 {
position : absolute;
top : 0;
right : 0;
}
We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element.
GitHub: You can find the HTML of the above image here and CSS here.
Hope this tutorial helps.
Edit 2: Release 1.15.2 of the body parser module introduces raw mode, which returns the body as a Buffer. By default, it also automatically handles deflate and gzip decompression. Example usage:
var bodyParser = require('body-parser');
app.use(bodyParser.raw(options));
app.get(path, function(req, res) {
// req.body is a Buffer object
});
By default, the options
object has the following default options:
var options = {
inflate: true,
limit: '100kb',
type: 'application/octet-stream'
};
If you want your raw parser to parse other MIME types other than application/octet-stream
, you will need to change it here. It will also support wildcard matching such as */*
or */application
.
Note: The following answer is for versions before Express 4, where middleware was still bundled with the framework. The modern equivalent is the body-parser module, which must be installed separately.
The rawBody
property in Express was once available, but removed since version 1.5.1. To get the raw request body, you have to put in some middleware before using the bodyParser. You can also read a GitHub discussion about it here.
app.use(function(req, res, next) {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
next();
});
});
app.use(express.bodyParser());
That middleware will read from the actual data stream, and store it in the rawBody
property of the request. You can then access the raw body like this:
app.post('/', function(req, res) {
// do something with req.rawBody
// use req.body for the parsed body
});
Edit: It seems that this method and bodyParser refuse to coexist, because one will consume the request stream before the other, leading to whichever one is second to never fire end
, thus never calling next()
, and hanging your application.
The simplest solution would most likely be to modify the source of bodyParser, which you would find on line 57 of Connect's JSON parser. This is what the modified version would look like.
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk){ buf += chunk });
req.on('end', function() {
req.rawBody = buf;
var first = buf.trim()[0];
...
});
You would find the file at this location:
/node_modules/express/node_modules/connect/lib/middleware/json.js
.
I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href
attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href
attributes blank.
<a href="" data-router="article" ng-click="changeListName('metro')">
Also I don't know what data-router
is doing but if you still aren't getting the proper result, that could be why.
I found this solution helpful. Just subtract if it isn't monday to get the previous Monday. I am using $lower_date as the date I pulled from a query that I then need to reconcile to the previous Monday.
//set this up to go backwards until you find monday
while(date('D',strtotime($lower_date))!='Mon'){
$lower_date = date('Y-m-d', strtotime($lower_date . ' - 1 day')); //increase the upper spec
}
For the controls embedded in WPF Extended WPF Toolkit Release 1.4.0, please refer http://elegantcode.com/2011/04/08/extended-wpf-toolkit-release-1-4-0/
For Calendar & DatePicker Walkthrough please refer, http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx
And you can cutomize the look and feel by Microsoft Expression Studio [Use Edit Template option]
Sample shows here:
Add following namespaces to xaml page
xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit.Extended"
xmlns:Microsoft_Windows_Controls_Core_Converters="clr-namespace:Microsoft.Windows.Controls.Core.Converters;assembly=WPFToolkit.Extended"
xmlns:Microsoft_Windows_Controls_Chromes="clr-namespace:Microsoft.Windows.Controls.Chromes;assembly=WPFToolkit.Extended"
Add followings to Page/Window resources
<!--DateTimePicker Customized Style-->
<Style x:Key="DateTimePickerStyle1" TargetType="{x:Type toolkit:DateTimePicker}">
<Setter Property="TimeWatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="WatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type toolkit:DateTimePicker}">
<Border>
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<toolkit:DateTimeUpDown AllowSpin="{TemplateBinding AllowSpin}"
BorderThickness="1,1,0,1"
FormatString="{TemplateBinding FormatString}"
Format="{TemplateBinding Format}"
ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}"
Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"
WatermarkTemplate="{TemplateBinding WatermarkTemplate}"
Watermark="{TemplateBinding Watermark}"
Foreground="#FFEFE3E3"
BorderBrush="#FFEBB31A">
<toolkit:DateTimeUpDown.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF2F2828" Offset="1"/>
</LinearGradientBrush>
</toolkit:DateTimeUpDown.Background>
</toolkit:DateTimeUpDown>
<ToggleButton x:Name="_calendarToggleButton"
Background="{x:Null}" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.IsHitTestVisible>
<Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
<Binding.Converter>
<Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
</Binding.Converter>
</Binding>
</ToggleButton.IsHitTestVisible>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid SnapsToDevicePixels="True">
<Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" BorderBrush="{x:Null}">
<Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FFF3F3F3" Offset="1"/>
<GradientStop Color="#7FC0A112"/>
</LinearGradientBrush>
</Microsoft_Windows_Controls_Chromes:ButtonChrome.Background>
</Microsoft_Windows_Controls_Chromes:ButtonChrome>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
<Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
<Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="#FF82E511" Height="4" Width="7"/>
</Grid>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
</Grid>
<Popup IsOpen="{Binding IsChecked, ElementName=_calendarToggleButton}" StaysOpen="False">
<Border BorderThickness="1" Padding="3">
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FFD2C217" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Border.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FFE9B116" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<StackPanel Background="{x:Null}">
<Calendar x:Name="Part_Calendar" BorderThickness="0" DisplayDate="2011-06-28" Background="#7FE0B41A"/>
<toolkit:TimePicker x:Name="Part_TimeUpDown" Format="ShortTime" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding TimeWatermarkTemplate}" Watermark="{TemplateBinding TimeWatermark}" Background="{x:Null}" Style="{DynamicResource TimePickerStyle1}"/>
</StackPanel>
</Border>
</Popup>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="TimePickerStyle1"
TargetType="{x:Type toolkit:TimePicker}">
<Setter Property="WatermarkTemplate">
<Setter.Value>
<DataTemplate>
<ContentControl Content="{Binding}" Foreground="Gray" Focusable="False"/>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type toolkit:TimePicker}">
<Border>
<Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid>
<toolkit:DateTimeUpDown x:Name="PART_TimeUpDown" AllowSpin="{TemplateBinding AllowSpin}" BorderThickness="1,1,0,1" FormatString="{TemplateBinding FormatString}" ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}" Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}" WatermarkTemplate="{TemplateBinding WatermarkTemplate}" Watermark="{TemplateBinding Watermark}" Background="#7FE0B41A" BorderBrush="#FFF9F2F2">
<toolkit:DateTimeUpDown.Format>
<TemplateBinding Property="Format">
<TemplateBinding.Converter>
<Microsoft_Windows_Controls_Core_Converters:TimeFormatToDateTimeFormatConverter/>
</TemplateBinding.Converter>
</TemplateBinding>
</toolkit:DateTimeUpDown.Format>
</toolkit:DateTimeUpDown>
</Grid>
<ToggleButton x:Name="_timePickerToggleButton" Grid.Column="1" IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}" >
<ToggleButton.IsHitTestVisible>
<Binding Path="IsOpen" RelativeSource="{RelativeSource TemplatedParent}">
<Binding.Converter>
<Microsoft_Windows_Controls_Core_Converters:InverseBoolConverter/>
</Binding.Converter>
</Binding>
</ToggleButton.IsHitTestVisible>
<ToggleButton.Style>
<Style TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid SnapsToDevicePixels="True">
<Microsoft_Windows_Controls_Chromes:ButtonChrome x:Name="ToggleButtonChrome" CornerRadius="0,2.75,2.75,0" InnerCornerRadius="0,1.75,1.75,0" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Stretch" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Stretch"/>
<Grid x:Name="arrowGlyph" Grid.Column="1" IsHitTestVisible="False" Margin="5">
<Path Data="M0,1C0,1 0,0 0,0 0,0 3,0 3,0 3,0 3,1 3,1 3,1 4,1 4,1 4,1 4,0 4,0 4,0 7,0 7,0 7,0 7,1 7,1 7,1 6,1 6,1 6,1 6,2 6,2 6,2 5,2 5,2 5,2 5,3 5,3 5,3 4,3 4,3 4,3 4,4 4,4 4,4 3,4 3,4 3,4 3,3 3,3 3,3 2,3 2,3 2,3 2,2 2,2 2,2 1,2 1,2 1,2 1,1 1,1 1,1 0,1 0,1z" Fill="Black" Height="4" Width="7"/>
</Grid>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
</Grid>
<Popup IsOpen="{Binding IsChecked, ElementName=_timePickerToggleButton}" StaysOpen="False">
<Border BorderThickness="1">
<Border.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FFE7C857" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Border.BorderBrush>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFA3AEB9" Offset="0"/>
<GradientStop Color="#FF8399A9" Offset="0.375"/>
<GradientStop Color="#FF718597" Offset="0.375"/>
<GradientStop Color="#FF617584" Offset="1"/>
</LinearGradientBrush>
</Border.BorderBrush>
<Grid>
<ListBox x:Name="PART_TimeListItems" BorderThickness="0" DisplayMemberPath="Display" Height="130" Width="150" Background="#7FE0B41A">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Border" SnapsToDevicePixels="True">
<ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Margin="4"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="Border" Value="#FFE7F5FD"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" TargetName="Border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</Border>
</Popup>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And in Window you can use the style as
Thanks,
One of the problems you might need to check is, Does the registry requires VPN, Enable your VPN and try pulling again.
Thanks.
I find that the OS Utils from Swingx does the job.
Yet another possibility if you're getting the error on a checkbox input. If your checkboxes use custom CSS which hides the default and replaces it with some other styling, this will also trigger the not focusable error in Chrome on validation error.
I found this in my stylesheet:
input[type="checkbox"] {
visibility: hidden;
}
Simple fix was to replace it with this:
input[type="checkbox"] {
opacity: 0;
}
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
I always use something like the following:
public static String GetTimestamp(this DateTime value)
{
return value.ToString("yyyyMMddHHmmssfff");
}
This will give you a string like 200905211035131468, as the string goes from highest order bits of the timestamp to lowest order simple string sorting in your SQL queries can be used to order by date if you're sticking values in a database
Add /Y to the command line
[A-Za-z0-9_.-]*
This will also match for empty strings, if you do not want that exchange the last *
for an +
I hit this error because I was specifying a label attribute in my geom (geom_text
) but was specifying a color in the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
geom_text(angle=45, label=df$V1, size=2)
To fix this, I just moved the label attribute out of the geom and into the top level aes:
df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)
# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
geom_text(angle=45, size=2)
prime=2
counter = 0
x = int(input("Enter the number:\n"))
while (counter < x):
if all(prime%j!=0 for j in range(2, prime)):
print(prime, "is a prime number")
counter+=1
prime+=1
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
In case you are considering using the numpy
module, it makes this task very simple, as requested:
import numpy as np
j = np.array([4, 5, 6, 7, 1, 3, 7, 5])
j2 = np.sort(j[j >= 5])
The code inside of the brackets, j >= 5
, produces a list of True
or False
values, which then serve as indices to select the desired values in j
. Finally, we sort with the sort
function built into numpy
.
Tested result (a numpy
array):
array([5, 5, 6, 7, 7])
I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.
This Facebook page has a simple tool to create various share buttons.
For example, this is some output I got:
<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>
For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME;
with protected $redirectTo = '/newurl';
and replace newurl
accordingly.
Tested with Laravel version-6
struct arg_struct *args = (struct arg_struct *)args;
--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!
the following two ways work well:
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs --file example2.json
C:\>mongodb\bin\mongoimport --jsonArray -d test -c docs < example2.json
if the collections are under a specific user, you can use -u -p --authenticationDatabase
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
Set style= "display:none;"
. By setting visible=false
, it will not render button in the browser. Thus,client side script wont execute.
<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />
html markup should be
<button id="btnsave" onclick="fncsave()">Save</button>
Change javascript to
<script type="text/javascript">
function fncsave()
{
document.getElementById('<%= savebtn.ClientID %>').click();
}
</script>
Why not use flash & javascript upload control?
I had some problems with the accepted solution and the Select2.js plugin; I was not able to delete characters in the editable box as the delete action was being prevented. This was my solution:
//Prevent backwards navigation when trying to delete disabled text.
$(document).unbind('keydown').bind('keydown', function (event) {
if (event.keyCode === 8) {
var doPrevent = false,
d = event.srcElement || event.target,
tagName = d.tagName.toUpperCase(),
type = (d.type ? d.type.toUpperCase() : ""),
isEditable = d.contentEditable,
isReadOnly = d.readOnly,
isDisabled = d.disabled;
if (( tagName === 'INPUT' && (type === 'TEXT' || type === 'PASSWORD'))
|| tagName === 'PASSWORD'
|| tagName === 'TEXTAREA') {
doPrevent = isReadOnly || isDisabled;
}
else if(tagName === 'SPAN'){
doPrevent = !isEditable;
}
else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
});
Select2 creates a Span with an attribute of "contentEditable" which is set to true for the editable combo box in it. I added code to account for the spans tagName and the different attribute. This solved all my problems.
Edit: If you are not using the Select2 combobox plugin for jquery, then this solution may not be needed by you, and the accepted solution might be better.
Normally svn add *
works. But if you get message like svn: warning: W150002:
due to mix off versioned and non-versioned files in working copy. Use this command:
svn add <path to directory> --force
or
svn add * --force
.NET Core 2.1.0
var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var config = builder.Build();
3. Install the following dependencies:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.json
4. Then, IMPORTANT: Right-click on the appsettings.json file -> click on Properties -> select Copy if newer:
Finally, you can do:
config["key1"]
Considering that my config file will look like this:
{ "ConnectionStrings": "myconnection string here", "key1": "value here" }
If you set it programmatically you can just call it like a variable (i.e. document.getElementById('image_1').style.top
). Otherwise, you can always use jQuery:
<html>
<body>
<div id="test" style="height: 100px;">Test</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
alert($("#test").css("height"));
</script>
</body>
</html>
I'm very late to the party but I'll put this up here if anyone else would like to know my solution:
I had a real struggle with this exact problem but I found a viable solution using iframes (I know, I know. It's terrible but it works for a simple problem that I had)
I had an html page that launched a separate php script that generated the file and then downloaded it. On the html page, i used the following jquery in the html header (you'll need to include a jquery library as well):
<script>
$(function(){
var iframe = $("<iframe>", {name: 'iframe', id: 'iframe',}).appendTo("body").hide();
$('#click').on('click', function(){
$('#iframe').attr('src', 'your_download_script.php');
});
$('iframe').load(function(){
$('#iframe').attr('src', 'your_download_script.php?download=yes'); <!--on first iframe load, run script again but download file instead-->
$('#iframe').unbind(); <!--unbinds the iframe. Helps prevent against infinite recursion if the script returns valid html (such as echoing out exceptions) -->
});
});
</script>
On your_download_script.php, have the following:
function downloadFile($file_path) {
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=' . basename($file_path));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
ob_clean();
flush();
readfile($file_path);
exit();
}
}
$_SESSION['your_file'] = path_to_file; //this is just how I chose to store the filepath
if (isset($_REQUEST['download']) && $_REQUEST['download'] == 'yes') {
downloadFile($_SESSION['your_file']);
} else {
*execute logic to create the file*
}
To break this down, jquery first launches your php script in an iframe. The iframe is loaded once the file is generated. Then jquery launches the script again with a request variable telling the script to download the file.
The reason that you can't do the download and file generation all in one go is due to the php header() function. If you use header(), you're changing the script to something other than a web page and jquery will never recognize the download script as being 'loaded'. I know this may not necessarily be detecting when a browser receives a file but your issue sounded similar to mine.
And with the new string formatting method...
f = open('{0}.csv'.format(name), 'wb')
@Test (expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = "This is not allowed")
public void testInvalidValidation() throws Exception{
//test code
}
A little different to the other answers, using a similar concept but divs instead of pseudoclasses:
input {_x000D_
position: absolute;_x000D_
left: 10px;_x000D_
top: 10px;_x000D_
width: 50px;_x000D_
height: 20px;_x000D_
padding: 0px;_x000D_
font-size: 14pt;_x000D_
border: solid 0.5px #000;_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
.spinner-button {_x000D_
position: absolute;_x000D_
cursor: default;_x000D_
z-index: 2;_x000D_
background-color: #ccc;_x000D_
width: 14.5px;_x000D_
text-align: center;_x000D_
margin: 0px;_x000D_
pointer-events: none;_x000D_
height: 10px;_x000D_
line-height: 10px;_x000D_
}_x000D_
_x000D_
#inc-button {_x000D_
left: 46px;_x000D_
top: 10.5px;_x000D_
}_x000D_
_x000D_
#dec-button {_x000D_
left: 46px;_x000D_
top: 20.5px;_x000D_
}
_x000D_
<input type="number" value="0" min="0" max="100"/>_x000D_
<div id="inc-button" class="spinner-button">+</div>_x000D_
<div id="dec-button" class="spinner-button">-</div>
_x000D_
I would try triming the number to see what you get:
select len(rtrim(ltrim(userid))) from audit
if that return the correct value then just do:
select convert(int, rtrim(ltrim(userid))) from audit
if that doesn't return the correct value then I would do a replace to remove the empty space:
select convert(int, replace(userid, char(0), '')) from audit
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
I just add three rules before spring default rule (/**) to tuckey's urlrewritefilter (urlrewrite.xml) to solve the problem
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.0//EN" "http://tuckey.org/res/dtds/urlrewrite3.0.dtd">
<urlrewrite default-match-type="wildcard">
<rule>
<from>/</from>
<to>/app/welcome</to>
</rule>
<rule>
<from>/scripts/**</from>
<to>/scripts/$1</to>
</rule>
<rule>
<from>/styles/**</from>
<to>/styles/$1</to>
</rule>
<rule>
<from>/images/**</from>
<to>/images/$1</to>
</rule>
<rule>
<from>/**</from>
<to>/app/$1</to>
</rule>
<outbound-rule>
<from>/app/**</from>
<to>/$1</to>
</outbound-rule>
</urlrewrite>
Edit /var/lib/logrotate.status (or /var/lib/loglogrotate/logrotate.status) to reset the 'last rotated' date on the log file you want to test.
Then run logrotate YOUR_CONFIG_FILE
.
Or you can use the --force flag, but editing logrotate.status gives you more precision over what does and doesn't get rotated.
This site allows you to view a packages tree as a node graph in 2D or 3D.
http://npm.anvaka.com/#/view/2d/waterline
Great work from @Avanka!
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/* PUT THIS LINE IN YOUR CLASS PROGRAM MAIN() */
AppDomain.CurrentDomain.AssemblyResolve += (sender, arg) => { if (arg.Name.StartsWith("YOURDLL")) return Assembly.Load(Properties.Resources.YOURDLL); return null; };
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
First add the DLL´s to your project-Resources. Add a folder "Resources"
Why not encapsulate a set with a list, sort like:
new ArrayList( new LinkedHashSet() )
This leaves the other implementation for someone who is a real master of Collections ;-)
You can set Apache to serve pages from anywhere with any restrictions but it's normally distributed in a more secure form.
Editing your apache files (http.conf is one of the more common names) will allow you to set any folder so it appears in your webroot.
EDIT:
alias myapp c:\myapp\
I've edited my answer to include the format for creating an alias in the http.conf file which is sort of like a shortcut in windows or a symlink under un*x where Apache 'pretends' a folder is in the webroot. This is probably going to be more useful to you in the long term.
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
Don't use MD5
as it is insecure. I would recommend using SHA
or bcrypt
with a salt
:
SHA256('".$password."')
You may refer to: How to deal with "refusing to merge unrelated histories" error:
$ git pull --allow-unrelated-histories
$ git push -f origin master
Get the file from a previous commit through checking-out previous commit and copying file.
git checkout 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8
git checkout theBranchYouNoted
git commit -m "added file ?? from previous commit"
You can use:
NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:@"*"] ) {
newString = [myString substringFromIndex:1];
}
From @sidharth: "caused my lava iris alfa to go into a bootloop :("
For my Motorola Nexus 6 running Android Marshmallow 6.0.1 I did:
adb devices # Check the phone is running
adb reboot bootloader
# Wait a few seconds
fastboot devices # Check the phone is in bootloader
fastboot -w # Wipe user data
I assume that you use distinct like a method call on a list. You need to use the result of the query as datasource for your DropDownList, for example by materializing it via ToList
.
var distinctCategories = product
.Select(m => new {m.CategoryId, m.CategoryName})
.Distinct()
.ToList();
DropDownList1.DataSource = distinctCategories;
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataValueField = "CategoryId";
Another way if you need the real objects instead of the anonymous type with only few properties is to use GroupBy
with an anonymous type:
List<Product> distinctProductList = product
.GroupBy(m => new {m.CategoryId, m.CategoryName})
.Select(group => group.First()) // instead of First you can also apply your logic here what you want to take, for example an OrderBy
.ToList();
A third option is to use MoreLinq's DistinctBy
.
Here are the outputs of isset()
and empty()
for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset
and false when tested by 'empty'.
So use isset()
when you're concerned about the existence of a variable. And use empty
when you're testing for true or false. If the actual type of emptiness matters, use is_null
and ===0
, ===false
, ===''
.
Steps To fix the Problem:-
I have fixed the problem with following steps:-
nvm install lts/dubnium
nvm install lts/dubnium
Now you can you gulp deploy
I used 'live' in my project but one of my friend suggested that i should use 'on' instead of live. And when i tried to use that i experienced a problem like you had.
On my pages i create buttons table rows and many dom stuff dynamically. but when i use on the magic disappeared.
The other solutions like use it like a child just calls your functions every time on every click. But i find a way to make it happen again and here is the solution.
Write your code as:
function caller(){
$('.ObjectYouWntToCall').on("click", function() {...magic...});
}
Call caller(); after you create your object in the page like this.
$('<dom class="ObjectYouWntToCall">bla... bla...<dom>').appendTo("#whereeveryouwant");
caller();
By this way your function is called when it is supposed to not every click on the page.
You could write a function that will convert and format this array as string. Even better: use FireBug for debugging instead of alerts.
There is no simple way to do this in a correct AND generic way.
First of all it must be understood that the offset depends on the date in question, the Time Zone AND DST.
GetDate()-GetUTCDate
only gives you the offset today at the server's TZ, which is not relevant.
I have seen only two working solution and I have search a lot.
1) A custom SQL function with a a couple of tables of base data such as Time Zones and DST rules per TZ. Working but not very elegant. I can't post it since I don't own the code.
EDIT: Here is an example of this method https://gist.github.com/drumsta/16b79cee6bc195cd89c8
2) Add a .net assembly to the db, .Net can do this very easily. This is working very well but the downside is that you need to configure several parameters on server level and the config is easily broken e.g. if you restore the database. I use this method but I cant post it since I don't own the code.
The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment
to send a command to the linker at link time for example
#pragma comment(linker,"/ENTRY:Entry")
tell the linker to change the entry point form WinMain()
to Entry()
after that the CRTStartup
going to transfer controll to Entry()
int pos = 0;
yourSeekBar.setMax(mPlayer.getDuration());
After You start Your MediaPlayer
i.e mplayer.start()
while(mPlayer!=null){
try {
Thread.sleep(1000);
pos = mPlayer.getCurrentPosition();
} catch (Exception e) {
//show exception in LogCat
}
yourSeekBar.setProgress(pos);
}
Before you added this code you have to create xml
resource for SeekBar
and use it in Your Activity
class of ur onCreate()
method.
You want to do this - set a function that will be executed to respond to the onclick event:
document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;
The things you are doing don't work because:
The onclick event handler expects to have a function, here you are assigning a string
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
You control how a row or column aligns its children using the mainAxisAlignment and crossAxisAlignment properties. For a row, the main axis runs horizontally and the cross axis runs vertically. For a column, the main axis runs vertically and the cross axis runs horizontally.
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
Google play store provides closed testing track
to test your application with a limited set of testers pre-defined in the tester's list known as Alpha Testing
. Here are some important things to be considered to use alpha testing.
Important
After publishing an alpha/beta app for the first time, it may take a few hours for your test link to be available to testers. If you publish additional changes, they may take several hours to be available for testers
CSV
file to bulk add and remove. The list of defined email addresses will be eligible for testing the app, here you can a control whom to provide the app for testing. Hence, this is known as Closed Testing
.YOUR PACKAGE NAME
stagged roll-out
. In stagged roll-out, the publisher publishes by the percentage of users, to better analyze the user response.Alpha Country Availability
. It gives more precise control over testers.in case you are working on a linux machine, also recheck the file and folder permissions of the database.
The db and the path to it can be obtained via:
in redis-cli
:
CONFIG GET dir
CONFIG GET dbfilename
and in the commandline ls -l
. The permissions for the directory should be 755, and those for the file should be 644. Also, normally redis-server executes as the user redis
, therefore its also nice to give the user redis
the ownership of the folder by executing sudo chown -R redis:redis /path/to/rdb/folder
. This has been elaborated in the answer here.
You can use Take extension method
var array = new byte[] {1, 2, 3, 4};
var firstTwoItems = array.Take(2);
The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.
If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.
You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.
See Unable to send emails to external domain using SMTP for an example of how to send the credentials.
For Image:
custom.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tab_icon_normal"), selectedImage: UIImage(named: "tab_icon_selected"))
For Text:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
Guys use this code in Your main activity. Very Efficient Method
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.users_list);
UsersAdapter adapter = new UsersAdapter(users, this);
recyclerView.setAdapter(adapter);
adapter.setOnCardClickListner(this);
Here is your Adapter class.
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
private ArrayList<User> mDataSet;
OnCardClickListner onCardClickListner;
public UsersAdapter(ArrayList<User> mDataSet) {
this.mDataSet = mDataSet;
}
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout, parent, false);
UserViewHolder userViewHolder = new UserViewHolder(v);
return userViewHolder;
}
@Override
public void onBindViewHolder(UserViewHolder holder, final int position) {
holder.name_entry.setText(mDataSet.get(position).getUser_name());
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onCardClickListner.OnCardClicked(v, position);
}
});
}
@Override
public int getItemCount() {
return mDataSet.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class UserViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView name_entry;
public UserViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.user_layout);
name_entry = (TextView) itemView.findViewById(R.id.name_entry);
}
}
public interface OnCardClickListner {
void OnCardClicked(View view, int position);
}
public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
this.onCardClickListner = onCardClickListner;
}
}
After this you will get this override method in your activity.
@Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
}
Enter this in the custom number format field:
[>=1000]#,##0,"K€";0"€"
What that means is that if the number is greater than 1,000, display at least one digit (indicated by the zero), but no digits after the thousands place, indicated by nothing coming after the comma. Then you follow the whole thing with the string "K".
Edited to add comma and euro.
from re import search
from functools import wraps
def is_match(_lambda, pattern):
def wrapper(f):
@wraps(f)
def wrapped(self, *f_args, **f_kwargs):
if callable(_lambda) and search(pattern, (_lambda(self) or '')):
f(self, *f_args, **f_kwargs)
return wrapped
return wrapper
class MyTest(object):
def __init__(self):
self.name = 'foo'
self.surname = 'bar'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'foo')
def my_rule(self):
print 'my_rule : ok'
@is_match(lambda x: x.name, 'foo')
@is_match(lambda x: x.surname, 'bar')
def my_rule2(self):
print 'my_rule2 : ok'
test = MyTest()
test.my_rule()
test.my_rule2()
ouput: my_rule2 : ok
the cause is that SQL SERVER is stopped from services.msc a solution for this problem could be starting SQL SERVER from services.msc
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy
do not stack, but you can make multiple calls to addOrderBy
:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
In my case I solved the issue by putting the name of the formControl in double and sinlge quotes so that it is interpreted as a string:
[formControlName]="'familyName'"
similar to below:
formControlName="familyName"
So this happened! I accidently clicked on "assume unchanged"! I tried searching on Internet, but could not find any working solution! So, I tried few things here and there and finally I found the solution (easiest one) for this which will undo the assume unchanged!
Right click on "Your Project" then Team > Advanced > No assume Unchanged
.
In PowerShell you can do:
$imageObj = New-Object System.IO.FileInfo("C:\test.jpg")
$imageObj.Length
If you want to keep production changes on the server, just merge into a new configuration item. The processing method is as follows:
git stash
git pull
git stash pop
Maybe you don't execute all operations. You can know what you can do next.
Some might say that I'm a little off-topic, but here it is anyway:
You don't necessarily have to choose because of your string's content between:
echo "It's \"game\" time.";
or echo 'It\'s "game" time.';
If you're familiar with the use of the english quotation marks, and the correct character for the apostrophe, you can use either double or single quotes, because it won't matter anymore:
echo "It’s “game” time.";
and echo 'It’s “game” time.';
Of course you can also add variables if needed. Just don't forget that they get evaluated only when in double quotes!
You actually don't need jQuery, just CSS. For example, here's some HTML:
<div class="special"></div>
And here's the CSS:
.special
{
cursor: pointer;
}
This guy worked for me:
list_get = lambda l, x: l[x:x+1] and l[x] or 0
lambdas are great for one liner helper functions like this
For extending control functionality like this, I like to use extension methods so that it can be reused easily. Here is a starter extensions file that contains an extension to disable sorting on a datagridview.
To use it, just include it in your project and call like this
myDatagridView.DisableSorting()
In my case, I added this line of code in the DataBindingComplete eventhandler of the DataGridView where I wanted sorting disabled
Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms
Public Module Extensions
<Extension()>
Public Sub DisableSorting(datagrid As DataGridView)
For index = 0 To datagrid.Columns.Count - 1
datagrid.Columns(index).SortMode = DataGridViewColumnSortMode.NotSortable
Next
End Sub
End Module
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
One way to debug this (and to make sure it is the protocol violation that is causing the problem), is to use Fiddler (Http Web Proxy) and see if the same error occurs. If it doesn't (i.e. Fiddler handled the issue for you) then you should be able to fix it using the UseUnsafeHeaderParsing flag.
If you are looking for a way to set this value programatically see the examples here: http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/
if you've got this error by using the express generator, I've solved it by using
express --view=ejs myapp
instead of
express --view=pug myapp
Check via Google, there are lots of examples, see here for one.
Inlined for ease of viewing:
import win32com.client
def send_mail_via_com(text, subject, recipient, profilename="Outlook2003"):
s = win32com.client.Dispatch("Mapi.Session")
o = win32com.client.Dispatch("Outlook.Application")
s.Logon(profilename)
Msg = o.CreateItem(0)
Msg.To = recipient
Msg.CC = "moreaddresses here"
Msg.BCC = "address"
Msg.Subject = subject
Msg.Body = text
attachment1 = "Path to attachment no. 1"
attachment2 = "Path to attachment no. 2"
Msg.Attachments.Add(attachment1)
Msg.Attachments.Add(attachment2)
Msg.Send()
If you want to save memory and want to obtain each row as a json object, then you can use fast-csv
to create readstream and can read each row as a json object as follows:
const csv = require('fast-csv');
const AWS = require('aws-sdk');
const credentials = new AWS.Credentials("ACCESSKEY", "SECRETEKEY", "SESSIONTOKEN");
AWS.config.update({
credentials: credentials, // credentials required for local execution
region: 'your_region'
});
const dynamoS3Bucket = new AWS.S3();
const stream = dynamoS3Bucket.getObject({ Bucket: 'your_bucket', Key: 'example.csv' }).createReadStream();
var parser = csv.fromStream(stream, { headers: true }).on("data", function (data) {
parser.pause(); //can pause reading using this at a particular row
parser.resume(); // to continue reading
console.log(data);
}).on("end", function () {
console.log('process finished');
});
Type check also works :
if(typeof Obj.property == "undefined"){
// Assign value to the property here
Obj.property = someValue;
}
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c
As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.
CUBRID (open source RDBMS) explains the idea of this two algorithms:
- Two-phase locking (2PL)
The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).
- Multi-version concurrency control (MVCC)
The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.
When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).
The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).
In 2PL Transaction isolation levels control the following:
Whether locks are taken when data is read, and what type of locks are requested.
How long the read locks are held.
Whether a read operation referencing rows modified by another transaction:
Block until the exclusive lock on the row is freed.
Retrieve the committed version of the row that existed at the time the statement or transaction started.
Read the uncommitted data modification.
Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.
A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.
Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)
READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]
READ_COMMITED:
REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.
SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.
In my experience the pythonw.exe is faster at least with using pygame.
There is a good case of async/await loops and threading in an article by Pimin Konstantin Kefaloukos Easy parallel HTTP requests with Python and asyncio:
To minimize the total completion time, we could increase the size of the thread pool to match the number of requests we have to make. Luckily, this is easy to do as we will see next. The code listing below is an example of how to make twenty asynchronous HTTP requests with a thread pool of twenty worker threads:
# Example 3: asynchronous requests with larger thread pool
import asyncio
import concurrent.futures
import requests
async def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
requests.get,
'http://example.org/'
)
for i in range(20)
]
for response in await asyncio.gather(*futures):
pass
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
The best (and easiest) way to copy data from a workbook to another is to use the object model of Excel.
Option Explicit
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set targetworkbook
Set wb2 = ActiveWorkbook
'For instance, copy data from a range in the first workbook to another range in the other workbook
wb2.Worksheets("Sheet2").Range("C3:D4").Value = wb.Worksheets("Sheet1").Range("A1:B2").Value
End Sub
Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View
for inspecting the value of variables.
To list all of the screen sessions for a user, run the following command as that user:
screen -ls
To see all screen sessions on a specific machine you can do:
ls -laR /var/run/screen/
I get this on my machine:
gentle ~ # ls -laR /var/run/screen/
/var/run/screen/:
total 1
drwxrwxr-x 4 root utmp 96 Mar 1 2005 .
drwxr-xr-x 10 root root 840 Feb 1 03:10 ..
drwx------ 2 josh users 88 Jan 13 11:33 S-josh
drwx------ 2 root root 48 Feb 11 10:50 S-root
/var/run/screen/S-josh:
total 0
drwx------ 2 josh users 88 Jan 13 11:33 .
drwxrwxr-x 4 root utmp 96 Mar 1 2005 ..
prwx------ 1 josh users 0 Feb 11 10:41 12931.pts-0.gentle
/var/run/screen/S-root:
total 0
drwx------ 2 root root 48 Feb 11 10:50 .
drwxrwxr-x 4 root utmp 96 Mar 1 2005 ..
This is a rather brilliantly Unixy use of Unix Sockets wrapped in filesystem permissions to handle security, state, and streams.
Is it a good practice to use try-except-else in python?
The answer to this is that it is context dependent. If you do this:
d = dict()
try:
item = d['item']
except KeyError:
item = 'default'
It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get
method:
item = d.get('item', 'default')
The try
/except
block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.
However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.
Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.
catch (WhateverException e) {
throw e;
}
will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.
You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.
function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 100);
}
for (var i = 1; i <= 2; ++i)
doSetTimeout(i);
If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.
edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout()
— take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.
Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.
If what you need is for the handlers to be called at intervals, you can either use setInterval()
, which is called exactly like setTimeout()
but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:
function doScaledTimeout(i) {
setTimeout(function() {
alert(i);
}, i * 5000);
}
(With a 100
millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i
is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.
Update
Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:
for (let i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}
The let
declaration, unlike var
, will itself cause there to be a distinct i
for each iteration of the loop.
Try
<td style="text-align:center;">
<input type="checkbox" name="myTextEditBox" value="checked" />
</td>
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
The point it is just an alternative for success callback option, and jqXHR.success()
is deprecated.
A more elegant solution
echo "Enter the file name"
read x
if [ -f $x ]
then
echo "This is a regular file"
else
echo "This is a directory"
fi
I like list
instead of c
because it handles mixed data types better. Adding an additional column to the original poster's question:
#Create an empty data frame
df <- data.frame(hello=character(), goodbye=character(), volume=double())
de <- list(hello="hi", goodbye="bye", volume=3.0)
df = rbind(df,de, stringsAsFactors=FALSE)
de <- list(hello="hola", goodbye="ciao", volume=13.1)
df = rbind(df,de, stringsAsFactors=FALSE)
Note that some additional control is required if the string/factor conversion is important.
Or using the original variables with the solution from MatheusAraujo/Ytsen de Boer:
df[nrow(df) + 1,] = list(hello="hallo",goodbye="auf wiedersehen", volume=20.2)
Note that this solution doesn't work well with the strings unless there is existing data in the dataframe.
Your OS doesn't know about en_US.UTF-8
.
You didn't mention a specific platform, but I can reproduce your problem:
% uname -a OSF1 hunter2 V5.1 2650 alpha % perl -e exit perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LC_ALL = (unset), LANG = "en_US.UTF-8" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C").
My guess is you used ssh to connect to this older host from a newer desktop machine. It's common for /etc/ssh/sshd_config
to contain
AcceptEnv LANG LC_*
which allows clients to propagate the values of those environment variables into new sessions.
The warning gives you a hint about how to squelch it if you don't require the full-up locale:
% env LANG=C perl -e exit %
or with Bash:
$ LANG=C perl -e exit $
For a permanent fix, choose one of
LANG
environment variable in your shell's initialization file.ssh hunter2
, use the command LANG=C ssh hunter2
.SendEnv LANG LC_*
line in the local /etc/ssh/ssh_config
file. (Thanks to this answer. See Bug 1285 for OpenSSH for more.)#include #include
not original cv.h
I was able to login using ec2-user
ssh -i [full path to keypair file] ec2-user@[EC2 instance hostname or IP address]
In my case, the culprit was not distinguish the main and test sources folder within pom.xml (generated by eclipse maven project)
<build>
<sourceDirectory>src</sourceDirectory>
....
</build>
If you override default source folder settings in pom file, you must explicitly set the main AND test source folders!!!!
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
....
</build>
You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
find source/ -type f | rsync -a --exclude-from - source/ target/
Copy dir only with associated permission and ownership
Go to your desired perspective. Go to 'Window->show view' menu.
If you see logcat there, click it and you are done.
Else, click on 'other' (at the bottom), chose 'Android'->logcat.
Hope that helps :-)
What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.
ls -ltrh /proc | grep YOUR-PID-HERE
For example, my Google Chrome's PID is 11583:
ls -l /proc | grep 11583
dr-xr-xr-x 7 adam adam 0 2011-04-20 16:34 11583
you can use the @ControllerAdvice to handle your Exceptions , The default behavior the @ControllerAdvice annotated class will assist all known Controllers.
so it will be called when any Controller you have throws 404 error .
like the following :
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
@ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
and map this 404 response error in your web.xml , like the following :
<error-page>
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
Hope that Helps .
This worked for me, inspired by Sheetal Kaul
pip uninstall matplotlib
python3 -m pip install matplotlib
I knew it installed in the wrong place when this worked:
python2.7
import matplotlib
Update:
Instagram are now banning accounts and removing the images based on this method. Please use with caution.
It seems that everyone who has answered this question with something along the lines of it can't be done
is somewhat correct. Officially, you cannot post a photo to Instagram with their API. However, if you reverse engineer the API, you can.
function SendRequest($url, $post, $post_data, $user_agent, $cookies) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://i.instagram.com/api/v1/'.$url);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($post) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return array($http, $response);
}
function GenerateGuid() {
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(16384, 20479),
mt_rand(32768, 49151),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535));
}
function GenerateUserAgent() {
$resolutions = array('720x1280', '320x480', '480x800', '1024x768', '1280x720', '768x1024', '480x320');
$versions = array('GT-N7000', 'SM-N9000', 'GT-I9220', 'GT-I9100');
$dpis = array('120', '160', '320', '240');
$ver = $versions[array_rand($versions)];
$dpi = $dpis[array_rand($dpis)];
$res = $resolutions[array_rand($resolutions)];
return 'Instagram 4.'.mt_rand(1,2).'.'.mt_rand(0,2).' Android ('.mt_rand(10,11).'/'.mt_rand(1,3).'.'.mt_rand(3,5).'.'.mt_rand(0,5).'; '.$dpi.'; '.$res.'; samsung; '.$ver.'; '.$ver.'; smdkc210; en_US)';
}
function GenerateSignature($data) {
return hash_hmac('sha256', $data, 'b4a23f5e39b5929e0666ac5de94c89d1618a2916');
}
function GetPostData($filename) {
if(!$filename) {
echo "The image doesn't exist ".$filename;
} else {
$post_data = array('device_timestamp' => time(),
'photo' => '@'.$filename);
return $post_data;
}
}
// Set the username and password of the account that you wish to post a photo to
$username = 'ig_username';
$password = 'ig_password';
// Set the path to the file that you wish to post.
// This must be jpeg format and it must be a perfect square
$filename = 'pictures/test.jpg';
// Set the caption for the photo
$caption = "Test caption";
// Define the user agent
$agent = GenerateUserAgent();
// Define the GuID
$guid = GenerateGuid();
// Set the devide ID
$device_id = "android-".$guid;
/* LOG IN */
// You must be logged in to the account that you wish to post a photo too
// Set all of the parameters in the string, and then sign it with their API key using SHA-256
$data ='{"device_id":"'.$device_id.'","guid":"'.$guid.'","username":"'.$username.'","password":"'.$password.'","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = GenerateSignature($data);
$data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';
$login = SendRequest('accounts/login/', true, $data, $agent, false);
if(strpos($login[1], "Sorry, an error occurred while processing this request.")) {
echo "Request failed, there's a chance that this proxy/ip is blocked";
} else {
if(empty($login[1])) {
echo "Empty response received from the server while trying to login";
} else {
// Decode the array that is returned
$obj = @json_decode($login[1], true);
if(empty($obj)) {
echo "Could not decode the response: ".$body;
} else {
// Post the picture
$data = GetPostData($filename);
$post = SendRequest('media/upload/', true, $data, $agent, true);
if(empty($post[1])) {
echo "Empty response received from the server while trying to post the image";
} else {
// Decode the response
$obj = @json_decode($post[1], true);
if(empty($obj)) {
echo "Could not decode the response";
} else {
$status = $obj['status'];
if($status == 'ok') {
// Remove and line breaks from the caption
$caption = preg_replace("/\r|\n/", "", $caption);
$media_id = $obj['media_id'];
$device_id = "android-".$guid;
$data = '{"device_id":"'.$device_id.'","guid":"'.$guid.'","media_id":"'.$media_id.'","caption":"'.trim($caption).'","device_timestamp":"'.time().'","source_type":"5","filter_type":"0","extra":"{}","Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"}';
$sig = GenerateSignature($data);
$new_data = 'signed_body='.$sig.'.'.urlencode($data).'&ig_sig_key_version=4';
// Now, configure the photo
$conf = SendRequest('media/configure/', true, $new_data, $agent, true);
if(empty($conf[1])) {
echo "Empty response received from the server while trying to configure the image";
} else {
if(strpos($conf[1], "login_required")) {
echo "You are not logged in. There's a chance that the account is banned";
} else {
$obj = @json_decode($conf[1], true);
$status = $obj['status'];
if($status != 'fail') {
echo "Success";
} else {
echo 'Fail';
}
}
}
} else {
echo "Status isn't okay";
}
}
}
}
}
}
Just copy and paste the code above in your text editor, change the few variables accordingly and VOILA! I wrote an article about this and I've done it many times. See a demo here.
Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio
I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.
The plugin is available here
There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
Android's callOnClick()
(added in API 15) can sometimes be a better choice in my experience than performClick()
. If a user has selection sounds enabled, then performClick()
could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener
that you're calling via code.)
Well I think you just need to add a quantifier to each pattern. Also the carriage-return thing is a little funny:
text.replace(/[^a-z0-9]+|\s+/gmi, " ");
edit The \s
thing matches \r
and \n
too.
Although SOAP and REST share similarities over the HTTP protocol, SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are relevant because we can’t achieve any degree of standardization without them. REST needs no processing as an architecture style and is inherently more versatile. In the spirit of information exchange, both SOAP and REST depend on well-established laws that everybody has decided to abide by. The choice of SOAP vs. REST is dependent on the programming language you are using the environment you are using and the specifications.
Applets from what I remember do not need a main method, though I am not sure they are technically a program.
As per Miller's Recursive Make Considered Harmful you should avoid calling $(MAKE)
! In the case you show, it's harmless, because this isn't really a makefile, just a wrapper script, that might just as well have been written in Shell. But you say you continue like that at deeper recursion levels, so you've probably encountered the problems shown in that eye-opening essay.
Of course with GNU make it's cumbersome to avoid. And even though they are aware of this problem, it's their documented way of doing things.
OTOH, makepp was created as a solution for this problem. You can write your makefiles on a per directory level, yet they all get drawn together into a full view of your project.
But legacy makefiles are written recursively. So there's a workaround where $(MAKE)
does nothing but channel the subrequests back to the main makepp process. Only if you do redundant or, worse, contradictory things between your submakes, you must request --traditional-recursive-make
(which of course breaks this advantage of makepp). I don't know your other makefiles, but if they're cleanly written, with makepp necessary rebuilds should happen automatically, without the need for any hacks suggested here by others.
You can go use registry editor.
The main reason for this is when the database is open somewhere else.
This could be as already said by many others:
When recently I had the same problem although different versions, I started to search for the reason.
In my case I had an excel file that queried data from the database.
In case the excel file is opened before the database, access would give this error.
Conclusion:
Check all files/connections related to the database. An open ODBC connection or query used in excel (my case) open the mdb file and will make it readonly.
2014 March: Truncating long strings with CSS: a new answer with focus on browser support
Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).
<style type="text/css">
span {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
-o-text-overflow: ellipsis; /** Opera 9 & 10 **/
width: 370px; /* note that this width will have to be smaller to see the effect */
}
</style>
<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>
The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.
Successfully tested (on Browserstack.com) on Windows OS, for web browsers:
Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).
I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).
Some further testing on a Mac OS web browsers would be needed.
Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated
Resources:
<script type="text/javascript">
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
<form id="myform" action="/your_url" method="post">
...
</form>
i have same issue this work fine for me
<style>
td{
word-break: break-word;
}
</style>
<table style="width: 100%;">
<tr>
<td>Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</td>
<td><span style="display: inline;">Short word</span></td>
</tr>
</table>
I think that mergetool.meld.path
should point directly to the meld executable. Thus, the command you want is:
git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld
Instead of using a custom RecyclerView
, extending an AdapterDataObserver
is a simpler solution that allows setting a custom View
that is displayed when there are no items in the list:
Example Usage:
RVEmptyObserver observer = new RVEmptyObserver(recyclerView, emptyView)
rvAdapter.registerAdapterDataObserver(observer);
Class:
public class RVEmptyObserver extends RecyclerView.AdapterDataObserver {
private View emptyView;
private RecyclerView recyclerView;
public RVEmptyObserver(RecyclerView rv, View ev) {
this.recyclerView = rv;
this.emptyView = ev;
checkIfEmpty();
}
private void checkIfEmpty() {
if (emptyView != null && recyclerView.getAdapter() != null) {
boolean emptyViewVisible = recyclerView.getAdapter().getItemCount() == 0;
emptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
recyclerView.setVisibility(emptyViewVisible ? View.GONE : View.VISIBLE);
}
}
public void onChanged() { checkIfEmpty(); }
public void onItemRangeInserted(int positionStart, int itemCount) { checkIfEmpty(); }
public void onItemRangeRemoved(int positionStart, int itemCount) { checkIfEmpty(); }
}
Every managed exe has a an entry point which can be seen when if you load your code to ILDASM. The Entry Point is specified in the CLR headed and would look something like this.
With pure javascript:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i <= buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?