if(typeof theObject['key'] != 'undefined'){
//key exists, do stuff
}
//or
if(typeof theObject.key != 'undefined'){
//object exists, do stuff
}
I'm writing here because no one seems to give the right answer..
I know it's old...
Somebody might question the same thing..
You can use the collections.Counter. Note, this will work for both numeric and non-numeric values.
>>> x = {1: 2, 3: 4, 4:3, 2:1, 0:0}
>>> from collections import Counter
>>> #To sort in reverse order
>>> Counter(x).most_common()
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
>>> #To sort in ascending order
>>> Counter(x).most_common()[::-1]
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
>>> #To get a dictionary sorted by values
>>> from collections import OrderedDict
>>> OrderedDict(Counter(x).most_common()[::-1])
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])
ERROR: Linux / Centos:
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
Solution:
Edit the Jenkins init file by doing
sudo vi /etc/init.d/jenkins
Add your own Java path, for example:
/opt/oracle/product/java/jdk1.8.0_45/bin/java
Restart the service:
sudo service jenkins start
sudo service jenkins status
sudo service jenkins stop
Sharing another option found here with credentials
JENKINS_HOST=username:[email protected]:port
curl -sSL "http://$JENKINS_HOST/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins" | perl -pe 's/.*?<shortName>([\w-]+).*?<version>([^<]+)()(<\/\w+>)+/\1 \2\n/g'|sed 's/ /:/'
Create a link in /var/www
like this:
sudo ln -s /usr/share/phpmyadmin /var/www/
Note: since 14.04 you may want to use /var/www/html/
instead of /var/www/
If that's not working for you, you need to include PHPMyAdmin
inside apache configuration.
Open apache.conf
using your favorite editor, mine is nano :)
sudo nano /etc/apache2/apache2.conf
Then add the following line:
Include /etc/phpmyadmin/apache.conf
For Ubuntu 15.04 and 16.04
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin.conf
sudo service apache2 reload
Generally speaking when you are trying to 'just get a working example' it is best to 'just start writing code'. There is no code here to help you with, so it makes answering the question a lot more work for us.
If you want to grab a file, you need something like this in an html file somewhere:
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" />
<input type="submit" name="submit" value="Upload" />
</form>
That will give you the browse button, an upload button to start the action (submit the form) and note the enctype so Django knows to give you request.FILES
In a view somewhere you can access the file with
def myview(request):
request.FILES['myfile'] # this is my file
There is a huge amount of information in the file upload docs
I recommend you read the page thoroughly and just start writing code - then come back with examples and stack traces when it doesn't work.
You can convert the dates into UNIX timestamps and compare the difference between them in seconds.
$today_date=date("Y-m-d");
$entered_date=$_POST['date'];
$dateTimestamp1 = strtotime($today_date);
$dateTimestamp2 = strtotime($entered_date);
$diff= $dateTimestamp1-$dateTimestamp2;
//echo $diff;
if ($diff<=0)
{
echo "Enter a valid date";
}
You're misinterpreting what the onchange event does when applied to a textarea. It won't fire until it loses focus or you hit enter. Why not fire the function from an onchange on the select that fills in the text area?
Check out here for more on the onchange event: w3schools
It helps not to focus on the strong
or weak
part of the discussion. Instead focus on the cycle part.
A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:
Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.
So, what we're worried about is retain cycles, and there's nothing about blocks in and of themselves that create these cycles. This isn't a problem, for example:
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
[self doSomethingWithObject:obj];
}];
The block retains self
, but self
doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.
Where you get into trouble is something like:
//In the interface:
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL *stop);
//In the implementation:
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWithObj:obj];
}];
Now, your object (self
) has an explicit strong
reference to the block. And the block has an implicit strong reference to self
. That's a cycle, and now neither object will be deallocated properly.
Because, in a situation like this, self
by definition already has a strong
reference to the block, it's usually easiest to resolve by making an explicitly weak reference to self
for the block to use:
__weak MyObject *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[weakSelf doSomethingWithObj:obj];
}];
But this should not be the default pattern you follow when dealing with blocks that call self
! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self
was deallocated.
//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
//By the time this gets called, "weakSelf" might be nil because it's not retained!
[weakSelf doSomething];
}];
In the comments, I mentioned a step-by-step method to easily install multiple Chrome versions, side-by-side. This answer quotes my original answer, and includes a script which does the job for you.
Quoted from: section 7 of Cross-browser testing: All major browsers on ONE machine:
Chrome: Stand-alone installers can be downloaded from File Hippo. It is also possible to run multiple Chrome versions side-by-side.
Although Sandboxie can be used, it's recommended to use the next native method in order to run multiple versions side-by-side.
- Download the desired version(s) from File Hippo.
- Create a main directory, e.g.
C:\Chrome\
.- Extract the installer (=without installing), using 7-Zip for example. After extracting, a
chrome.7z
archive is created. Also extract this file, and descend the createdChrome-bin
directory. Now, you seechrome.exe
and a dir like18.0.1025.45
. Movechrome.exe
to18.0.1025.45
, then move this directory toC:\Chrome
. The remaining files inChrome-bin
can safely be deleted.Create a shortcut for each version:
"C:\Chrome\18.0.1024.45\chrome.exe" --user-data-dir="..\User Data\18" --chrome-version=18.0.1025.45
Explanation of this shortcut:
"C:\Chrome\18.0.1024.45\chrome.exe"
• This is the launcher--user-data-dir="..\User Data\18"
• User profile, relative to the location ofchrome.exe
. You could also have used--user-data-dir="C:\Chrome\User Data\18"
for the same effect. Set your preferences for the lowest Chrome version, and duplicate the User profile for each Chrome version. Older Chrome versions refuse to use User profiles from new versions.--chrome-version=18.0.1025.45
• Location of binaries:
- The location (eg
18.0.1025.45
) must be the name of the directory:- Must start and end with a number. A dot may appear in between.
- The numbers do not necessarily have to match the real version number (though it's convenient to use real version numbers...).
Regarding configuration: All preferences can be set at
chrome://settings/
. I usually change the home page and "Under the hood" settings.
- Disable auto-updates: http://dev.chromium.org/administrators/turning-off-auto-updates
(the old version of this answer referred to Old Apps for old Chrome versions, but they do not offer direct download links any more through the UI. The files do still exist, I've created a shell script (bash) to ease the creation of a local repository of Chrome versions - see https://gist.github.com/Rob--W/8577499)
I've created a VB script which installs and configures Chrome (tested in XP and Win 7). Launch the script, and a file dialog appears (or: Drag & drop the chrome installer on the VBS). Select the destination of the Chrome installer, and the script automatically unpacks the files and duplicates the profile from a pre-configured base directory.
By default:
C:\Chrome\
.C:\Chrome\User Data\
.sFolderChromeUserDataDefault
variable, which is C:\Chrome\User Data\2\
by default.The only dependency is 7-zip, expected to be located at C:\Program Files\7-zip\7z.exe
.
Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.
Code:
Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value
However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...
Code:
Cells(1, 3).Copy
Cells(1, 1).PasteSpecial (xlPasteFormats)
Application.CutCopyMode = False
This will put the results in tab delimited file(s) under a directory:
INSERT OVERWRITE LOCAL DIRECTORY '/home/hadoop/YourTableDir'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
STORED AS TEXTFILE
SELECT * FROM table WHERE id > 100;
You can clone the Array like
this.assignCustomerList = Object.assign([], this.customerList);
And clone the object like
this.assignCustomer = Object.assign({}, this.customer);
How about using unique()
itself?
df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
per = c("AYLIK", "AYLIK", "2 AYLIK", "2 AYLIK"),
hmm = 1:4)
df
# yad per hmm
# 1 BARBIE AYLIK 1
# 2 BARBIE AYLIK 2
# 3 BAKUGAN 2 AYLIK 3
# 4 BAKUGAN 2 AYLIK 4
unique(df[c("yad", "per")])
# yad per
# 1 BARBIE AYLIK
# 3 BAKUGAN 2 AYLIK
You can add parameter columns or use dict
with key which is converted to column name:
np.random.seed(123)
e = np.random.normal(size=10)
dataframe=pd.DataFrame(e, columns=['a'])
print (dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
e_dataframe=pd.DataFrame({'a':e})
print (e_dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
Maybe you can simply
$ sudo bash -c "echo vm.overcommit_memory=1 >> /etc/sysctl.conf"
$ sudo sysctl -p
It works for my case.
Reference: https://github.com/openai/gym/issues/110#issuecomment-220672405
My full example is here, but I will provide a summary below.
Layout
Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).
Make the swift file the xib file's owner.
Add the following code to the .swift file and hook up the outlets and actions from the .xib file.
import UIKit
class ResuableCustomView: UIView {
let nibName = "ReusableCustomView"
var contentView: UIView?
@IBOutlet weak var label: UILabel!
@IBAction func buttonTap(_ sender: UIButton) {
label.text = "Hi"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let view = loadViewFromNib() else { return }
view.frame = self.bounds
self.addSubview(view)
contentView = view
}
func loadViewFromNib() -> UIView? {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil).first as? UIView
}
}
Use it
Use your custom view anywhere in your storyboard. Just add a UIView
and set the class name to your custom class name.
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.
MyCustomClass.swift
MyCustomClass.xib
File's Owner
of the .xib file to be your custom class (MyCustomClass
)class
value (under the identity Inspector
) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.Assistant Editor
.
Connections Inspector
you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass
), but rather reference File's Owner
. Since File's Owner
is specified to be your custom class, the outlets will hook up and work propery. NibLoadable
protocol referenced below.
.swift
file name is different from your .xib
file name, then set the nibName
property to be the name of your .xib
file.required init?(coder aDecoder: NSCoder)
and override init(frame: CGRect)
to call setupFromNib()
like the example below.MyCustomClass
).Here is the protocol you will want to reference:
public protocol NibLoadable {
static var nibName: String { get }
}
public extension NibLoadable where Self: UIView {
public static var nibName: String {
return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
}
public static var nib: UINib {
let bundle = Bundle(for: Self.self)
return UINib(nibName: Self.nibName, bundle: bundle)
}
func setupFromNib() {
guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
}
}
And here is an example of MyCustomClass
that implements the protocol (with the .xib file being named MyCustomClass.xib
):
@IBDesignable
class MyCustomClass: UIView, NibLoadable {
@IBOutlet weak var myLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupFromNib()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupFromNib()
}
}
NOTE: If you miss the Gotcha and set the class
value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS
error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder)
method which then calls Self.nib.instantiate
and calls the init
again.
use pgAdmin or use pg_proc to get the source of your stored procedures. pgAdmin does the same.
Browsers may differ, and you should also remember to not trust any info generated by the client, that being said, the below statement works for me (Google Chrome v24 on Mac OS X 10.8.2)
var utcDate = new Date(new Date().getTime());
edit: "How is this different than just new Date()
?" see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Adding the 60000 * Date.getTimezoneOffset() as previous answers have stated is incorrect. First, you must think of all Dates/Times as already being UTC with a timezone modifier for display purposes.
Again, browsers may differ, however, Date.getTime() returns the number of milliseconds since 1970-01-01 UTC/GMT. If you create a new Date using this number as I do above, it will be UTC/GMT. However, if you display it by calling .toString() it will appear to be in your local timezone because .toString() uses your local timezone, not the timezone of the Date object it is called on.
I have also found that if you call .getTimezoneOffset() on a date, it will return your local timezone, not the timezone of the date object you called it on (I can't verify this to be standard however).
In my browser, adding 60000 * Date.getTimezoneOffset() creates a DateTime that is not UTC. However when displayed within my browser (ex: .toString() ), it displays a DateTime in my local timezone that would be correct UTC time if timezone info is ignored.
You could use preg_replace to swap out all non-numeric characters and the comma and period/full stop as follows:
$testString = '12.322,11T';
echo preg_replace('/[^0-9,.]+/', '', $testString);
The pattern can also be expressed as /[^\d,.]+/
The best way for DateTime is use a Trigger:
/************ ROLE ************/
drop table if exists `role`;
create table `role` (
`id_role` bigint(20) unsigned not null auto_increment,
`date_created` datetime,
`date_deleted` datetime,
`name` varchar(35) not null,
`description` text,
primary key (`id_role`)
) comment='';
drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
on `role`
for each row
set new.`date_created` = now();
You can add a new series, and name it at the same time. The name will be the index of the new row, and all the values will automatically be NaN.
df.append(pd.Series(name='Afterthought'))
Easy way by using commons-lang-2.3.jar that library of java to clone list
link download commons-lang-2.3.jar
How to use
oldList.........
List<YourObject> newList = new ArrayList<YourObject>();
foreach(YourObject obj : oldList){
newList.add((YourObject)SerializationUtils.clone(obj));
}
I hope this one can helpful.
:D
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
This is a safety measure to avoid pushing branches that are not ready to be published. Loosely speaking, by executing "git push", only local branches that already exist on the server with the same name will be pushed, or branches that have been pushed using the localbranch:remotebranch syntax.
To push all local branches to the remote repository, use --all
:
git push REMOTENAME --all
git push --all
or specify all branches you want to push:
git push REMOTENAME master exp-branch-a anotherbranch bugfix
In addition, it's useful to add -u
to the "git push" command, as this will tell you if your local branch is ahead or behind the remote branch. This is shown when you run "git status" after a git fetch.
This is the best you can do without JavaScript:
[draggable=true] {_x000D_
cursor: move;_x000D_
}_x000D_
_x000D_
.resizable {_x000D_
overflow: scroll;_x000D_
resize: both;_x000D_
max-width: 300px;_x000D_
max-height: 460px;_x000D_
border: 1px solid black;_x000D_
min-width: 50px;_x000D_
min-height: 50px;_x000D_
background-color: skyblue;_x000D_
}
_x000D_
<div draggable="true" class="resizable"></div>
_x000D_
When calling rsync within java (and perhaps other languages), I found that setting
-e ssh -p 22
resulting in rsync complaining it could not execute the binary:
ssh -p 22
because that path ssh -p 22
did not exist (the -p and 22 are no longer arguments for some reason and now make up part of the path to the binary rsync should call).
To workaround this problem I was able to use this environment variable:
export "RSYNC_RSH=ssh -p 2222"
(Programmatically set within java using env.put("RSYNC_RSH", "ssh -p " + port);
)
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
Just make sure that you have one root div and put everything inside this root
<div class="root">
<!--and put all child here --!>
<div class='child1'></div>
<div class='child2'></div>
</div>
and so on
Another thing I would like to add is that you need to select View -> Tool Windows -> Gradle before you can run the project using the Gradle.
If using the Gradle the project builds and runs normally but using the IntelliJ it doesn't, then this can solve the matter.
Allocate maximum memory to your docker machine from (docker preference -> advance )
Screenshot of advance settings:
This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.
docker run -m=4g {imageID}
Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.
see this code what i am used in my application
String data="{'foo':'bar','coolness':2.0, 'altitude':39000, 'pilot':{'firstName':'Buzz','lastName':'Aldrin'}, 'mission':'apollo 11'}";
I retrieved like this
JSONObject json = (JSONObject) JSONSerializer.toJSON(data);
double coolness = json.getDouble( "coolness" );
int altitude = json.getInt( "altitude" );
JSONObject pilot = json.getJSONObject("pilot");
String firstName = pilot.getString("firstName");
String lastName = pilot.getString("lastName");
System.out.println( "Coolness: " + coolness );
System.out.println( "Altitude: " + altitude );
System.out.println( "Pilot: " + lastName );
Proxy support and the Host field:
HTTP 1.1 has a required Host header by spec.
HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.
Example:
GET / HTTP/1.1
Host: www.blahblahblahblah.com
This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.
So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.
Persistent connections:
HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.
In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.
OPTIONS method:
HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.
Caching:
HTTP 1.0 had support for caching via the header: If-Modified-Since.
HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.
HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.
There are also further additions relating to caching like the Cache-Control header.
100 Continue status:
There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.
Much more:
Global.asax file contain the URL Route. Default URL route like this.
"{controller}/{action}/{id}"
So,Try this.
1. Right click your controller method as below.
Example: let say we call Index()
method.Right click on it.
2. Click Add View.. and give appropriate name.In this example name should be Index.
Then it will add correct View by creating with relevant folder structure.
I suggest to use
#selector {
text-transform: capitalize;
}
or
#selector::first-letter {
text-transform: uppercase;
}
By the way, check this w3schools link: http://www.w3schools.com/cssref/pr_text_text-transform.asp
I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href
attribute of each links. It will match whether double or single quotes are used.
<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1
You can view a full explanation of this regex at here.
Snippet playground:
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
Text to match:_x000D_
<input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
_x000D_
<button>Match</button>_x000D_
</label>
_x000D_
A python script from Sergiy Kolodyazhnyy posted on Copy only folders not files?:
#!/usr/bin/env python
import os,sys
dirs=[ r for r,s,f in os.walk(".") if r != "."]
for i in dirs:
os.makedirs(os.path.join(sys.argv[1],i))
or from the shell:
python -c 'import os,sys;dirs=[ r for r,s,f in os.walk(".") if r != "."];[os.makedirs(os.path.join(sys.argv[1],i)) for i in dirs]' ~/new_destination
FYI:
Using 2to3 utility.
$ cat try.py
import SimpleHTTPServer
$ 2to3 try.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored try.py
--- try.py (original)
+++ try.py (refactored)
@@ -1 +1 @@
-import SimpleHTTPServer
+import http.server
RefactoringTool: Files that need to be modified:
RefactoringTool: try.py
Like many *nix utils, 2to3
accepts stdin
if the argument passed is -
. Therefore, you can test without creating any files like so:
$ 2to3 - <<< "import SimpleHTTPServer"
Add this line to the dependencies in build.gradle:
compile 'com.mcxiaoke.volley:library:1.0.+'
Per the docs, you can catch the appropriate exception type (ClientErrorResponseException
for 4xx errors) and call its getResponse()
method to get the response object, then call getBody()
on that:
use Guzzle\Http\Exception\ClientErrorResponseException;
...
try {
$response = $request->send();
} catch (ClientErrorResponseException $exception) {
$responseBody = $exception->getResponse()->getBody(true);
}
Passing true
to the getBody
function indicates that you want to get the response body as a string. Otherwise you will get it as instance of class Guzzle\Http\EntityBody
.
You can check if the object is produced by JQuery with the jquery
property:
myObject.jquery // 3.3.1
=> return the number of the JQuery version if the object produced by JQuery.
=> otherwise, it returns undefined
Also something that can go wrong: Make sure you exit Docker for Mac (possibly all other kind of docker installations as well).
g.next()
has been renamed to g.__next__()
. The reason for this is consistency: special methods like __init__()
and __del__()
all have double underscores (or "dunder" in the current vernacular), and .next()
was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]
But instead of calling g.__next__()
, use next(g)
.
[*] There are other special attributes that have gotten this fix; func_name
, is now __name__
, etc.
After reading all the solutions posted here. This is how I solved it:
// How to embedded a "Text file" inside of a C# project
// and read it as a resource from c# code:
//
// (1) Add Text File to Project. example: 'myfile.txt'
//
// (2) Change Text File Properties:
// Build-action: EmbeddedResource
// Logical-name: myfile.txt
// (note only 1 dot permitted in filename)
//
// (3) from c# get the string for the entire embedded file as follows:
//
// string myfile = GetEmbeddedResourceFile("myfile.txt");
public static string GetEmbeddedResourceFile(string filename) {
var a = System.Reflection.Assembly.GetExecutingAssembly();
using (var s = a.GetManifestResourceStream(filename))
using (var r = new System.IO.StreamReader(s))
{
string result = r.ReadToEnd();
return result;
}
return "";
}
Reading app/config/mailphp
Supported : "smtp", "mail", "sendmail"
Depending on your mail utilities installed on your machine, fill in the value of the driver key. I would do
'driver' => 'sendmail',
max_allowed_packet
is set in mysql config, not on php side
[mysqld]
max_allowed_packet=16M
You can see it's curent value in mysql like this:
SHOW VARIABLES LIKE 'max_allowed_packet';
You can try to change it like this, but it's unlikely this will work on shared hosting:
SET GLOBAL max_allowed_packet=16777216;
You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
EDIT
The [mysqld] is necessary to make the max_allowed_packet
working since at least mysql version 5.5.
Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet
. It you set the value under [mysqld_safe]
(which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld]
and restarted the mysqld, it worked.
In web applications within an enterprize can be used for holding session/window/thread/user specific data on the server for reasons of optimization and to preserve against loss of work where connection are unstable. As mentioned, race conditions need to be handled. We use a single instance of a class for this information and it is carefully managed.
To make it read only
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @readonly="true"})
To diable
@Html.TextBoxFor(m=> m.Total, new {@class ="form-control", @disabled="true"})
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.
So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.
This Python snippet will git mv --force
all files in a directory to be lowercase. For example, foo/Bar.js will become foo/bar.js via git mv foo/Bar.js foo/bar.js --force
.
Modify it to your liking. I just figured I'd share :)
import os
import re
searchDir = 'c:/someRepo'
exclude = ['.git', 'node_modules','bin']
os.chdir(searchDir)
for root, dirs, files in os.walk(searchDir):
dirs[:] = [d for d in dirs if d not in exclude]
for f in files:
if re.match(r'[A-Z]', f):
fullPath = os.path.join(root, f)
fullPathLower = os.path.join(root, f[0].lower() + f[1:])
command = 'git mv --force ' + fullPath + ' ' + fullPathLower
print(command)
os.system(command)
So easy:
git diff --name-only
Go forth and diff!
One of my college instructors explained it to me this way:
Suppose I have one class, which is a Toaster, and another class, which is NuclearBomb. They both might have a "darkness" setting. They both have an on() method. (One has an off(), the other doesn't.) If I want to create a class that's a subclass of both of these...as you can see, this is a problem that could really blow up in my face here.
So one of the main issues is that if you have two parent classes, they might have different implementations of the same feature — or possibly two different features with the same name, as in my instructor's example. Then you have to deal with deciding which one your subclass is going to use. There are ways of handling this, certainly — C++ does so — but the designers of Java felt that this would make things too complicated.
With an interface, though, you're describing something the class is capable of doing, rather than borrowing another class's method of doing something. Multiple interfaces are much less likely to cause tricky conflicts that need to be resolved than are multiple parent classes.
Say your variable is myNode
, you can do myNode.value
to retrieve the value of input elements.
Firebug has a "DOM" tab which shows useful DOM attributes.
Also see the mozilla page for a reference: https://developer.mozilla.org/en-US/docs/DOM/HTMLInputElement
Bootstrap 2.x
You could create a new CSS class such as:
.img-center {margin:0 auto;}
And then, add this to each IMG:
<img src="images/2.png" class="img-responsive img-center">
OR, just override the .img-responsive
if you're going to center all images..
.img-responsive {margin:0 auto;}
Demo: http://bootply.com/86123
Bootstrap 3.x
EDIT - With the release of Bootstrap 3.0.1, the center-block
class can now be used without any additional CSS..
<img src="images/2.png" class="img-responsive center-block">
Bootstrap 4
In Bootstrap 4, the mx-auto
class (auto x-axis margins) can be used to center images that are display:block
. However, img is display:inline
by default so text-center
can be used on the parent.
<div class="container">
<div class="row">
<div class="col-12">
<img class="mx-auto d-block" src="//placehold.it/200">
</div>
</div>
<div class="row">
<div class="col-12 text-center">
<img src="//placehold.it/200">
</div>
</div>
</div>
Here's my code (not optimized but a full working example):
<head>
<style>
#divtoshow {position:absolute;display:none;color:white;background-color:black}
#onme {width:150px;height:80px;background-color:yellow;cursor:pointer}
</style>
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}
function follow(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
document.onmousemove = follow;
</script>
</head>
<body>
<div id="divtoshow">test</div>
<br><br>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>Mouse over this</div>
</body>
I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs
Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:
wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:
python -V
I hope it helps
Javascript is the only viable way to do this client side (that is, CSS won't help you). In jQuery:
$("table td:last").css("border", "none");
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
jQuery.parseJSON - new in jQuery 1.4.1
for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).
I've used this creating an IFrame through Javascript and it worked for me:
// IFrame points to the IFrame element, obviously
IFrame.src = 'about: blank';
IFrame.style.backgroundColor = "transparent";
IFrame.frameBorder = "0";
IFrame.allowTransparency="true";
Not sure if it makes any difference, but I set those properties before adding the IFrame to the DOM. After adding it to the DOM, I set its src to the real URL.
Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)
Code:
include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf');
$a->decodePDF();
echo $a->output();
class.pdf2text.php
Project Home
pdf2textclass
doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser
Both setInterval
and requestAnimationFrame
don't work when tab is inactive or work but not at the right periods. A solution is to use another source for time events. For example web sockets or web workers are two event sources that work fine while tab is inactive. So no need to move all of your code to a web worker, just use worker as a time event source:
// worker.js
setInterval(function() {
postMessage('');
}, 1000 / 50);
.
var worker = new Worker('worker.js');
var t1 = 0;
worker.onmessage = function() {
var t2 = new Date().getTime();
console.log('fps =', 1000 / (t2 - t1) | 0);
t1 = t2;
}
jsfiddle link of this sample.
Pass the date into the function.
<?php
function getTheDay($date)
{
$curr_date=strtotime(date("Y-m-d H:i:s"));
$the_date=strtotime($date);
$diff=floor(($curr_date-$the_date)/(60*60*24));
switch($diff)
{
case 0:
return "Today";
break;
case 1:
return "Yesterday";
break;
default:
return $diff." Days ago";
}
}
?>
Having created my own emulator of the BBC Microcomputer of the 80s (type VBeeb into Google), there are a number of things to know.
Practically speaking, you're generally looking to write for speed and fidelity of emulation. This is because software on the target system will (may) run more slowly than the original hardware on the source system. That may constrain the choice of programming language, compilers, target system etc.
Further to that you have to circumscribe what you're prepared to emulate, for example its not necessary to emulate the voltage state of transistors in a microprocessor, but its probably necessary to emulate the state of the register set of the microprocessor.
Generally speaking the smaller the level of detail of emulation, the more fidelity you'll get to the original system.
Finally, information for older systems may be incomplete or non-existent. So getting hold of original equipment is essential, or at least prising apart another good emulator that someone else has written!
There's many reason that leads to
com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_60\bin\java.exe'' finished with non-zero exit value 1
If you are not hitting the dex limit but you are getting error similar to this Error:com.android.dx.cf.iface.ParseException: name already added: string{"a"}
Try disable proguard, if it manage to compile without issue then you will need to figure out which library caused it and add it to proguard-rules.pro
file
In my case this issue occur when I updated compile 'com.google.android.gms:play-services-ads:8.3.0'
to compile 'com.google.android.gms:play-services-ads:8.4.0'
One of the workaround is I added this to proguard-rules.pro
file
## Google AdMob specific rules ##
## https://developers.google.com/admob/android/quick-start ##
-keep public class com.google.ads.** {
public *;
}
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
Hope this will help some how in your case, I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe. So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time. As far as i can see the only condition is access to the parent page code. Hope this will help someone.
This should work with lambda expression:
personList.Distinct().ToDictionary(i => i.FirstandLastName, i => i);
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or filename.pl
?
EDIT:
To answer... sure, if you always have an extension of .jpg
, x.length-4
would work just fine.
However, if you don't know the length of your extension, any of a number of solutions are better/more robust.
x = x.replace(/\..+$/, '');
OR
x = x.substring(0, x.lastIndexOf('.'));
OR
x = x.replace(/(.*)\.(.*?)$/, "$1");
OR (with the assumption filename only has one dot)
parts = x.match(/[^\.]+/);
x = parts[0];
OR (also with only one dot)
parts = x.split(".");
x = parts[0];
Public Function LastData(rCol As Range) As Range
Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious)
End Function
Usage: ?lastdata(activecell.EntireColumn).Address
When you pass props
to super
, the props get assigned to this
. Take a look at the following scenario:
constructor(props) {
super();
console.log(this.props) //undefined
}
How ever when you do :
constructor(props) {
super(props);
console.log(this.props) //props will get logged.
}
This will format column A as text, B as General, C as a number.
Sub formatColumns()
Columns(1).NumberFormat = "@"
Columns(2).NumberFormat = "General"
Columns(3).NumberFormat = "0"
End Sub
Just few more details:
`image` blob
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
<img src="data:image/png;base64,'.base64_encode($row['image']).'">
Javascript, the language, came first, from Netscape.
Microsoft reverse engineered Javascript and called it JScript to avoid trademark issues with Sun. (Netscape and Sun were partnered up at the time, so this was less of an issue)
The languages are identical, both are dialects of ECMA script, the after-the-fact standard.
Although the languages are identical, since JScript runs in Internet Explorer, it has access to different objects exposed by the browser (such as ActiveXObject)
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
chmod a+x
modifies the argument's mode while chmod 755
sets it. Try both variants on something that has full or no permissions and you will notice the difference.
Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:
>>> import operator
>>> def multiply(*args):
... return reduce(operator.mul, args)
Then you use this function like:
>>> multiply(1,2,3)
6
or
>>> numbers = [1,2,3]
>>> multiply(*numbers)
6
You are populating your dictionaries with references to a single list so when you update it, the update is reflected across all the references. Try a dictionary comprehension instead. See Create a dictionary with list comprehension in Python
d = {k : v for k in blah blah blah}
The best way is to use the UINavigationController delegate methods
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
Using this you can know what controller is showing the UINavigationController.
if ([viewController isKindOfClass:[HomeController class]]) {
NSLog(@"Show home controller");
}
Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.
So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title
attribute).
There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.
On the other hand, in HTML 5 you have two options:
input of type number
:
<input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
– only validates the range – if user enters a non-number, an empty value is submitted
– the field visual is enhanced with increment / decrement controls (browser dependent)
the pattern
attribute:
<input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
<input type="text" pattern="\d{3}" title="Format: 3 digits" />
– this gives you a full contorl over the format (anything you can specify by regular expression)
– no visual difference / enhancement
But here you still rely on browser capabilities, so do a server-side validation in either case.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
You would create two functions and then run something similar to this.
Notice, you want to choose the same number of execution/run to compare apple to apple.
This was tested under Python 3.7.
Here is the code for ease of copying it
!/usr/local/bin/python3
import timeit
def fibonacci(n):
"""
Returns the n-th Fibonacci number.
"""
if(n == 0):
result = 0
elif(n == 1):
result = 1
else:
result = fibonacci(n-1) + fibonacci(n-2)
return result
if __name__ == '__main__':
import timeit
t1 = timeit.Timer("fibonacci(13)", "from __main__ import fibonacci")
print("fibonacci ran:",t1.timeit(number=1000), "milliseconds")
My requirement is to include a ListView of equally-sized items within a ScrollView. I tried a few of the other solutions listed here, none seemed to size the ListView correctly (either too little space or too much). Here's what worked for me:
public static void expandListViewHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
ViewGroup.LayoutParams params = listView.getLayoutParams();
listView.measure(0, 0);
params.height = listView.getMeasuredHeight() * listAdapter.getCount() + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
Hope this helps someone.
This command should do the trick (provided that you installed it using a dpkg-based packet manager):
aptitude purge ruby
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
To convert it to a single dictionary with some decided keys value, you can use the code below.
data = ListOfDict.copy()
PrecedingText = "Obs_"
ListOfDictAsDict = {}
for i in range(len(data)):
ListOfDictAsDict[PrecedingText + str(i)] = data[i]
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).
As much as I love XAML, for this kinds of tasks I switch to code behind. Attached behaviors are a good pattern for this. Keep in mind, Expression Blend 3 provides a standard way to program and use behaviors. There are a few existing ones on the Expression Community Site.
The proj.4 software provides a command line program that can do the conversion, e.g.
LAT=40
LON=-110
echo $LON $LAT | cs2cs +proj=latlong +datum=WGS84 +to +proj=geocent +datum=WGS84
It also provides a C API. In particular, the function pj_geodetic_to_geocentric
will do the conversion without having to set up a projection object first.
I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false}
property for window.addEventListener
, which is recommended as the only working solution, for example here.
In the end, after many tries, I found a way that works for me in both Firefox and Chrome:
window.addEventListener('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 37: // left
case 39: // right
e.preventDefault();
break;
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Quote for EventTarget.addEventListener()
from MDN
options Optional
An options object specifies characteristics about the event listener. The available options are:capture
ABoolean
indicating that events of this type will be dispatched to the registeredlistener
before being dispatched to anyEventTarget
beneath it in the DOM tree.
once
...
passive
ABoolean
that, if true, indicates that the function specified bylistener
will never callpreventDefault()
. If a passive listener does callpreventDefault()
, the user agent will do nothing other than generate a console warning. ...
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
http://en.wikipedia.org/wiki/Smart_pointer
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency. Smart pointers typically keep track of the objects that point to them for the purpose of memory management. The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers makes it very likely that some memory leaks will occur. Smart pointers try to prevent memory leaks by making the resource deallocation automatic: when the pointer to an object (or the last in a series of pointers) is destroyed, for example because it goes out of scope, the pointed object is destroyed too.
In my case, the folder ProgramData
was hidden by default on windows 7, so I was unable to find my.ini
file.
After selecting show hidden files and folders option, I was able to find the my.ini
file at the location: C:\ProgramData\MySQL\MySQL Server 5.6
.
Display hidden files and folders on windows 7:
Right-click the Windows Logo button and choose Open Windows Explorer.
Click Organize and choose Folder and Search Options.
Click the View tab, select Show hidden files and folders and then clear the checkbox for Hide protected system operating files.
Click Yes on the warning and then click OK.
None of that stuff worked. Here's a much simpler way .. the label str is the pointer to what IS an array...
String str = String(yourNumber, DEC); // Obviously .. get your int or byte into the string
str = str + '\r' + '\n'; // Add the required carriage return, optional line feed
byte str_len = str.length();
// Get the length of the whole lot .. C will kindly
// place a null at the end of the string which makes
// it by default an array[].
// The [0] element is the highest digit... so we
// have a separate place counter for the array...
byte arrayPointer = 0;
while (str_len)
{
// I was outputting the digits to the TX buffer
if ((UCSR0A & (1<<UDRE0))) // Is the TX buffer empty?
{
UDR0 = str[arrayPointer];
--str_len;
++arrayPointer;
}
}
I know you can't edit the HTML, but if you can modify the CSS, can you add javascript?
if so, you can include jquery, then you could do
<script language="javascript">
$(document).ready(function() {
$('br').append('<span class="myclass"></span>');
});
</script>
Use the values
attribute to return the values as a np array and then use [0]
to get the first value:
In [4]:
df.loc[df.Letters=='C','Letters'].values[0]
Out[4]:
'C'
EDIT
I personally prefer to access the columns using subscript operators:
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
This avoids issues where the column names can have spaces or dashes -
which mean that accessing using .
.
protected void DescargarArchivo(string strRuta, string strFile)
{
FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
Response.ContentType = "application/pdf";
Response.WriteFile(ObjArchivo.FullName);
Response.End();
}
Might be useful:
double a = 5.0/2.0;
Console.WriteLine (a); // 2.5
double b = 5/2;
Console.WriteLine (b); // 2
int c = 5/2;
Console.WriteLine (c); // 2
double d = 5f/2f;
Console.WriteLine (d); // 2.5
If you are using Python 3, you should use pip3 instead of pip. The command looks like $ pip3 install requirements.txt
Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:
import os
def my_lock(f):
if os.name == "posix":
# Unix or OS X specific locking here
elif os.name == "nt":
# Windows specific locking here
else:
print "Unknown operating system, lock unavailable"
I know this is a very old thread but I wish to post this to help those who bump into this like I did.
if you don't care about using a 3rd party script, you can use moment,js Then you can use .format() to format it to anything you want it to.
In 1.0, the functionality was bound to (
and tab
and shift-tab
, in 2.0 tab
was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab
. (
was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab
.
So press Shift-Tab
.
If you're looking for a ready-to-roll solution -
Mongoid has built in simple versioning
http://mongoid.org/en/mongoid/docs/extras.html#versioning
mongoid-history is a Ruby plugin that provides a significantly more complicated solution with auditing, undo and redo
if(isset($_POST['submit']))
{
if(!empty($_POST['login_username']) && !empty($_POST['login_password']))
{
$uname = $_POST['login_username'];
$pass = $_POST['login_password'];
$res="SELECT count(*),uname,role FROM users WHERE uname='$uname' and password='$pass' ";
$query=mysql_query($res)or die (mysql_error());
list($result,$uname,$role) = mysql_fetch_row($query);
$_SESSION['username'] = $uname;
$_SESSION['role'] = $role;
if(isset($_SESSION['username']) && $_SESSION['role']=="admin")
{
if($result>0)
{
header ('Location:Dashboard.php');
}
else
{
header ('Location:loginform.php');
}
}
/* Current time */
select now();
/* Epoch from current time;
Epoch is number of seconds since 1970-01-01 00:00:00+00 */
select extract(epoch from now());
/* Get back time from epoch */
-- Option 1 - use to_timestamp function
select to_timestamp( extract(epoch from now()));
-- Option 2 - add seconds to 'epoch'
select timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second';
/* Cast timestamp to date */
-- Based on Option 1
select to_timestamp(extract(epoch from now()))::date;
-- Based on Option 2
select (timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second')::date;
/* For column epoch_ms */
select to_timestamp(extract(epoch epoch_ms))::date;
parameter?: type
is a shorthand for parameter: type | undefined
I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part. But, it won't work for all cases (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char s_value[60], s_integral[60], s_fractional[60];
int i, found = 0, count = 1, integral, fractional;
scanf("%s", s_value);
for (i = 0; s_value[i] != '\0'; i++)
{
if (!found)
{
if (s_value[i] == '.')
{
found = 1;
s_integral[i] = '\0';
continue;
}
s_integral[i] = s_value[i];
count++;
}
else
s_fractional[i - count] = s_value[i];
}
s_fractional[i - count] = '\0';
integral = atoi(s_integral);
fractional = atoi(s_fractional);
printf("value = %s, integral = %d, fractional = %d\n",
s_value, integral, fractional);
return 0;
}
How I update my deviceToken
First when I login I send the first device token under the user collection and the current logged in user.
After that, I just override onNewToken(token:String)
in my FirebaseMessagingService()
and just update that value if a new token is generated for that user
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
val currentUser= FirebaseAuth.getInstance().currentUser?.uid
if(currentUser != null){
FirebaseFirestore.getInstance().collection("user").document(currentUser).update("deviceToken",token)
}
}
}
Each time your app opens it will check for a new token, if the user is not yet signed in it will not update the token, if the user is already logged in you can check for a newToken
then is a method callback stack which is available after a promise is resolved it is part of library like jQuery but now it is available in native JavaScript and below is the detail explanation how it works
You can do a Promise in native JavaScript : just like there are promises in jQuery, Every promise can be stacked and then can be called with Resolve and Reject callbacks, This is how you can chain asynchronous calls.
I forked and Edited from MSDN Docs on Battery charging status..
What this does is try to find out if user laptop or device is charging battery. then is called and you can do your work post success.
navigator
.getBattery()
.then(function(battery) {
var charging = battery.charging;
alert(charging);
})
.then(function(){alert("YeoMan : SINGH is King !!");});
function fetchAsync (url, timeout, onData, onError) {
…
}
let fetchPromised = (url, timeout) => {
return new Promise((resolve, reject) => {
fetchAsync(url, timeout, resolve, reject)
})
}
Promise.all([
fetchPromised("http://backend/foo.txt", 500),
fetchPromised("http://backend/bar.txt", 500),
fetchPromised("http://backend/baz.txt", 500)
]).then((data) => {
let [ foo, bar, baz ] = data
console.log(`success: foo=${foo} bar=${bar} baz=${baz}`)
}, (err) => {
console.log(`error: ${err}`)
})
Definition :: then is a method used to solve Asynchronous callbacks
this is introduced in ES6
Please find the proper documentation here Es6 Promises
A minor improvement on a variant:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
Because of short-circuit evaluation, getObject()
will immediately return null
if key
is not in Storage. It also will not throw a SyntaxError
exception if value
is ""
(the empty string; JSON.parse()
cannot handle that).
This should work:
System.currentTimeMillis();
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
Whenever we don't add width and add margin:auto
, I guess it will not work. It's from my experience. Width gives the idea where exactly it needs to provide equal margins.
You can try joda-time.
sed -e 's/regexp/\0\n/g'
\0 is the null, so your expression is replaced with null (nothing) and then...
\n is the new line
On some flavors of Unix doesn't work, but I think it's the solution to your problem.
echo "Hello" | sed -e 's/Hello/\0\ntmow/g'
Hello
tmow
check this code:
CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
It's a ton more portable, easier to use and more feature packed too.
Just something I found for Wordpress users,
As obvious as it sounds, If your div is returning some AJAX content based on say a header that would commonly link out to a new post page, some tutorials will say to return false since you're returning the post data on the same page and the return would prevent the page from moving. However if you return false, you also prevent Fancybox2 from doing it's thing as well. I spent hours trying to figure that stupid simple thing out.
So for these kind of links, just make sure that the href property is the hashed (#) div you wish to select, and in your javascript, make sure that you do not return false since you no longer will need to.
Simple I know ^_^
This is 100% working:
Thats it, hope it helps
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10)
date -= timedelta(days=5)
And convert back using:
s = date.strftime("%Y%m%d")
To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)
This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
This is horrifying. All these answers suggesting adding to the start of the label text, and there is not one word in the Java 11 (or earlier) documentation for JLabel to suggest that the text of a label is handled differently if it happens to start with <html>
. Who says that works everywhere and always will? And you can get big, big surprises wrapping arbitrary text in and handing it to an html layout engine.
I've upvoted the answer that suggests JTextArea. But I'll note that JTextArea isn't a drop-in replacement; by default it expands to fill rows, which is not how JLabel acts. I haven't come up with a solution to that yet.
Element
objects have no .getroot()
method. Drop that call, and the .tostring()
call works:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
You only need to use .getroot()
if you have an ElementTree
instance.
Other notes:
This produces a bytestring, which in Python 3 is the bytes
type.
If you must have a str
object, you have two options:
Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")
Use encoding='unicode'
; this avoids an encode / decode cycle:
xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8
as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?>
declaration. Use utf-8
or UTF-8
(with a dash) if you want to prevent this. When using encoding="unicode"
no declaration header is added.
If you're using Eclipse, then add the reference library
into your project as the following steps:
Project Explorer
View.Properties
.Android
in the Properties
window.Library
group, click Add...
OK
.OK
button again in the Properties window.If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
This is the simple one to perform substring in Go
package main
import "fmt"
var p = fmt.Println
func main() {
value := "address;bar"
// Take substring from index 2 to length of string
substring := value[2:len(value)]
p(substring)
}
I know I'm late, but I've only ever had this error if my Response.Redirect
is in a Try...Catch
block.
Never put a Response.Redirect into a Try...Catch block. It's bad practice
As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.
inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.
outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.
This code is far from perfect and probably should not be copied since I haven't tested it.
public void btnLogin_Click(UserLoginViewModel model)
{
bool ValidLogin = false; // this is our "result value"
try
{
using (Context Db = new Context)
{
User User = new User();
if (String.IsNullOrEmpty(model.EmailAddress))
ValidLogin = false; // no email address was entered
else
User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
ValidLogin = true; // login succeeded
}
}
catch (Exception ex)
{
throw ex; // something went wrong so throw an error
}
if (ValidLogin)
{
GenerateCookie(User);
Response.Redirect("~/Members/Default.aspx");
}
else
{
// do something to indicate that the login failed.
}
}
I have written the following code in my last assignment, it may help you:
// A method that converts the nano-seconds to Seconds-Minutes-Hours form
private static String formatTime(long nanoSeconds)
{
int hours, minutes, remainder, totalSecondsNoFraction;
double totalSeconds, seconds;
// Calculating hours, minutes and seconds
totalSeconds = (double) nanoSeconds / 1000000000.0;
String s = Double.toString(totalSeconds);
String [] arr = s.split("\\.");
totalSecondsNoFraction = Integer.parseInt(arr[0]);
hours = totalSecondsNoFraction / 3600;
remainder = totalSecondsNoFraction % 3600;
minutes = remainder / 60;
seconds = remainder % 60;
if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
else seconds += Double.parseDouble("." + arr[1]);
// Formatting the string that conatins hours, minutes and seconds
StringBuilder result = new StringBuilder(".");
String sep = "", nextSep = " and ";
if(seconds > 0)
{
result.insert(0, " seconds").insert(0, seconds);
sep = nextSep;
nextSep = ", ";
}
if(minutes > 0)
{
if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
sep = nextSep;
nextSep = ", ";
}
if(hours > 0)
{
if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
else result.insert(0, sep).insert(0, " hour").insert(0, hours);
}
return result.toString();
}
Just convert nano-seconds to milli-seconds.
Use this:
setContentView(R.layout.yourlayout);
//after setting yor layout do the following
EditText email = (EdiText) findViewById(R.id.vnosEmaila);
String val = email.getText().toString; // Use the toString method to convert the return value to a String.
//Your Toast with String val;
Toast toast = Toast.makeText(EmailGumb.this, val, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Thanks
in some cases where pywin32 is not the direct reference and other libraries require pywin32-ctypes to be installed; causes the "ImportError: No module named win32com" when application bundled with pyinstaller.
running following command solves on python 3.7 - pyinstaller 3.6
pip install pywin32==227
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/
is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
Here is what I use when I don't have access to the source string, e.g. for downloaded HTML:
// replace newlines with <br>
public static String replaceNewlinesWithBreaks(String source) {
return source != null ? source.replaceAll("(?:\n|\r\n)","<br>") : "";
}
For XML you should probably edit that to replace with <br/>
instead.
Example of its use in a function (additional calls removed for clarity):
// remove HTML tags but preserve supported HTML text styling (if there is any)
public static CharSequence getStyledTextFromHtml(String source) {
return android.text.Html.fromHtml(replaceNewlinesWithBreaks(source));
}
...and a further example:
textView.setText(getStyledTextFromHtml(someString));
I think somebody chose very unfortunate name for STATELESS concept and that's why the whole misunderstanding is caused. It's not about storing any kind of resources, but rather about the relationship between the client and the server.
Client: I'm keeping all the resources on my side and send you the "list" of all the important items which need to processed. Do your job.
Server: All right.. let me take the responsibility on filtering what's important to give you the proper response.
Which means that the server is the "slave" of the client and has to forget about his "master" after each request. Actually, STATELESS refers only to the state of the server.
https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_3
Günters answer is great, I just want to point out another way without using Observables.
Here we though have to remember that these objects are passed by reference, so if you want to do some work on the object in the child and not affect the parent object, I would suggest using Günther's solution. But if it doesn't matter, or actually is desired behavior, I would suggest the following.
@Injectable()
export class SharedService {
sharedNode = {
// properties
};
}
In your parent you can assign the value:
this.sharedService.sharedNode = this.node;
And in your children (AND parent), inject the shared Service in your constructor. Remember to provide the service at module level providers array if you want a singleton service all over the components in that module. Alternatively, just add the service in the providers array in the parent only, then the parent and child will share the same instance of service.
node: Node;
ngOnInit() {
this.node = this.sharedService.sharedNode;
}
And as newman kindly pointed, you can also have this.sharedService.sharedNode
in the html template or a getter:
get sharedNode(){
return this.sharedService.sharedNode;
}
When you run into a problem where it cats all.txt into all.txt, You can try check all.txt is existing or not, if exists, remove
Like this:
[ -e $"all.txt" ] && rm $"all.txt"
You should use @input
:
<input @input="handleInput" />
@input
fires when user changes input value.
@change
fires when user changed value and unfocus input (for example clicked somewhere outside)
You can see the difference here: https://jsfiddle.net/posva/oqe9e8pb/
For Swift 3 & 4:
Use Toaster library
Toast(text: "Hello, world!", duration: Delay.long)
For Swift 2:
Use JLToast
This works for me. Kudos go here.
jQuery.fn.redraw = function() {
return this.hide(0, function() {
$(this).show();
});
};
$(el).redraw();
In head:
(function() {
var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
})();
End of Body:
<script type="text/javascript">
google.load("jquery", "version");
</script>
Frames have been deprecated because they caused trouble for url navigation and hyperlinking, because the url would just take to you the index page (with the frameset) and there was no way to specify what was in each of the frame windows. Today, webpages are often generated by server-side technologies such as PHP, ASP.NET, Ruby etc. So instead of using frames, pages can simply be generated by merging a template with content like this:
Template File
<html>
<head>
<title>{insert script variable for title}</title>
</head>
<body>
<div class="menu">
{menu items inserted here by server-side scripting}
</div>
<div class="main-content">
{main content inserted here by server-side scripting}
</div>
</body>
</html>
If you don't have full support for a server-side scripting language, you could also use server-side includes (SSI). This will allow you to do the same thing--i.e. generate a single web page from multiple source documents.
But if you really just want to have a section of your webpage be a separate "window" into which you can load other webpages that are not necessarily located on your own server, you will have to use an iframe.
You could emulate your example like this:
Frames Example
<html>
<head>
<title>Frames Test</title>
<style>
.menu {
float:left;
width:20%;
height:80%;
}
.mainContent {
float:left;
width:75%;
height:80%;
}
</style>
</head>
<body>
<iframe class="menu" src="menu.html"></iframe>
<iframe class="mainContent" src="events.html"></iframe>
</body>
</html>
There are probably better ways to achieve the layout. I've used the CSS float attribute, but you could use tables or other methods as well.
If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py
with
import camelot
tables = camelot.read_pdf('foo.pdf')
You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.
tables.export('foo.csv', f='csv', compress=False)
Edit: tabula-py
appears roughly 6 times faster than camelot-py
so that should be used instead.
import camelot
import cProfile
import pstats
import tabula
cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt
cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt
print(time_tabula, time_camelot, time_camelot/time_tabula)
gave
1.8495559890000015 11.057014036000016 5.978199147125147
The following approach was inspired by this answer to a related (more general) question.
The approach is to read the MachineGuid
value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
. This value is generated during OS installation.
There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid
value.
However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.
public string GetMachineGuid()
{
string location = @"SOFTWARE\Microsoft\Cryptography";
string name = "MachineGuid";
using (RegistryKey localMachineX64View =
RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
{
if (rk == null)
throw new KeyNotFoundException(
string.Format("Key Not Found: {0}", location));
object machineGuid = rk.GetValue(name);
if (machineGuid == null)
throw new IndexOutOfRangeException(
string.Format("Index Not Found: {0}", name));
return machineGuid.ToString();
}
}
}
I tried all these answers, even closed Visual Studio and deleted all bin directories.
After starting it up again the MVC reference appeared to have a yellow exclamation mark on it, so I removed it and added it again.
Now it works, without copy local.
Just add click event by jquery in $(document).ready() like :
$(document).ready(function(){
$('#YourControlID').click(function(){
if(Check your condtion)
{
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
What about:
WHERE table.field = "0" or CAST(table.field as SIGNED) != 0
to test for numeric and the corrolary:
WHERE table.field != "0" and CAST(table.field as SIGNED) = 0
There's no easy way to do it, and like @alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.
<script>
var links = document.querySelectorAll( '.post-content a' );
for (var i = 0, length = links.length; i < length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
</script>
The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.
As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/
There is also the env_inst_info admin view. As with CanSpice I can only vouch for LUW, but there should at least be a similar view available for Z/OS.
SELECT * FROM SYSIBMADM.ENV_INST_INFO
I had same problem and the solution was very simple. Solution : foreign keys declared in table should not set to be not null.
reference : If you specify a SET NULL action, make sure that you have not declared the columns in the child table as NOT NULL. (ref )
I think it's better to create an interface for that class. And create a unit test using interface.
If it you don't have access to that class, you can create an adapter for that class.
For example:
public class RealClass
{
int DoSomething(string input)
{
// real implementation here
}
}
public interface IRealClassAdapter
{
int DoSomething(string input);
}
public class RealClassAdapter : IRealClassAdapter
{
readonly RealClass _realClass;
public RealClassAdapter() => _realClass = new RealClass();
int DoSomething(string input) => _realClass.DoSomething(input);
}
This way, you can easily create mock for your class using IRealClassAdapter.
Hope it works.
Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:
$(".row").each( function() {
if ( ! leaveTheLoop ) {
... do stuff here ...
}
});
Rather than actually returning like this:
$(".row").each( function() {
if ( leaveTheLoop )
return; //go to next iteration in .each()
... do stuff here ...
});
A simple function that makes GIFs:
import imageio
import pathlib
from datetime import datetime
def make_gif(image_directory: pathlib.Path, frames_per_second: float, **kwargs):
"""
Makes a .gif which shows many images at a given frame rate.
All images should be in order (don't know how this works) in the image directory
Only tested with .png images but may work with others.
:param image_directory:
:type image_directory: pathlib.Path
:param frames_per_second:
:type frames_per_second: float
:param kwargs: image_type='png' or other
:return: nothing
"""
assert isinstance(image_directory, pathlib.Path), "input must be a pathlib object"
image_type = kwargs.get('type', 'png')
timestampStr = datetime.now().strftime("%y%m%d_%H%M%S")
gif_dir = image_directory.joinpath(timestampStr + "_GIF.gif")
print('Started making GIF')
print('Please wait... ')
images = []
for file_name in image_directory.glob('*.' + image_type):
images.append(imageio.imread(image_directory.joinpath(file_name)))
imageio.mimsave(gif_dir.as_posix(), images, fps=frames_per_second)
print('Finished making GIF!')
print('GIF can be found at: ' + gif_dir.as_posix())
def main():
fps = 2
png_dir = pathlib.Path('C:/temp/my_images')
make_gif(png_dir, fps)
if __name__ == "__main__":
main()
Since the question was asked/answered long time ago, those top answers do not work for me. Here's my solution, in 2020.
Background: Fresh mysql/mariadb installed by homebrew.
Problem: The password for root is not empty and unknown.
The fix:
The reason:
Easiest way for me to fix this issue:
This solution will give you the Network parameters. Check out this solution
The compile can't know T couldn't be a struct (value type). So you have to tell it it can only be of reference type i think:
bool Compare<T>(T x, T y) where T : class { return x == y; }
It's because if T could be a value type, there could be cases where x == y
would be ill formed - in cases when a type doesn't have an operator == defined. The same will happen for this which is more obvious:
void CallFoo<T>(T x) { x.foo(); }
That fails too, because you could pass a type T that wouldn't have a function foo. C# forces you to make sure all possible types always have a function foo. That's done by the where clause.
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U
I had to use required="required"
along with the same name and type, and then validation worked fine.
<input type="radio" name="user-radio" id="" value="User" required="required" />
<input type="radio" name="user-radio" id="" value="Admin" />
<input type="radio" name="user-radio" id="" value="Guest" />
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
This solution works if you are using asp.net validators:
<script language="javascript" type="text/javascript">
function disableButton(sender,group)
{
Page_ClientValidate(group);
if (Page_IsValid)
{
sender.disabled = "disabled";
__doPostBack(sender.name, '');
}
}</script>
and change the button:
<asp:Button runat="server" ID="btnSendMessage" Text="Send" OnClick="btnSendMessage_OnClick" OnClientClick="disableButton(this,'theValidationGroup')" CausesValidation="true" ValidationGroup="theValidationGroup" />
While the accepted answer is good in theory, it ignores the fact that the thumb then cannot be bigger than size of the track without being chopped off by the overflow: hidden
. See this example of how to handle this with just a tiny bit of JS.
// .chrome styling Vanilla JS
document.getElementById("myinput").oninput = function() {
var value = (this.value-this.min)/(this.max-this.min)*100
this.style.background = 'linear-gradient(to right, #82CFD0 0%, #82CFD0 ' + value + '%, #fff ' + value + '%, white 100%)'
};
_x000D_
#myinput {
background: linear-gradient(to right, #82CFD0 0%, #82CFD0 50%, #fff 50%, #fff 100%);
border: solid 1px #82CFD0;
border-radius: 8px;
height: 7px;
width: 356px;
outline: none;
transition: background 450ms ease-in;
-webkit-appearance: none;
}
_x000D_
<div class="chrome">
<input id="myinput" min="0" max="60" type="range" value="30" />
</div>
_x000D_
Another way of doing this in plain bash is making use of the rev
command like this:
cat file | rev | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","
Basically, you reverse the lines of the file, then split them with cut
using space as the delimiter, take the first field that cut
produces and then you reverse the token again, use tr -d
to delete unwanted chars and tr
again to replace newline chars with ,
Also, you can avoid the first cat by doing:
rev < file | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","
As everyone said above
var str = "foo"
str += " bar"
console.log(str) //will now give you "foo bar"
_x000D_
Check this out as well https://www.sitepoint.com/shorthand-javascript-techniques/
Both of the following code will work fine for removing highchart.com from the chart:-
credits: false
or
credits:{
enabled:false,
}
android:ellipsize
added in API Level 1. An ellipsis
is three periods in a row. (...) .
In your Xml
<TextView
....
android:text="Hi I am Amiyo, you can see how to ellipse works."
android:ellipsize = "end"
/>
At this point, the ellipsis will not display yet as a TextView is set to automatically expand on default when new text is entered. You will need to limit the TextView in some way. Do do this, you can use either add to your TextView a scrollHorizontally, minLines, or maxLines
to have the ellipsis display.
To make the ellipse:
at the end: this is how it would.
use: android:ellipsize = "end"
And
in the middle:
use: android:ellipsize = "middle"
And
at the start:
use: android:ellipsize = "start"
And
to have no ellipse
use: android:ellipsize = "none"
Note Please :
Do not use android:singeLine = "true", it is deprecated.
android:maxLines = "1" will not display the three dots (...)
android:lines = "1" will not display the three dots (...)
For more details you can visit here
http://developer.android.com/reference/android/widget/TextView.html#attr_android%3aellipsize
I bumped into this problem as well. Using the Python csv
module, I was trying to read an XLS file created in MS Excel and running into the NULL byte
error you were getting. I looked around and found the xlrd Python module for reading and formatting data from MS Excel spreadsheet files. With the xlrd
module, I am not only able to read the file properly, but I can also access many different parts of the file in a way I couldn't before.
I thought it might help you.
This question is old but I just had the same problem and solved it like this
LayoutParams lay = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)
lay.gravity = Gravity.CENTER;
Not 100%; however, it sounds like the heap is an object or set of allocated space (on RAM) that is built into the functionality of the code either Java itself or more likely functionality from ehcache itself, and the off-heap Ram is there own system as well; however, it sounds like this is one magnitude slower as it is not as organized, meaning it may not use a heap (meaning one long set of space of ram), and instead uses different address spaces likely making it slightly less efficient.
Then of course the next tier lower is hard-drive space itself.
I don't use ehcache, so you may not want to trust me, but that what is what I gathered from their documentation.
This error can be caused by an unclosed set of brackets.
int main {
doSomething {}
doSomething else {
}
Not so easy to spot, even in this 4 line example.
This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.
Another alternative :
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json
Then with python2 :
>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
"a": 1,
"b": 2,
"c": 3
}
or with python 3 :
>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
"a": 1,
"b": 2,
"c": 3
}
This should work:
Regex.IsMatch("124", "^[0-9]+$", RegexOptions.Compiled)
int.Parse
or int.TryParse
won't always work, because the string might contain more digits that an int can hold.
If you are going to do this check more than once it is useful to use a compiled regex - it takes more time the first time, but is much faster after that.
hi see the following sample code of xml file.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="@+id/TextView01" >
</TextView>
</LinearLayout>
</RelativeLayout>
</ScrollView>
PHP array_walk() function is specifically for altering array.
Try this:
array_walk ( $data, function (&$key) {
$key["transaction_date"] = date('d/m/Y',$key["transaction_date"]);
});
Use any()
.
if any(t < 0 for t in x):
# do something
numpy.array
is a function that returns a numpy.ndarray
. There is no object type numpy.array.
If you don't specify visibility for a class member, it defaults to "private". You should make your members private or protected if you want to access them in a subclass.
You need to include the library path (-L/usr/local/lib/)
gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto
It works for me.
ReactJs defines the following synthetic events for mouse events:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
As you can see there is no hover event, because browsers do not define a hover event natively.
You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.
This is not so much an answer to your original question as to one of the queries you had in the body of your question.
A little preamble, so that my naming doesn't seem strange:
import matplotlib
from matplotlib import rc
from matplotlib.figure import Figure
ax = self.figure.add_subplot( 111 )
As has been mentioned you can use ticklabel_format to specify that matplotlib should use scientific notation for large or small values:
ax.ticklabel_format(style='sci',scilimits=(-3,4),axis='both')
You can affect the way that this is displayed using the flags in rcParams (from matplotlib import rcParams) or by setting them directly. I haven't found a more elegant way of changing between '1e' and 'x10^' scientific notation than:
ax.xaxis.major.formatter._useMathText = True
This should give you the more Matlab-esc, and indeed arguably better appearance. I think the following should do the same:
rc('text', usetex=True)
No, the @jmlane answer is wrong.
Checkin (git add, git commit)
:text
property is Set, Set value to 'auto'
, the conversion happens enen the file has been committed with 'CRLF'text
property is Unset
:nothing happens, enen for Checkout
text
property is Unspecified
, conversion depends on core.autocrlf
autocrlf = input or autocrlf = true
, the conversion only happens when the file in the repository is 'LF', if it has been 'CRLF', nothing will happens.autocrlf = false
, nothing happensCheckout
:text
property is Unset
: nothing happens.text
property is Set, Set value to 'auto
: it depends on core.autocrlf
, core.eol
.
core.eol
text
property is Unspecified
, it depends on core.autocrlf
.
2.1
2.2
text
property is Unspecified
So the Default behavior is text
property is Unspecified
and core.autocrlf = false
:
text
property is set, checkin behavior is depends on itself, not on autocrlfFrom man 1 pkill
-f The pattern is normally only matched against the process name.
When -f is set, the full command line is used.
Which means, for example, if we see these lines in ps aux
:
apache 24268 0.0 2.6 388152 27116 ? S Jun13 0:10 /usr/sbin/httpd
apache 24272 0.0 2.6 387944 27104 ? S Jun13 0:09 /usr/sbin/httpd
apache 24319 0.0 2.6 387884 27316 ? S Jun15 0:04 /usr/sbin/httpd
We can kill them all using the pkill -f
option:
pkill -f httpd
I have looked at all the responses and tested them all. I pretty much compiled them all into one as a 'Safety closure'. This in c#
NOTE you can change the param from IModule app to that of the actual driver.
public class WebDriverCleaner
{
public static void CloseWebDriver(IModule app)
{
try
{
if (app?.GetDriver() != null)
{
app.GetDriver().Close();
Thread.Sleep(3000); // Gives time for everything to close before quiting
app.GetDriver().Quit();
app.GetDriver().Dispose();
KillProcessAndChildren("chromedriver.exe"); // One more to make sure we get rid of them chromedrivers.
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public static void KillProcessAndChildren(string p_name)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher
("Select * From Win32_Process Where Name = '" + p_name + "'");
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch (ArgumentException)
{
break;
}
}
}
public static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
try
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
catch
{
break;
}
}
try
{
Process proc = Process.GetProcessById(pid);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
}
Using yaml folded style. The indention in each line will be ignored. A line break will be inserted at the end.
Key: >
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with only a single carriage return appended to the end.
http://symfony.com/doc/current/components/yaml/yaml_format.html
You can use the "block chomping indicator" to eliminate the trailing line break, as follows:
Key: >-
This is a very long sentence
that spans several lines in the YAML
but which will be rendered as a string
with NO carriage returns.
In either case, each line break is replaced by a space.
There are other control tools available as well (for controlling indentation for example).
Preamble
below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!
To undo make install
I would do (and I did) this:
Idea: check whatever script installs and undo this with simple bash script.
--prefix=$PWD/install
. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.make install
again).make install
script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local
). So, we need a script.
3.1. Script should compare custom dir, with dir you want clean. I use this:anti-install.sh
RM_DIR=$1
PRESENT_DIR=$2
echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"
pushd $RM_DIR
for fn in `find . -iname '*'`; do
# echo "Checking $PRESENT_DIR/$fn..."
if test -f "$PRESENT_DIR/$fn"; then
# First try this, and check whether things go plain
echo "rm $RM_DIR/$fn"
# Then uncomment this, (but, check twice it works good to you).
# rm $RM_DIR/$fn
fi
done
popd
3.2. Now just run this script (it will go dry-run)
bash anti-install.sh <dir you want to clean> <custom installation dir>
E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/llvm.build/install, then it would be
bash anti-install.sh /usr/local /user/me/llvm.build/install
3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn
and run it again. But stop! Did you really check carefully? May be check again?
Source to instructions: https://dyatkovskiy.com/2019/11/26/anti-make-install/
Good luck!
Another great Treeview jquery plugin is http://www.jstree.com/
For an advance view you should check jquery-treetable
http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/
I've had trouble with git revert in the past (mainly because I'm not quite certain how it works.) I've had trouble reverting because of merge problems..
My simple solution is this.
Step 1.
git clone <your repos URL> .
your project in another folder, then:
Step 2.
git reset --hard <the commit you wanna go to>
then Step 3.
in your latest (and main) project dir (the one that has the problematic last commit) paste the files of step 2
Step 4.
git commit -m "Fixing the previous messy commit"
Step 5.
Enjoy
Haha, I have been stuck at that point a while ago as well, so I am glad I can help you out with a solution, that worked for me at least :)
What you want to do is define a new style within values/styles.xml so it looks like this
<resources>
<style name = "AppTheme" parent = "android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name = "NoActionBar" parent = "@android:style/Theme.Holo.Light">
<item name = "android:windowActionBar">false</item>
<item name = "android:windowNoTitle">true</item>
</style>
</resources>
Only the NoActionBar style is intresting for you. At last you have to set is as your application's theme in the AndroidManifest.xml so it looks like this
<application
android:allowBackup = "true"
android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name"
android:theme = "@style/NoActionBar" <!--This is the important line-->
>
<activity
[...]
I hope this helps, if not, let me know.
Here is another way to run multi line commands.
apiVersion: batch/v1 kind: Job metadata: name: multiline spec: template: spec: containers: - command: - /bin/bash - -exc - | set +x echo "running below scripts" if [[ -f "if-condition.sh" ]]; then echo "Running if success" else echo "Running if failed" fi name: ubuntu image: ubuntu restartPolicy: Never backoffLimit: 1
@objc
, see below example!#selector(name)
.private
or public
doesn't matter; you can use private.override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let menuButtonImage = UIImage(systemName: "flame")
let menuButton = UIBarButtonItem(image: menuButtonImage, style: .plain, target: self, action: #selector(didTapMenuButton))
navigationItem.rightBarButtonItem = menuButton
}
@objc public func didTapMenuButton() {
print("Hello World")
}
You can use sp_MSforeachdb to search all databases.
declare @RETURN_VALUE int
declare @command1 nvarchar(2000)
set @command1 = "Your command goes here"
exec @RETURN_VALUE = sp_MSforeachdb @command1 = @command1
Raj