var select = new SelectElement(elementX);
select.MoveToElement(elementX).Build().Perform();
var click = (
from sel in select
let value = "College"
select value
);
I have similar issue on touch devices. Adding "touch-action: none" to the element resolved the issue.
For more information. Check this out:-
https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action
Simply just do in this way.
string yourFormat = DateTime.Now.ToString("yyyyMMdd");
Happy coding :)
Try this:
np.concatenate((a, np.array([a[0]])))
http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html
concatenate needs both elements to be numpy arrays; however, a[0] is not an array. That is why it does not work.
Either specify the type of T, or if you want to make it generic, you'll need to make the parent class generic.
public class MyClass<T>
{
etc
As of July 2012, the WebAudio API is now supported in Chrome, and at least partly supported in Firefox, and is slated to be added to IOS as of version 6.
Although it is robust enough to be used programatically for basic tasks, the Audio element was never meant to provide full audio support for games, etc. It was designed to allow a single piece of media to be embedded in a page, similar to an img tag. There are a lot of issues with trying to use the Audio tag for games:
I used this Getting Started With WebAudio article to get started with the WebAudio API. The FieldRunners WebAudio Case Study is also a good read.
UPDATE:
You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.
First, list locally-tracking branches that were merged in remote (you may consider to use -r flag to list all remote-tracking branches as suggested in other answers).
git branch --merged
You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.
git branch --merged| egrep -v "(^\*|master|main|dev)"
If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name
will not be deleted.
git branch --merged| egrep -v "(^\*|master|main|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | egrep -v "(^\*|master|main|dev)" | xargs git branch -d
You can see that master and dev are excluded in case they are an ancestor.
You can delete a merged local branch with:
git branch -d branchname
If it's not merged, use:
git branch -D branchname
To delete it from the remote use:
git push --delete origin branchname
git push origin :branchname # for really old git
Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:
git remote prune origin
or prune individual remote tracking branches, as the other answer suggests, with:
git branch -dr branchname
//Turn off submit on "Enter" key
$("form").bind("keypress", function (e) {
if (e.keyCode == 13) {
$("#btnSearch").attr('value');
//add more buttons here
return false;
}
});
To include the direction along with the orderBy function:
ng-repeat="card in cards | orderBy:myOrderbyFunction():defaultSortDirection"
where
defaultSortDirection = 0; // 0 = Ascending, 1 = Descending
I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout
to 1min as suggested by this link
Yes VBA is the way to go.
But, if you don't need to have a cell with formula that auto-counts/updates the number of cells with a particular colour, an alternative is simply to use the 'Find and Replace' function and format the cell to have the appropriate colour fill.
Hitting 'Find All' will give you the total number of cells found at the bottom left of the dialogue box.
This becomes especially useful if your search range is massive. The VBA script will be very slow but the 'Find and Replace' function will still be very quick.
MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…
SELECT * FROM `table` WHERE `column` = 'value'
The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY
operator, which forces a byte by byte comparison:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
FileReaderJS can read the files for you. You get the file content inside onLoad(e)
event handler as e.target.result
.
Example: @property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
By Default automatically get and set to nil
Example : @property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.
import unittest
test = unittest.TestCase()
test.assertEqual(dictA, dictB)
PHPUnit is hiding the output with ob_start()
. We can disable it temporarily.
public function log($something = null)
{
ob_end_clean();
var_dump($something);
ob_start();
}
You can call the method newLine()
provided by java, to insert the new line in to a file.
For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()
cout
is in std namespace, you shall use std::cout
in your code.
And you shall not add using namespace std;
in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.
However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub
. What if there are multiple jenkins servers that need to access the same gitolite server?
(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)
So in this case you do need to run the Jenkins daemon as a different user.
There are two steps:
The main thing is to update the JENKINS_USER
environment variable. Here's a patch showing how to change the user to ptran
.
--- etc/default/jenkins.old 2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
PIDFILE=/var/run/jenkins/jenkins.pid
# user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran
# location of the jenkins war file
JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old 2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins 2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@
#DAEMON=$JENKINS_SH
DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG - -pidfile=$PIDFILE"
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE"
SU=/bin/su
END PATCH
Update ownership of jenkins directories:
chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins
Restart jenkins
sudo service jenkins restart
Repeat >> reads in loop.
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
Result:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
If you know exactly, how many elements there are in a file, you can chain >> operator:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
Edit: In response to your comments in main question.
You have two options.
Edit: How to skip values in file
To choose the 1234th value, use the following code:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
you should use tagName
property and attr('type')
for inputs
All good answers, to which I must add:
Since TRUNCATE TABLE
is a DDL (Data Defination Language), not a DML (Data Manipulation Langauge) command, the Delete Triggers
do not run.
Since other solutions are old and either poorly-working or not working at all, I've modified NestedScrollView
, which is stable, modern and it has all you expect from a scroll view. Except for horizontal scrolling.
Here's the repo: https://github.com/ultimate-deej/TwoWayNestedScrollView
I've made no changes, no "improvements" to the original NestedScrollView
expect for what was absolutely necessary.
The code is based on androidx.core:core:1.3.0
, which is the latest stable version at the time of writing.
All of the following works:
NestedScrollView
)you can also skip creating dictionary altogether. i used below approach to same problem .
mappedItems: {};
items.forEach(item => {
if (mappedItems[item.key]) {
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
} else {
mappedItems[item.key] = [];
mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
}
});
when using ajax, try $.getJSON()
instead of $.get()
if you have trouble with the correct display of the results.
In my case i got only the first character of every result when i used $.get()
, although i used json_encode()
server-side.
The consensus answer above is good but if you've got problems running queries within stored procedures after fixing your my.cnf file, then try loading your SPs again.
I suspect MySQL must have compiled the SPs with the default only_full_group_by set originally. Therefore, even when I changed my.cnf and restarted mysqld it had no effect on the SPs, and they kept failing with "SELECT list is not in GROUP BY clause and contains nonaggregated column ... which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by".
Reloading the SPs must have caused them to be recompiled now with only_full_group_by disabled. After that, they seem to work as expected.
You are looking for child_process.exec
Here is the example:
const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
For Sublime Text 3, First Install Package Control:
Type Install package and then press enter Click here to see Install Package Search Pic
After the package got installed. It may prompt to restart SublimeText
It perfectly worked for me. Hopefully, it helped you too. For any left requirements, visit https://packagecontrol.io/installation#st3 here.
I tried doing.
db.copyDatabase('DB_toBeRenamed','Db_newName','host')
and came to know that it has been Deprecated by the mongo community although it created the backup or renamed DB.
WARNING: db.copyDatabase is deprecated. See http://dochub.mongodb.org/core/copydb-clone-deprecation
{
"note" : "Support for the copydb command has been deprecated. See
http://dochub.mongodb.org/core/copydb-clone-deprecation",
"ok" : 1
}
So not convinced with the above approach I had to take Dump of local using below command
mongodump --host --db DB_TobeRenamed --out E://FileName/
connected to Db.
use DB_TobeRenamed
then
db.dropDatabase()
then restored the DB with command.
mongorestore -host hostName -d Db_NewName E://FileName/
I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32
instead of the usual directory from which I run my python module
Using Thread.sleep(2000);
is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait
is the better solution.
However, I don't see why implicitlyWait
does not work in your case. Did you measure if the findElement
actually takes two seconds before throwing an exception. If so, can you try to use WebDriver's conditional wait as described in this answer?
Since the beginning, Swift has provided some facilities for making ObjC and C more Swifty, adding more with each version. Now, in Swift 3, the new "import as member" feature lets frameworks with certain styles of C API -- where you have a data type that works sort of like a class, and a bunch of global functions to work with it -- act more like Swift-native APIs. The data types import as Swift classes, their related global functions import as methods and properties on those classes, and some related things like sets of constants can become subtypes where appropriate.
In Xcode 8 / Swift 3 beta, Apple has applied this feature (along with a few others) to make the Dispatch framework much more Swifty. (And Core Graphics, too.) If you've been following the Swift open-source efforts, this isn't news, but now is the first time it's part of Xcode.
Your first step on moving any project to Swift 3 should be to open it in Xcode 8 and choose Edit > Convert > To Current Swift Syntax... in the menu. This will apply (with your review and approval) all of the changes at once needed for all the renamed APIs and other changes. (Often, a line of code is affected by more than one of these changes at once, so responding to error fix-its individually might not handle everything right.)
The result is that the common pattern for bouncing work to the background and back now looks like this:
// Move to a background thread to do some long running work
DispatchQueue.global(qos: .userInitiated).async {
let image = self.loadOrGenerateAnImage()
// Bounce back to the main thread to update the UI
DispatchQueue.main.async {
self.imageView.image = image
}
}
Note we're using .userInitiated
instead of one of the old DISPATCH_QUEUE_PRIORITY
constants. Quality of Service (QoS) specifiers were introduced in OS X 10.10 / iOS 8.0, providing a clearer way for the system to prioritize work and deprecating the old priority specifiers. See Apple's docs on background work and energy efficiency for details.
By the way, if you're keeping your own queues to organize work, the way to get one now looks like this (notice that DispatchQueueAttributes
is an OptionSet
, so you use collection-style literals to combine options):
class Foo {
let queue = DispatchQueue(label: "com.example.my-serial-queue",
attributes: [.serial, .qosUtility])
func doStuff() {
queue.async {
print("Hello World")
}
}
}
Using dispatch_after
to do work later? That's a method on queues, too, and it takes a DispatchTime
, which has operators for various numeric types so you can just add whole or fractional seconds:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // in half a second...
print("Are we there yet?")
}
You can find your way around the new Dispatch API by opening its interface in Xcode 8 -- use Open Quickly to find the Dispatch module, or put a symbol (like DispatchQueue
) in your Swift project/playground and command-click it, then brouse around the module from there. (You can find the Swift Dispatch API in Apple's spiffy new API Reference website and in-Xcode doc viewer, but it looks like the doc content from the C version hasn't moved into it just yet.)
See the Migration Guide for more tips.
http://blueimp.github.com/jQuery-File-Upload/ = great solution
According to their docs, the following browsers support drag & drop:
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
None of the previous solutions worked for me. However I noticed that although I installed Visual Studio version 15 (not to be confused with Visual Studio 2015) the directory created on my computer was for Visual Studio 14.
When I specified Visual Studio 14 when I pressed the configuration button it worked.
Tried all these methods for conversion ->
public static void main(String[] args) {
Object myObj = 10.101;
System.out.println("Cast to Double: "+((Double)myObj)+10.99); //concates
Double d1 = new Double(myObj.toString());
System.out.println("new Object String - Cast to Double: "+(d1+10.99)); //works
double d3 = (double) myObj;
System.out.println("new Object - Cast to Double: "+(d3+10.99)); //works
double d4 = Double.valueOf((Double)myObj);
System.out.println("Double.valueOf(): "+(d4+10.99)); //works
double d5 = ((Number) myObj).doubleValue();
System.out.println("Cast to Number and call doubleValue(): "+(d5+10.99)); //works
double d2= Double.parseDouble((String) myObj);
System.out.println("Cast to String to cast to Double: "+(d2+10)); //works
}
what is a SID and Service name
please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm
In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"
When I have to use one or another? Why do I need two of them?
Consider below mapping in a RAC Environment,
SID SERVICE_NAME
bob1 bob
bob2 bob
bob3 bob
bob4 bob
if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.
Please refer, https://community.oracle.com/thread/4049517
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
When using Windows, the comparison is cut short: memcache
appears to be the only client available.
imageView.setLayoutParams
(new ViewGroup.MarginLayoutParams
(width, ViewGroup.LayoutParams.MATCH_PARENT));
The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.
glib has functions for base64 encoding: https://developer.gnome.org/glib/stable/glib-Base64-Encoding.html
There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....
{
"name":"myname"
}
And you want to bring in this new json content (adding key "id")
{
"id": "134",
"name": "myname"
}
My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).
import json
# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' # assuming same directory (but you can work your magic here with os.)
# read existing json to memory. you do this to preserve whatever existing data.
with open(PATH_TO_JSON,'r') as jsonfile:
json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'
Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.
So what we can do now, is simply write to the same filename with the new data
# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"
with open(PATH_TO_JSON,'w') as jsonfile:
json.dump(json_content, jsonfile, indent=4) # you decide the indentation level
And there you go! data.json should be good to go for an good old POST request
A little bit late, but here's an extension that enable you to find a responder of any type, including ViewController.
extension NSObject{
func findNext(type: AnyClass) -> Any{
var resp = self as! UIResponder
while !resp.isKind(of: type.self) && resp.next != nil
{
resp = resp.next!
}
return resp
}
}
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
You can use --targets ARG
option where ARG is the name of textfile containing the targets for commit.
svn ci --targets myfiles.txt -m "another commit"
The normal idea would be to run the command and then use $?
to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.
ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.
I personally like to put this function in my .bashrc
file
Below I demonstrate a few ways in which you can use this:
# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.
$ ec echo test
test
$ echo $ec
0
# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.
$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0
# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`
$ ec -h echo test
$ echo $ec
0
Solution to your code using this function
#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
echo "Error when executing command: 'grep p' [$ec]"
exit $ec;
fi
You should also note that the exit code you will be seeing will be for the
grep
command that's being run, as it is the last command being executed. Not thels
.
From Java 8 onward you can try the following:
import java.time.*;
import java.time.temporal.ChronoUnit;
Instant start_time = Instant.now();
// Your code
Instant stop_time = Instant.now();
System.out.println(Duration.between(start_time, stop_time).toMillis());
//or
System.out.println(ChronoUnit.MILLIS.between(start_time, stop_time));
#define a <::BOOST_VERSION>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::106200': No such file or directory
Works even if preprocess to file
is enabled, even if invalid tokens are present:
#define a <::'*/`#>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::'*/`#': No such file or directory
GCC4.x: warning: missing terminating ' character [-Winvalid-pp-token]
#define a <::'*/`#>
Two-way binding just means that:
Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.
In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set
in the handler.
Here's a Fiddle with two-way binding set up in Backbone.
try this one
return Content("<form action='actionname' id='frmTest' method='post'><input type='hidden' name='someValue' value='" + someValue + "' /><input type='hidden' name='anotherValue' value='" + anotherValue + "' /></form><script>document.getElementById('frmTest').submit();</script>");
It is simple: if recv()
returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.
It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
These answers are a bit dated. Therefore I give you:
hash = JSON.parse string
Rails should automagically load the json
module for you, so you don't need to add require 'json'
.
You need to send customerKey and customerSecret to Zend_Service_Twitter
$twitter = new Zend_Service_Twitter(array(
'consumerKey' => $this->consumer_key,
'consumerSecret' => $this->consumer_secret,
'username' => $user->screenName,
'accessToken' => unserialize($user->token)
));
Set python3 as a main version in the terminal: ln -sf python3 /usr/bin/python
Install pip3: apt-get install python3-pip
Update spyder: pip install -U spyder
Enjoy
If you have both remote server then you can follow this:
pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase
It will copy the mentioned table of source Database into same named table of target database, if you already have existing schema.
I have modified one of the answers (by @op1ekun):
123-(apple(?=-)|banana(?=-)|(?!-))-?456
The reason is that the answer from @op1ekun also matches "123-apple456"
, without the hyphen after apple.
I got asked this question recently, and this was my solution:
function fib(n) {_x000D_
const arr = [0,1]; // the inital array, we need something to sum at the very beginning_x000D_
for (let i = 2; i <= n; i++) { // we want the last number, so don't forget the '=' sign_x000D_
let a = arr[i-1]; // previous Number_x000D_
let b = arr[i-2]; // the one before that_x000D_
arr.push(a+b); // push the result_x000D_
}_x000D_
return arr; // if you want the n-th number, just return arr[n] or arr.length - 1_x000D_
}_x000D_
_x000D_
console.log(fib(4));
_x000D_
A recursive solution would be:
// NOTE: This has extremly bad performance => Exponential time complexity 2^n_x000D_
_x000D_
function fib(n) {_x000D_
if (n < 2) {_x000D_
return n;_x000D_
}_x000D_
return fib(n-1) + fib(n-2);_x000D_
}_x000D_
_x000D_
console.log('The n-th fibonacci number: ', fib(6));_x000D_
console.log('The entire fibonacci sequence: ');_x000D_
_x000D_
// Let's see the entire fibonacci sequence_x000D_
for (let i = 0; i <= 6; i++) {_x000D_
console.log(fib(i));_x000D_
}
_x000D_
Like mentioned earlier, the above recursive solution has a very bad impact on performance. Fortunately, there's a solution and it's called memoization:
// LET'S CREATE A MEMO FUNCTION _x000D_
// (and use it on the recursive **fib** function from above):_x000D_
_x000D_
// We want to pass in a function which is going to, eventually, _x000D_
// use this utility function_x000D_
function memo(fn) { _x000D_
const cache = {}; _x000D_
// let's make it reusable, and by that I mean, let's assume that_x000D_
// we don't know the number of arguments that will be eventually passed in _x000D_
return function(...args) {_x000D_
// if we already call this function with the same args?_x000D_
// YES => return them_x000D_
if(cache[args]) { _x000D_
console.log('cached', args[0]);_x000D_
return cache[args];_x000D_
}_x000D_
// otherwise, we want to call our function _x000D_
// (the one using this 'memo' function) and pass in the arguments_x000D_
// w/ the help of 'apply'_x000D_
const res = fn.apply(this, args);_x000D_
cache[args] = res; _x000D_
// we want to store the result, so later if we'll be able to_x000D_
// return that if the args don't change_x000D_
console.log('not cached', args[0]);_x000D_
return res; // don't forget to return the result of it :)_x000D_
}_x000D_
}_x000D_
_x000D_
// Now, let's use the memoized function:_x000D_
// NOTE: Remember the above function has to change in a way_x000D_
// that it calls the memoized function instead of itself_x000D_
_x000D_
function fastFib(n) {_x000D_
// SAME LOGIC AS BEFORE_x000D_
if (n<2) { _x000D_
return n;_x000D_
}_x000D_
// But, here is where the 'magic' happens_x000D_
// Very important: We want to call the instantiated 'fibMemo' function _x000D_
// and NOT 'fastFib', cause then it wouldn't be so fast, right :) _x000D_
return fibMemo(n-1) + fibMemo(n-2);_x000D_
}_x000D_
_x000D_
// DO NOT CALL IT, JUST PASS IT IN_x000D_
const fibMemo = memo(fastFib); _x000D_
_x000D_
// HERE WE WANT TO PASS IN THE ARGUMENT_x000D_
console.log(fibMemo(6));
_x000D_
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
I almost always end up defining n-Tuple classes when I code in Java. For instance:
public class Tuple2<T1,T2> {
private T1 f1;
private T2 f2;
public Tuple2(T1 f1, T2 f2) {
this.f1 = f1; this.f2 = f2;
}
public T1 getF1() {return f1;}
public T2 getF2() {return f2;}
}
I know it's a bit ugly, but it works, and you just have to define your tuple types once. Tuples are something Java really lacks.
EDIT: David Hanak's example is more elegant, as it avoids defining getters and still keeps the object immutable.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
QUESTION was: suppose T john is to be converted john T, how to change in excel?
If text "T john" is in cell A1
=CONCATENATE(RIGHT(A1,LEN(A1)-2)," ",LEFT(A1,1))
and with a nod to the & crowd
=RIGHT(A1,LEN(A1)-2)&" "&LEFT(A1,1)
takes the right part of the string excluding the first 2 characters, adds a space, adds the first character.
A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )
$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"
The answer may be outdated, since there is a name
property on the UploadedFile
class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField
correctly, the access should be as easy as:
if form.is_valid():
form.cleaned_data['my_file'].name
If you're sure you configure your aws correctly, just make sure the user of the project can read from ./aws or just run your project as a root
In python notebooks I often want to filter out 'dangling' numpy.ndarray
's, in particular the ones that are stored in _1
, _2
, etc that were never really meant to stay alive.
I use this code to get a listing of all of them and their size.
Not sure if locals()
or globals()
is better here.
import sys
import numpy
from humanize import naturalsize
for size, name in sorted(
(value.nbytes, name)
for name, value in locals().items()
if isinstance(value, numpy.ndarray)):
print("{:>30}: {:>8}".format(name, naturalsize(size)))
Simply because CPU/ABI says "No system images installed for this target". You need to install system images.
In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device)
In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both.
In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2
As long as I don't install the 4.2 System Image I would have the same problem as you.
UPDATE : This recent article Speeding Up the Android Emaulator on Intel Architectures explains how to use/install correctly the intel system images to speed up the emulator.
EDIT/FOLLOW UP
What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android.
Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image".
Finally, as @SeanJA said, you have to restart eclipse to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so.
A kludgy way is:
$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
function get_first ($foo) {
foreach ($foo as $k=>$v){
return $v;
}
}
print get_first($foo);
After installing php5-gd
apache restart is needed.
You may want to use statement_timestamp(). This give the timestamp when the statement was executed. Whereas NOW()
and CURRENT_TIMESTAMP
give the timestamp when the transaction started.
More details in the manual
I've made basic black launch screens that will make the app scale properly on the iPhone 6 and iPhone 6+:
If you already have a LaunchImage in your .xcassett, open it, switch to the third tab in the right menu in Xcode and tick the iOS 8.0 iPhone images to add them to the existing set. Then drag the images over:
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-
def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
if string[y]==" ":
list_.append(string[x:y])
x = y+1
elif y==len(string)-1:
list_.append(string[x:y+1])
return list_
def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
reversed_list.append(element)
return reversed_list
def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with
space as a separator'''
final_string = str()
for element in list_:
final_string += str(element) + " "
return final_string
#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I
Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!
You can turn the color picker into an application by following the guide here:
http://hints.macworld.com/article.php?story=20060408050920158
From the guide:
Simply fire up AppleScript (Applications -> AppleScript Editor) and enter this text:
choose color
Now, save it as an application (File -> Save As, and set the File Format pop-up to Application), and you're done
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
This is a great place for auto
:
auto now = std::chrono::system_clock::now();
Since you want to traffic at millisecond
precision, it would be good to go ahead and covert to it in the time_point
:
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
now_ms
is a time_point
, based on system_clock
, but with the precision of milliseconds
instead of whatever precision your system_clock
has.
auto epoch = now_ms.time_since_epoch();
epoch
now has type std::chrono::milliseconds
. And this next statement becomes essentially a no-op (simply makes a copy and does not make a conversion):
auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
Here:
long duration = value.count();
In both your and my code, duration
holds the number of milliseconds
since the epoch of system_clock
.
This:
std::chrono::duration<long> dur(duration);
Creates a duration
represented with a long
, and a precision of seconds
. This effectively reinterpret_cast
s the milliseconds
held in value
to seconds
. It is a logic error. The correct code would look like:
std::chrono::milliseconds dur(duration);
This line:
std::chrono::time_point<std::chrono::system_clock> dt(dur);
creates a time_point
based on system_clock
, with the capability of holding a precision to the system_clock
's native precision (typically finer than milliseconds). However the run-time value will correctly reflect that an integral number of milliseconds are held (assuming my correction on the type of dur
).
Even with the correction, this test will (nearly always) fail though:
if (dt != now)
Because dt
holds an integral number of milliseconds
, but now
holds an integral number of ticks finer than a millisecond
(e.g. microseconds
or nanoseconds
). Thus only on the rare chance that system_clock::now()
returned an integral number of milliseconds
would the test pass.
But you can instead:
if (dt != now_ms)
And you will now get your expected result reliably.
Putting it all together:
int main ()
{
auto now = std::chrono::system_clock::now();
auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
std::chrono::milliseconds dur(duration);
std::chrono::time_point<std::chrono::system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Personally I find all the std::chrono
overly verbose and so I would code it as:
int main ()
{
using namespace std::chrono;
auto now = system_clock::now();
auto now_ms = time_point_cast<milliseconds>(now);
auto value = now_ms.time_since_epoch();
long duration = value.count();
milliseconds dur(duration);
time_point<system_clock> dt(dur);
if (dt != now_ms)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
Which will reliably output:
Success.
Finally, I recommend eliminating temporaries to reduce the code converting between time_point
and integral type to a minimum. These conversions are dangerous, and so the less code you write manipulating the bare integral type the better:
int main ()
{
using namespace std::chrono;
// Get current time with precision of milliseconds
auto now = time_point_cast<milliseconds>(system_clock::now());
// sys_milliseconds is type time_point<system_clock, milliseconds>
using sys_milliseconds = decltype(now);
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
sys_milliseconds dt{milliseconds{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
The main danger above is not interpreting integral_duration
as milliseconds
on the way back to a time_point
. One possible way to mitigate that risk is to write:
sys_milliseconds dt{sys_milliseconds::duration{integral_duration}};
This reduces risk down to just making sure you use sys_milliseconds
on the way out, and in the two places on the way back in.
And one more example: Let's say you want to convert to and from an integral which represents whatever duration system_clock
supports (microseconds, 10th of microseconds or nanoseconds). Then you don't have to worry about specifying milliseconds as above. The code simplifies to:
int main ()
{
using namespace std::chrono;
// Get current time with native precision
auto now = system_clock::now();
// Convert time_point to signed integral type
auto integral_duration = now.time_since_epoch().count();
// Convert signed integral type to time_point
system_clock::time_point dt{system_clock::duration{integral_duration}};
// test
if (dt != now)
std::cout << "Failure." << std::endl;
else
std::cout << "Success." << std::endl;
}
This works, but if you run half the conversion (out to integral) on one platform and the other half (in from integral) on another platform, you run the risk that system_clock::duration
will have different precisions for the two conversions.
I saw the above result and query will work fine if you need to check single column value which are duplicate. For example email.
But if you need to check with more columns and would like to check the combination of the result so this query will work fine:
SELECT COUNT(CONCAT(name,email)) AS tot,
name,
email
FROM users
GROUP BY CONCAT(name,email)
HAVING tot>1 (This query will SHOW the USER list which ARE greater THAN 1
AND also COUNT)
I'm not 100% sure this is the only difference, but it is the main difference. It is also recommended to have bi-directional associations by the Hibernate docs:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html
Specifically:
Prefer bidirectional associations: Unidirectional associations are more difficult to query. In a large application, almost all associations must be navigable in both directions in queries.
I personally have a slight problem with this blanket recommendation -- it seems to me there are cases where a child doesn't have any practical reason to know about its parent (e.g., why does an order item need to know about the order it is associated with?), but I do see value in it a reasonable portion of the time as well. And since the bi-directionality doesn't really hurt anything, I don't find it too objectionable to adhere to.
Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.
http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment
I use ExpressMaint.
To backup all user databases I do for example:
C:\>ExpressMaint.exe -S (local)\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\backupdir\ -DS
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan's answer which uses SpEL list {#isbn, #includeUsed}
which is the simplest way to create unique keys.
From Spring Documentation
The default key generation strategy changed with the release of Spring 4.0. Earlier versions of Spring used a key generation strategy that, for multiple key parameters, only considered the hashCode() of parameters and not equals(); this could cause unexpected key collisions (see SPR-10237 for background). The new 'SimpleKeyGenerator' uses a compound key for such scenarios.
Before Spring 4.0
I suggest you to concat the values of the parameters in Spel expression with something like key="#checkWarehouse.toString() + #isbn.toString()")
, I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don't have to provide an int
in your SPEL expression.
As for the hash code with a high collision probability - you can't use it as the key.
Someone in this thread has suggested to use T(java.util.Objects).hash(#p0,#p1, #p2)
but it WILL NOT WORK and this approach is easy to break, for example I've used the data from SPR-9377 :
System.out.println( Objects.hash("someisbn", new Integer(109), new Integer(434)));
System.out.println( Objects.hash("someisbn", new Integer(110), new Integer(403)));
Both lines print -636517714 on my environment.
P.S. Actually in the reference documentation we have
@Cacheable(value="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.
P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.
I'd like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:
[['Gender']]
If it's easy enough for you to access your csv, you can use the excel formula trim()
to clip any spaces of the cells.
or remove it like this
df.columns = df.columns.to_series().apply(lambda x: x.strip())
Also happens when you forget to change the ConnectionString and ask a table that has no idea about the changes you're making locally.
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
$i = 1;
do {
$newTime = strtotime('+'.$i++.' days',$startTime);
echo $newTime;
} while ($newTime < $endTime);
or
$startTime = strtotime('2010-05-01');
$endTime = strtotime('2010-05-10');
// Loop between timestamps, 1 day at a time
do {
$startTime = strtotime('+1 day',$startTime);
echo $startTime;
} while ($startTime < $endTime);
As an empty string is not valid JSON it would be incorrect for JSON.parse('')
to return null
because "null"
is valid JSON. e.g.
JSON.parse("null");
returns null
. It would be a mistake for invalid JSON to also be parsed to null.
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
Which is to say a string that contains two quotes is not the same thing as an empty string.
JSON.parse('""');
will parse correctly, (returning an empty string). But
JSON.parse('');
will not.
Valid minimal JSON strings are
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
Using Set
this.items = new Set();
this.items.add(1);
this.items.add(2);
this.items.add(1);
this.items.add(2);
console.log(Array.from(this.items)); // [1, 2]
Two ways:
Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.
Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.
If portability is important you may not want to depend on a specific shell in your Makefile. Not all environments have bash available.
to be secured, you should execute 3 commands :
cmdkey /generic:"server-address" /user:"username" /pass:"password"
mstsc /v:server-address
cmdkey /delete:server-address
first command to save the credential
second command to open remote desktop
and the third command to delete the credential
all of these commands can be saved in a batch file(bat).
See tables from Python string formatting to select the proper format layout. In your case it's %.2E
.
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
Python 2.x and Python 3.x are different. If you would like to download a newer version of Python 2, you could just download and install the newer version.
If you want to install Python 3, you could install Python 3 separately then change the path for Python 2.x to Python 3.x in Control Panel > All Control Panel Items > System > Advanced System Settings > Environment Variables.
In my case I was getting latin cross sign instead of nbsp, even that a page was correctly encoded into the UTF-8. Nothing of above helped in resolving the issue and I tried all.
In the end changing font for IE (with browser specific css) helped, I was using Helvetica-Nue as a body font changing to the Arial resolved the issue .
You can run brew link openssl
to link it into /usr/local
, if you don't mind the potential problem highlighted in the warning message. Otherwise, you can add the openssl bin directory to your path:
export PATH=$(brew --prefix openssl)/bin:$PATH
If the HTMLElement
is input[type='button']
, input[type='submit']
, etc.
<input id="ShowButton" type="button" value="Show">
<input id="ShowButton" type="submit" value="Show">
change it using this code:
document.querySelector('#ShowButton').value = 'Hide';
If, the HTMLElement
is button[type='button']
, button[type='submit']
, etc:
<button id="ShowButton" type="button">Show</button>
<button id="ShowButton" type="submit">Show</button>
change it using any of these methods,
document.querySelector('#ShowButton').innerHTML = 'Hide';
document.querySelector('#ShowButton').innerText = 'Hide';
document.querySelector('#ShowButton').textContent = 'Hide';
Please note that
input
is an empty tag and cannot have innerHTML
, innerText
or textContent
button
is a container tag and can have innerHTML
, innerText
or textContent
You must use value
instead of .innerHTML
Try this.
document.getElementById("ShowButton").value= "Hide Filter";
And since you are running the button at server
the ID may get mangled in the framework. I so, try
document.getElementById('<%=ShowButton.ClientID %>').value= "Hide Filter";
Another better way to do this is like this.
On markup, change your onclick attribute like this. onclick="showFilterItem(this)"
Now use it like this
function showFilterItem(objButton) {
if (filterstatus == 0) {
filterstatus = 1;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
objButton.value = "Hide Filter";
}
else {
filterstatus = 0;
$find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
objButton.value = "Show filter";
}
}
Correct me if I'm wrong (I'm not), but the offset from UTC changes with daylight saving time. So you should use
tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)
I also believe that the sign should be different:
tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)
I could be wrong, but I don't think so.
I found this post very useful so here is the solution in PHP. I've been using this successfully and just wanted to save another dev some time.
/**
* Get a center latitude,longitude from an array of like geopoints
*
* @param array data 2 dimensional array of latitudes and longitudes
* For Example:
* $data = array
* (
* 0 = > array(45.849382, 76.322333),
* 1 = > array(45.843543, 75.324143),
* 2 = > array(45.765744, 76.543223),
* 3 = > array(45.784234, 74.542335)
* );
*/
function GetCenterFromDegrees($data)
{
if (!is_array($data)) return FALSE;
$num_coords = count($data);
$X = 0.0;
$Y = 0.0;
$Z = 0.0;
foreach ($data as $coord)
{
$lat = $coord[0] * pi() / 180;
$lon = $coord[1] * pi() / 180;
$a = cos($lat) * cos($lon);
$b = cos($lat) * sin($lon);
$c = sin($lat);
$X += $a;
$Y += $b;
$Z += $c;
}
$X /= $num_coords;
$Y /= $num_coords;
$Z /= $num_coords;
$lon = atan2($Y, $X);
$hyp = sqrt($X * $X + $Y * $Y);
$lat = atan2($Z, $hyp);
return array($lat * 180 / pi(), $lon * 180 / pi());
}
The **
operator in Python is really "power;" that is, 2**3 = 8
.
This confusion is because URLs are still 'broken' to this day.
Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.
We can extract detailed information about the "http://www.google.com" URL:
+---------------+-------------------+
| Part | Data |
+---------------+-------------------+
| Scheme | http |
| Host | www.google.com |
+---------------+-------------------+
If we look at a more complex URL such as:
"https://bob:[email protected]:8080/file;p=1?q=2#third"
we can extract the following information:
+-------------------+---------------------+
| Part | Data |
+-------------------+---------------------+
| Scheme | https |
| User | bob |
| Password | bobby |
| Host | www.lunatech.com |
| Port | 8080 |
| Path | /file;p=1 |
| Path parameter | p=1 |
| Query | q=2 |
| Fragment | third |
+-------------------+---------------------+
https://bob:[email protected]:8080/file;p=1?q=2#third
\___/ \_/ \___/ \______________/ \__/\_______/ \_/ \___/
| | | | | | \_/ | |
Scheme User Password Host Port Path | | Fragment
\_____________________________/ | Query
| Path parameter
Authority
The reserved characters are different for each part.
For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.
Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".
This means that the "blue+light blue" string has to be encoded differently in the path and query parts:
"http://example.com/blue+light%20blue?blue%2Blight+blue".
From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.
This boils down to:
You should have %20
before the ?
and +
after.
You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)
What I see in this case is that if I pull the client machine's network cable and make the call, the ajax success handler is called (why, I don't know), and the data parameter is an empty string. So if you factor out the real error handling, you can do something like this:
function handleError(jqXHR, textStatus, errorThrown) {
...
}
jQuery.ajax({
...
success: function(data, textStatus, jqXHR) {
if (data == "") handleError(jqXHR, "clientNetworkError", "");
},
error: handleError
});
The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.
So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.
The current "pipable" variant of this operator is called finalize()
(since RxJS 6). The older and now deprecated "patch" operator was called finally()
(until RxJS 5.5).
I think finalize()
operator is actually correct. You say:
do that logic only when I subscribe, and after the stream has ended
which is not a problem I think. You can have a single source
and use finalize()
before subscribing to it if you want. This way you're not required to always use finalize()
:
let source = new Observable(observer => {
observer.next(1);
observer.error('error message');
observer.next(3);
observer.complete();
}).pipe(
publish(),
);
source.pipe(
finalize(() => console.log('Finally callback')),
).subscribe(
value => console.log('#1 Next:', value),
error => console.log('#1 Error:', error),
() => console.log('#1 Complete')
);
source.subscribe(
value => console.log('#2 Next:', value),
error => console.log('#2 Error:', error),
() => console.log('#2 Complete')
);
source.connect();
This prints to console:
#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Jan 2019: Updated for RxJS 6
The easiest and cleanest way to do this by far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="path/to/your/jquery"><\/script>')</script>
There is no issue in passing back a struct. It will be passed by value
But, what if the struct contains any member which has a address of a local variable
struct emp {
int id;
char *name;
};
struct emp get() {
char *name = "John";
struct emp e1 = {100, name};
return (e1);
}
int main() {
struct emp e2 = get();
printf("%s\n", e2.name);
}
Now, here e1.name
contains a memory address local to the function get()
.
Once get()
returns, the local address for name would have been freed up.
SO, in the caller if we try to access that address, it may cause segmentation fault, as we are trying a freed address. That is bad..
Where as the e1.id
will be perfectly valid as its value will be copied to e2.id
So, we should always try to avoid returning local memory addresses of a function.
Anything malloced can be returned as and when wanted
For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:
echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'
In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...
Cheers, Fernando
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.
You try to instantiate an object of the Friends
class like this:
Friends f = new Friends(friendsName, friendsAge);
The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);
Regarding WMI and Registry:
There are three WMI event classes concerning registry:
But you need to be aware of these limitations:
With RegistryTreeChangeEvent and RegistryKeyChangeEvent there is no way of directly telling which values or keys actually changed. To do this, you would need to save the registry state before the event and compare it to the state after the event.
You can't use these classes with HKEY_CLASSES_ROOT or HKEY_CURRENT_USER hives. You can overcome this by creating a WMI class to represent the registry key to monitor:
Defining a Registry Class With Qualifiers
and use it with __InstanceOperationEvent derived classes.
So using WMI to monitor the Registry is possible, but less then perfect. The advantage is that it is possible to monitor the changes in 'real time'. Another advantage could be WMI permanent event subscription:
a method to monitor the Registry 'at all times', ie. event if your application is not running.
Assuming that all viewControllers that you present modally are wrapped inside a new navigationController (which you should always do anyway), you can add this property to your VC.
private var wasPushed: Bool {
guard let vc = navigationController?.viewControllers.first where vc == self else {
return true
}
return false
}
Your solutions don't seem to be working for me, I have the following code. How to put link into the last two divs.
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<style>
/* Import */
@import url(https://fonts.googleapis.com/css?family=Quicksand:300,400);
* {
font-family: "Quicksand", sans-serif;
font-weight: bold;
text-align: center;
text-transform: uppercase;
-webkit-transition: all 0.25s ease;
-moz-transition: all 0.25s ease;
-ms-transition: all 0.25s ease;
-o-transition: all 0.025s ease;
}
/* Colors */
#ora {
background-color: #e67e22;
}
#red {
background-color: #e74c3c;
}
#orab {
background-color: white;
border: 5px solid #e67e22;
}
#redb {
background-color: white;
border: 5px solid #e74c3c;
}
/* End of Colors */
.B {
width: 240px;
height: 55px;
margin: auto;
line-height: 45px;
display: inline-block;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
}
#orab:hover {
background-color: #e67e22;
}
#redb:hover {
background-color: #e74c3c;
}
#whib:hover {
background-color: #ecf0f1;
}
/* End of Border
.invert:hover {
-webkit-filter: invert(1);
-moz-filter: invert(1);
-ms-filter: invert(1);
-o-filter: invert(1);
}
</style>
<h1>Flat and Modern Buttons</h1>
<h2>Border Stylin'</h2>
<div class="B bo" id="orab">See the movies list</div></a>
<div class="B bo" id="redb">Avail a free rental day</div>
</html>
There two alternate ways to set accept header, which are as below:
1) setRequestHeader('Accept','application/json; charset=utf-8');
2) $.ajax({
dataType: ($.browser.msie) ? "text" : "json",
accepts: {
text: "application/json"
}
});
Try this:
SELECT user.userID, edge.TailUser, edge.Weight
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043
OR
AND edge.HeadUser=5043
instead of WHERE clausule.
If SESSION_START_DATE_TIME is of type TIMESTAMP you may want to try using the SQL function TO_TIMESTAMP. Here is an example:
SQL> CREATE TABLE t (ts TIMESTAMP);
Table created.
SQL> INSERT INTO t
2 VALUES (
3 TO_TIMESTAMP (
4 '1/12/2012 5:03:27.221008 PM'
5 ,'mm/dd/yyyy HH:MI:SS.FF AM'
6 )
7 );
1 row created.
SQL> SELECT *
2 FROM t
3 WHERE ts =
4 TO_TIMESTAMP (
5 '1/12/2012 5:03:27.221008 PM'
6 ,'mm/dd/yyyy HH:MI:SS.FF AM'
7 );
TS
-------------------------------------------------
12-JAN-12 05.03.27.221008 PM
A very nice explanation is here-
A Normal Payload- // House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 20 } PUT For Updated- // PUT request payload to update windows of House on plot 1 { address: 'plot 1', owner: 'segun', type: 'duplex', color: 'green', rooms: '5', kitchens: '1', windows: 21 } Note: In above payload we are trying to update windows from 20 to 21.
Now see the PATH payload- // Patch request payload to update windows on the House { windows: 21 }
Since PATCH is not idempotent, failed requests are not automatically re-attempted on the network. Also, if a PATCH request is made to a non-existent url e.g attempting to replace the front door of a non-existent building, it should simply fail without creating a new resource unlike PUT, which would create a new one using the payload. Come to think of it, it’ll be odd having a lone door at a house address.
send requtest and get response with kibana,kibana is can autocomplete elastic query builder and have more tools
GET /_cat/indices
kibana dev tools
http://localhost:5601/app/kibana#/dev_tools/console
Here's an alternative way to do the same call. And your type should always be in CAPS, eg. type:"GET" / type:"POST".
$.ajax({
url:/ControllerName/ActionName,
data: "id=" + Id + "¶m2=" + param2,
type: "GET",
success: function(data){
// code here
},
error: function(passParams){
// code here
}
});
Another alternative will be to use the data-ajax on a link.
<a href="/ControllerName/ActionName/" data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#_content">Click Me!</a>
Assuming u had a div with the I'd _content, this will call the action and replace the content inside that div with the data returned from that action.
<div id="_content"></div>
Not really a direct answer to ur question but its some info u should be aware of ;).
//C# class
public class DashBoardViewModel
{
public int Id { get; set;}
public decimal TotalSales { get; set;}
public string Url { get; set;}
public string MyDate{ get; set;}
}
//JavaScript file
//Create dashboard.js file
$(document).ready(function () {
// See the html on the View below
$('.dashboardUrl').on('click', function(){
var url = $(this).attr("href");
});
$("#inpDateCompleted").change(function () {
// Construct your view model to send to the controller
// Pass viewModel to ajax function
// Date
var myDate = $('.myDate').val();
// IF YOU USE @Html.EditorFor(), the myDate is as below
var myDate = $('#MyDate').val();
var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: '/Dashboard/IndexPartial',
data: viewModel ,
success: function (data, textStatus, jqXHR) {
//Do Stuff
$("#DailyInvoiceItems").html(data.Id);
},
error: function (jqXHR, textStatus, errorThrown) {
//Do Stuff or Nothing
}
});
});
});
//ASP.NET 5 MVC 6 Controller
public class DashboardController {
[HttpGet]
public IActionResult IndexPartial(DashBoardViewModel viewModel )
{
// Do stuff with my model
var model = new DashBoardViewModel { Id = 23 /* Some more results here*/ };
return Json(model);
}
}
// MVC View
// Include jQuerylibrary
// Include dashboard.js
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically
<div>
<a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
<input class="myDate" type="text"/>
//OR
@Html.EditorFor(model => model.MyDate)
</div>
Any one on windows 10 Pro , this is for you guys --
Paste below code-
RD /S /Q "%WinDir%\System32\GroupPolicyUsers"
RD /S /Q "%WinDir%\System32\GroupPolicy"
gpupdate /force
After few seconds you will see this -
User Policy update has completed successfully.
Computer Policy update has completed successfully.
Now you can change your search engine to whatever you want.
Thank you
Function is not a property/method from range.
If you want to sum values then use the following:
Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))
EDIT:
if you want the formula then use as follows:
Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"
'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).
In case you are allways going to use the same range address then you can use as Rory sugested:
Range("A1").Formula ="=Sum(A2:B3)"
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
It can be done using classes from the official bootstrap 3.x version, without any custom css.
Use input-group-addon
before the input tag, inside of input-group
then use any of the glyphicons, here is the code
<form>
<div class="form-group">
<div class="col-xs-5">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon glyphicon-user"></span></span>
<input class="form-control left-border-none" placeholder="User Name" type="text" name="username">
</div>
</div>
</div>
</form>
Here is the output
To customise it further add a couple of lines of custom css to your own custom.css file (adjust padding if needed)
.transparent {
background-color: transparent !important;
box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
}
.left-border-none {
border-left:none !important;
box-shadow: inset 0px 1px 0 rgba(0,0,0,.075);
}
By making the background of the input-group-addon
transparent and making the left gradient of the input tag to zero the input will have a seamless appearance. Here is the customised output
Here is a jsbin example
This will solve the custom css problems of overlapping with labels, alignment while using input-lg
and focus on tab issue.
Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.
StringUtils.equals(-, -) :
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
StringUtils.equalsIgnoreCase(-, -) :
StringUtils.equalsIgnoreCase(null, null) = true
StringUtils.equalsIgnoreCase(null, "abc") = false
StringUtils.equalsIgnoreCase("xyz", null) = false
StringUtils.equalsIgnoreCase("xyz", "xyz") = true
StringUtils.equalsIgnoreCase("xyz", "XYZ") = true
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.The best way to describe a table such as a column, type, modifiers of columns, etc.
\d+ tablename or \d tablename
Both of the above two answers work for me with a similar problem.
However, the body {-webkit-transform} approach causes all elements on the page to effectively be rendered in 3D. This isn't the worst thing, but it slightly changes the rendering of text and other CSS-styled elements.
It may be an effect you want. It may be useful if you're doing a lot of transform on your page. Otherwise, -webkit-backface-visibility:hidden on the element your transforming is the least invasive option.
By using the org.apache.commons.io package, it gave more performance, especially in legacy code which uses Java 6 and below.
Java 7 has a better API with fewer exceptions handling and more useful methods:
LineIterator lineIterator = null;
try {
lineIterator = FileUtils.lineIterator(new File("/home/username/m.log"), "windows-1256"); // The second parameter is optionnal
while (lineIterator.hasNext()) {
String currentLine = lineIterator.next();
// Some operation
}
}
finally {
LineIterator.closeQuietly(lineIterator);
}
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
background-image:url('image/img2.jpg');
background-repeat:repeat-x;
Use some image for internal image and use this.
Put this in the first line of your server.js (or whatever contains your main Node.js app):
require('events').EventEmitter.prototype._maxListeners = 0;
and the error goes away :)
You are recursively defining x
with x
. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.
You must say I am twice John's age or any other variable but yourself.
computed variables are always dependent on another variable.
The rule of the thumb is never access the property itself from within the getter ie get
. Because that would trigger another get
which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!
struct Person{
var name: String{
get{
print(name) // DON'T do this!!!!
return "as"
}
set{
}
}
}
let p1 = Person()
As that would give the following warning:
Attempting to access 'name' from within it's own getter.
The error looks vague like this:
As an alternative you might want to use didSet
. With didSet
you'll get a hold to the value that is was set before and just got set to. For more see this answer.
This might be helpful
http://opencvuser.blogspot.in/2011/08/creating-haar-cascade-classifier-aka.html
Sorting with multiple fields in Java8
package com.java8.chapter1;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;
public class Example1 {
public static void main(String[] args) {
List<Employee> empList = getEmpList();
// Before Java 8
empList.sort(new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
int res = o1.getDesignation().compareTo(o2.getDesignation());
if (res == 0) {
return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
} else {
return res;
}
}
});
for (Employee emp : empList) {
System.out.println(emp);
}
System.out.println("---------------------------------------------------------------------------");
// In Java 8
empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
empList.stream().forEach(System.out::println);
}
private static List<Employee> getEmpList() {
return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
new Employee("Jaishree", "Opearations HR", 350000));
}
}
class Employee {
private String fullName;
private String designation;
private double salary;
public Employee(String fullName, String designation, double salary) {
super();
this.fullName = fullName;
this.designation = designation;
this.salary = salary;
}
public String getFullName() {
return fullName;
}
public String getDesignation() {
return designation;
}
public double getSalary() {
return salary;
}
@Override
public String toString() {
return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
}
}
More general sorted, where the key
keyword defines the sorting method, minus before numerical type indicates descending:
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> sorted(x.items(), key=lambda k: -k[1]) # Ascending
[('c', 7), ('a', 5), ('b', 3)]
Perhaps the "replace" module (www.npmjs.org/package/replace) also would work for you. It would not require you to read and then write the file.
Adapted from the documentation:
// install:
npm install replace
// require:
var replace = require("replace");
// use:
replace({
regex: "string to be replaced",
replacement: "replacement string",
paths: ['path/to/your/file'],
recursive: true,
silent: true,
});
A regex splitting on word boundary \b
isn't the best solution for this:
var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ");
or as a jQuery mixin:
$.fn.removeClassPrefix = function(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ");
});
return this;
};
put this line at the end of the body. May be the DOM is not ready yet at the moment this line is read by compiler.
<script type="text/javascript" src="script.js"></script>"
What about using .splitlines()
?
for line in textData.splitlines():
print(line)
lineResult = libLAPFF.parseLine(line)
Type in the terminal as follows:
mysql.server start
Use a regex like ^\d
Using control-z suspends the process (see the output from stty -a
which lists the key stroke under susp
). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.
If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg
).
Note that all key combinations are subject to change via the stty
command or equivalents; the defaults may vary from system to system.
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Instead of appending element you can just do.
document.getElementById("p").textContent += " this has just been added";
document.getElementById("p").textContent += " this has just been added";
_x000D_
<p id ="p">This is some text</p>
_x000D_
And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):
(function () {
var cookies = document.cookie.split("; ");
for (var c = 0; c < cookies.length; c++) {
var d = window.location.hostname.split(".");
while (d.length > 0) {
var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
var p = location.pathname.split('/');
document.cookie = cookieBase + '/';
while (p.length > 0) {
document.cookie = cookieBase + p.join('/');
p.pop();
};
d.shift();
}
}
})();
In OOP, you can't cast an instance of a parent class into a child class. You can only cast a child instance into a parent that it inherits from.
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
Would the use of <caption>
be allowed?
<ul>
<caption> Title of List </caption>
<li> Item 1 </li>
<li> Item 2 </li>
</ul>
There is an argument for keeping it simple and stupid if the date picker comes from a simple html5 input and the goal is to test whatever events were added to the test. Consider for example:
<input type=date name=mydate />
and one wants to set a test where 'mydate' is hardcoded to 02/22/2017, a solution with python is to use the following code, which is simple enough to debug to observe what it does:
def setdate(elem_name, date_str):
elem = driver.find_element_by_name('mydate')
elem.click()
elem.send_keys(Keys.ARROW_LEFT)
elem.send_keys(Keys.ARROW_LEFT)
elem.send_keys(date_str)
setdate('mydate'', '02222017')
Yes:
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);
First, the code creates a new layout params by specifying the height and width. The addRule
method adds the equivalent of the xml properly android:layout_below
. Then you just call View#setLayoutParams
on the view you want to have those params.
I usually attach a class to the element then check if the class exist like this:
let element = document.getElementsById("someElement");
if(!element.classList.contains('attached-listener'))
element.addEventListener("click", this.itemClicked);
element.classList.add('attached-listener');
You'll probably want to try textContent
instead of innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
For example, considering the following markup:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
Try this:
<div class="row">
<div class="alert alert-info" style="min-height:100px;">
<div class="col-xs-9">
<a href="#" class="alert-link">Summary:Its some
description.......testtesttest</a>
</div>
<div class="col-xs-3">
<button type="button" class="btn btn-primary btn-lg">Large button</button>
</div>
</div>
</div>
Demo:
I think Android does not support Java 8. Officially android need java 6 as mentioned at the below:
https://developer.android.com/sdk/installing/installing-adt.html
Here I'm providing you a good link, hope those will clear this question :
Unfortunately none of the suggestions helped me, but after some more googling this
pip install aenum
solved it for me
i wanted to mention Jailbreak specifically (GitHub):
Jailbreak
Jailbreak is a tool for exporting certificates marked as non-exportable from the Windows certificate store. This can help when you need to extract certificates for backup or testing. You must have full access to the private key on the filesystem in order for jailbreak to work.
Prerequisites: Win32
For debugging purposes, you can use the DLL file. You can run it using dotnet ConsoleApp2.dll
. If you want to generate an EXE file, you have to generate a self-contained application.
To generate a self-contained application (EXE in Windows), you must specify the target runtime (which is specific to the operating system you target).
Pre-.NET Core 2.0 only: First, add the runtime identifier of the target runtimes in the .csproj file (list of supported RIDs):
<PropertyGroup>
<RuntimeIdentifiers>win10-x64;ubuntu.16.10-x64</RuntimeIdentifiers>
</PropertyGroup>
The above step is no longer required starting with .NET Core 2.0.
Then, set the desired runtime when you publish your application:
dotnet publish -c Release -r win10-x64
dotnet publish -c Release -r ubuntu.16.10-x64
Try:
#your_div_id {
width: 855px;
margin:0 auto;
text-align: center;
}
document.querySelectorAll(`[data-slide='${current}']`);
I know the question is about JQuery, but readers may want a pure JS method.
Modified code of Tapas's answer:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
I'd suggest doing this with a combination of
overflow-y: hidden;
scrolling="no"
(for HTML4)seamless="seamless"
(for HTML5)* The seamless
attribute has been removed from the standard, and no browsers support it.
.foo {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
overflow-y: hidden;_x000D_
}
_x000D_
<iframe src="https://bing.com" _x000D_
class="foo" _x000D_
scrolling="no" >_x000D_
</iframe>
_x000D_
Keep in mind that TCP usually keeps multiple messages on wire. If you want to implement this in UDP you'll have quite a lot of work if you want to do it reliably. Your solution is either going to be less reliable, less fast or an incredible amount of work. There are valid applications of UDP, but if you're asking this question yours probably is not.
How are you generating your data?
See how the output shows that your data is of 'object' type? the groupby operations specifically check whether each column is a numeric dtype first.
In [31]: data
Out[31]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2004-01-01 00:00:00 to 2010-12-31 00:00:00
Freq: <1 DateOffset>
Columns: 360 entries, -89.75 to 89.75
dtypes: object(360)
look ?
Did you initialize an empty DataFrame first and then filled it? If so that's probably why it changed with the new version as before 0.9 empty DataFrames were initialized to float type but now they are of object type. If so you can change the initialization to DataFrame(dtype=float)
.
You can also call frame.astype(float)
I had a similar issue and what I did is: Create a array of Buttons
Button buttons[] = new Button[10];
Then to implement on click listener and reference xml id's I used a loop like this
for (int i = 0; i < 10; i++) {
String buttonID = "button" + i;
int resID = getResources().getIdentifier(buttonID, "id",
"your package name here");
buttons[i] = (Button) findViewById(resID);
buttons[i].setOnClickListener(this);
}
But calling them up remains same as in Prag's answer point 4. PS- If anybody has a better method to call up all the button's onClick, please do comment.
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
This happened to me when I installed Intellij IDEA 2017, go to menu Preferences -> Build, Execution, Deployment -> Debugger and disable the option: "Force Classic VM for JDK 1.3.x and earlier". This works to me.
List your current SSH keys:
ls -l ~/.ssh
Generate a new SSH key:
ssh-keygen -t ed25519 -C "[email protected]"
where you should replace [email protected]
with your GitHub email
address.
When prompted to Enter a file in which to save the key
, press
Enter.
Upon Enter passphrase (empty for no passphrase)
- just press
Enter (for an empty passphrase).
List the your SSH keys again:
ls -l ~/.ssh
The files id_ed25519
and id_ed25519.pub
should now have been added.
Start the ssh-agent in the background:
eval $(ssh-agent -s)
Add your SSH private key to the ssh-agent:
ssh-add ~/.ssh/id_ed25519
Next output the public key to the terminal screen:
cat ~/.ssh/id_ed25519.pub
Copy the output to the clipboard
(Ctrl + Insert).
Go to https://github.com/<your-github-username>
and sign in with your
username and password.
Click your GitHub avatar in the upper-right corner, and then Settings.
In the left pane click SSH and GPG keys.
Click the green-colored button New SSH key
and paste the public SSH key into the textarea labeled Key.
Use a descriptive Title that tells from what computer you will
use this SSH key. Click Add SSH key.
If your current local repository was created with http and username,
it needs to be recreated it so as to become SSH compatible.
First check to make sure that you have a clean working tree
so that you don't lose any work:
git status
Then cd ..
to the parent directory and rm -fr <name-of-your-repo>
.
Finally clone a fresh copy that uses SSH instead of username/password:
git clone [email protected]:[your-github-username]/[repository-name].git
References:
https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/adding-a-new-ssh-key-to-your-github-account
Everyone seems to focus on the host part of your questions. Ports are used to be able to run several servers (for example for different purposes such as file sharing, web serving, printing, etc) from the same machine (one single IP address).
I'm guessing you've taken a look at mod_perl?
Have you tried the following tutorial?
EDIT: In relation to your posting - perhaps you could include a sample of the code inside your .cgi
file. Perhaps even the first few lines?
A bit late but this is what I'm doing with journald
. It's pretty powerful.
You need to be running your docker containers on an OS with systemd-journald
.
docker run -d --log-driver=journald myapp
This pipes the whole lot into host's journald which takes care of stuff like log pruning, storage format etc and gives you some cool options for viewing them:
journalctl CONTAINER_NAME=myapp -f
which will feed it to your console as it is logged,
journalctl CONTAINER_NAME=myapp > output.log
which gives you the whole lot in a file to take away, or
journalctl CONTAINER_NAME=myapp --since=17:45
Plus you can still see the logs via docker logs ....
if that's your preference.
No more > my.log
or -v "/apps/myapp/logs:/logs"
etc
What worked for me, On Windows 2012 Server R2:
Thanks goes to "Aaron D"
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
svnbackup over at Google Code, a .NET console application.
I had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/
For the record, here is an example using a sqlite database:
import pandas as pd
import sqlite3
with sqlite3.connect("whatever.sqlite") as con:
sql = "SELECT * FROM table_name"
df = pd.read_sql_query(sql, con)
print df.shape
Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.
I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.
<div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
<div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>
function setMobDeskCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value + "; path=/";
window.location.reload();
}
$(function() {
$(".make_desktop").click(function() {
setMobDeskCookie('deskmob', 1, 3650);
});
$(".make_responsive").click(function() {
setMobDeskCookie('deskmob', 0, 3650);
});
});`enter code here`
i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me
and i also created non-responsive.css that forces the grid to maintain the large screen version
in case u select mobile i would load / echo
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />
in case you select desktop i would load /echo
<meta name="viewport" content="width=1024">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
<!-- Main CSS -->
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />
the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files
please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).In Pythons <= 3.4 you can, as others suggested, use list(range(10))
in order to make a list out of a range (In general, any iterable).
Another alternative, introduced in Python 3.5
with its unpacking generalizations, is by using *
in a list literal []
:
>>> r = range(10)
>>> l = [*r]
>>> print(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Though this is equivalent to list(r)
, it's literal syntax and the fact that no function call is involved does let it execute faster. It's also less characters, if you need to code golf :-)
After researching a lot on this laravel validation topic including unique column, finally got the best approach. Please have a look
In your controller
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function saveUser(Request $request){
$validator = Validator::make($request->all(),User::rules($request->get('id')),User::$messages);
if($validator->fails()){
return redirect()->back()->withErrors($validator)->withInput();
}
}
}
saveUser
method can be called for add/update user record.
In you model
class User extends Model
{
public static function rules($id = null)
{
return [
'email_address' => 'required|email|unique:users,email_address,'.$id,
'first_name' => "required",
'last_name' => "required",
'password' => "required|min:6|same:password_confirm",
'password_confirm' => "required:min:6|same:password",
'password_current' => "required:min:6"
];
}
public static $messages = [
'email_address.required' => 'Please enter email!',
'email_address.email' => 'Invalid email!',
'email_address.unique' => 'Email already exist!',
...
];
}
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].
No need for mysqladmin:
just use mysql command line
mysql -u [username] -p[password] -e 'drop database db-name;'
This will send the drop command although I wouldn't pass the password this way as it'll be exposed to other users of the system via ps aux
Use
export LD_LIBRARY_PATH="/path/to/library/"
in your .bashrc otherwise, it'll only be available to bash and not any programs you start.
Try -R/path/to/library/
flag when you're linking, it'll make the program look in that directory and you won't need to set any environment variables.
EDIT: Looks like -R
is Solaris only, and you're on Linux.
An alternate way would be to add the path to /etc/ld.so.conf
and run ldconfig
. Note that this is a global change that will apply to all dynamically linked binaries.
If you have no Medium security level, then you should add your application to the Exception Site List (Java Control Panel ? Security tab).
Go to Control Panel ? Java Control Panel ? Security tab and press the Edit Site List... button.
Press the Add button, insert your path and press Enter.
Press Continue on the security warning that appears.
Open the applet again and don't forget to press Run on the pop-up window.
There is no such feature as a multi-line comment. #
is the only way to comment a single line of code.
Many of you answered ''' a comment ''' this as their solution.
It seems to work, but internally '''
in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #
.
mvn install "-Dsomeproperty=propety value"
In pom.xml:
<properties>
<someproperty> ${someproperty} </someproperty>
</properties>
Referred from this question
Why not just change the content of the modal body?
window.switchContent = function(myFile){
$('.modal-body').load(myFile);
};
In the modal just put a link or a button
<a href="Javascript: switchContent('myFile.html'); return false;">
click here to load another file</a>
If you just want to switch beetween 2 modals:
window.switchModal = function(){
$('#myModal-1').modal('hide');
setTimeout(function(){ $('#myModal-2').modal(); }, 500);
// the setTimeout avoid all problems with scrollbars
};
In the modal just put a link or a button
<a href="Javascript: switchModal(); return false;">
click here to switch to the second modal</a>
try
<select onchange="location=this.value">_x000D_
<option value="unit_01.htm">Unit 1</option>_x000D_
<option value="#5.2" selected >Bookmark 2</option>_x000D_
</select>
_x000D_
You need to annotate your Customer class with @Named or @Model annotation:
package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
private String email;
private String password;
}
or create/modify beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
Use format
method with a specific pattern to extract the time.
Working example
var myDate = "2017-08-30T14:24:03";_x000D_
console.log(moment(myDate).format("HH:mm")); // 24 hour format_x000D_
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM_x000D_
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
Some old school array sorting. Of course this only sorts single dimension arrays.
'C:\DropBox\Automation\Libraries\Array.vbs
Option Explicit
Public Function Array_AdvancedBubbleSort(ByRef rarr_ArrayToSort(), ByVal rstr_SortOrder)
' ==================================================================================
' Date : 12/09/1999
' Author : Christopher J. Scharer (CJS)
' Description : Creates a sorted Array from a one dimensional array
' in Ascending (default) or Descending order based on the rstr_SortOrder.
' Variables :
' rarr_ArrayToSort() The array to sort and return.
' rstr_SortOrder The order to sort in, default ascending or D for descending.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_AdvancedBubbleSort"
Dim bln_Sorted
Dim lng_Loop_01
Dim str_SortOrder
Dim str_Temp
bln_Sorted = False
str_SortOrder = Left(UCase(rstr_SortOrder), 1) 'We only need to know if the sort order is A(SENC) or D(ESEND)...and for that matter we really only need to know if it's D because we are defaulting to Ascending.
Do While (bln_Sorted = False)
bln_Sorted = True
str_Temp = ""
If (str_SortOrder = "D") Then
'Sort in descending order.
For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)
If (rarr_ArrayToSort(lng_Loop_01) < rarr_ArrayToSort(lng_Loop_01 + 1)) Then
bln_Sorted = False
str_Temp = rarr_ArrayToSort(lng_Loop_01)
rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)
rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp
End If
If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) > rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then
bln_Sorted = False
str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))
rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)
rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp
End If
Next
Else
'Default to Ascending.
For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)
If (rarr_ArrayToSort(lng_Loop_01) > rarr_ArrayToSort(lng_Loop_01 + 1)) Then
bln_Sorted = False
str_Temp = rarr_ArrayToSort(lng_Loop_01)
rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)
rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp
End If
If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) < rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then
bln_Sorted = False
str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))
rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)
rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp
End If
Next
End If
Loop
End Function
Public Function Array_BubbleSort(ByRef rarr_ArrayToSort())
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_BubbleSort"
Dim lng_Loop_01
Dim lng_Loop_02
Dim var_Temp
For lng_Loop_01 = (UBound(rarr_ArrayToSort) - 1) To 0 Step -1
For lng_Loop_02 = 0 To lng_Loop_01
If rarr_ArrayToSort(lng_Loop_02) > rarr_ArrayToSort(lng_Loop_02 + 1) Then
var_Temp = rarr_ArrayToSort(lng_Loop_02 + 1)
rarr_ArrayToSort(lng_Loop_02 + 1) = rarr_ArrayToSort(lng_Loop_02)
rarr_ArrayToSort(lng_Loop_02) = var_Temp
End If
Next
Next
End Function
Public Function Array_GetDimensions(ByVal rarr_Array)
Const const_FUNCTION_NAME = "Array_GetDimensions"
Dim int_Dimensions
Dim int_Result
Dim str_Dimensions
int_Result = 0
If IsArray(rarr_Array) Then
On Error Resume Next
Do
int_Dimensions = -2
int_Dimensions = UBound(rarr_Array, int_Result + 1)
If int_Dimensions > -2 Then
int_Result = int_Result + 1
If int_Result = 1 Then
str_Dimensions = str_Dimensions & int_Dimensions
Else
str_Dimensions = str_Dimensions & ":" & int_Dimensions
End If
End If
Loop Until int_Dimensions = -2
On Error GoTo 0
End If
Array_GetDimensions = int_Result ' & ";" & str_Dimensions
End Function
Public Function Array_GetUniqueCombinations(ByVal rarr_Fields, ByRef robj_Combinations)
Const const_FUNCTION_NAME = "Array_GetUniqueCombinations"
Dim int_Element
Dim str_Combination
On Error Resume Next
Array_GetUniqueCombinations = CBool(False)
For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)
str_Combination = rarr_Fields(int_Element)
Call robj_Combinations.Add(robj_Combinations.Count & ":" & str_Combination, 0)
' Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)
Next 'int_Element
For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)
Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)
Next 'int_Element
Array_GetUniqueCombinations = CBool(True)
End Function 'Array_GetUniqueCombinations
Public Function Array_GetUniqueCombinationsSub(ByVal rarr_Fields, ByRef robj_Combinations, ByRef rint_LBound)
Const const_FUNCTION_NAME = "Array_GetUniqueCombinationsSub"
Dim int_Element
Dim str_Combination
On Error Resume Next
Array_GetUniqueCombinationsSub = CBool(False)
str_Combination = rarr_Fields(rint_LBound)
For int_Element = (rint_LBound + 1) To UBound(rarr_Fields)
str_Combination = str_Combination & "," & rarr_Fields(int_Element)
Call robj_Combinations.Add(robj_Combinations.Count & ":" & str_Combination, str_Combination)
Next 'int_Element
Array_GetUniqueCombinationsSub = CBool(True)
End Function 'Array_GetUniqueCombinationsSub
Public Function Array_HeapSort(ByRef rarr_ArrayToSort())
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_HeapSort"
Dim lng_Loop_01
Dim var_Temp
Dim arr_Size
arr_Size = UBound(rarr_ArrayToSort) + 1
For lng_Loop_01 = ((arr_Size / 2) - 1) To 0 Step -1
Call Array_SiftDown(rarr_ArrayToSort, lng_Loop_01, arr_Size)
Next
For lng_Loop_01 = (arr_Size - 1) To 1 Step -1
var_Temp = rarr_ArrayToSort(0)
rarr_ArrayToSort(0) = rarr_ArrayToSort(lng_Loop_01)
rarr_ArrayToSort(lng_Loop_01) = var_Temp
Call Array_SiftDown(rarr_ArrayToSort, 0, (lng_Loop_01 - 1))
Next
End Function
Public Function Array_InsertionSort(ByRef rarr_ArrayToSort())
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_InsertionSort"
Dim lng_ElementCount
Dim lng_Loop_01
Dim lng_Loop_02
Dim lng_Index
lng_ElementCount = UBound(rarr_ArrayToSort) + 1
For lng_Loop_01 = 1 To (lng_ElementCount - 1)
lng_Index = rarr_ArrayToSort(lng_Loop_01)
lng_Loop_02 = lng_Loop_01
Do While lng_Loop_02 > 0
If rarr_ArrayToSort(lng_Loop_02 - 1) > lng_Index Then
rarr_ArrayToSort(lng_Loop_02) = rarr_ArrayToSort(lng_Loop_02 - 1)
lng_Loop_02 = (lng_Loop_02 - 1)
End If
Loop
rarr_ArrayToSort(lng_Loop_02) = lng_Index
Next
End Function
Private Function Array_Merge(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_Left, ByVal rlng_MiddleIndex, ByVal rlng_Right)
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Merges an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_Merge"
Dim lng_Loop_01
Dim lng_LeftEnd
Dim lng_ElementCount
Dim lng_TempPos
lng_LeftEnd = (rlng_MiddleIndex - 1)
lng_TempPos = rlng_Left
lng_ElementCount = (rlng_Right - rlng_Left + 1)
Do While (rlng_Left <= lng_LeftEnd) _
And (rlng_MiddleIndex <= rlng_Right)
If rarr_ArrayToSort(rlng_Left) <= rarr_ArrayToSort(rlng_MiddleIndex) Then
rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)
lng_TempPos = (lng_TempPos + 1)
rlng_Left = (rlng_Left + 1)
Else
rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)
lng_TempPos = (lng_TempPos + 1)
rlng_MiddleIndex = (rlng_MiddleIndex + 1)
End If
Loop
Do While rlng_Left <= lng_LeftEnd
rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)
rlng_Left = (rlng_Left + 1)
lng_TempPos = (lng_TempPos + 1)
Loop
Do While rlng_MiddleIndex <= rlng_Right
rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)
rlng_MiddleIndex = (rlng_MiddleIndex + 1)
lng_TempPos = (lng_TempPos + 1)
Loop
For lng_Loop_01 = 0 To (lng_ElementCount - 1)
rarr_ArrayToSort(rlng_Right) = rarr_ArrayTemp(rlng_Right)
rlng_Right = (rlng_Right - 1)
Next
End Function
Public Function Array_MergeSort(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_FirstIndex, ByVal rlng_LastIndex)
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' Note :The rarr_ArrayTemp array that is passed in has to be dimensionalized to the same size
' as the rarr_ArrayToSort array that is passed in prior to calling the function.
' Also the rlng_FirstIndex variable should be the value of the LBound(rarr_ArrayToSort)
' and the rlng_LastIndex variable should be the value of the UBound(rarr_ArrayToSort)
' ==================================================================================
Const const_FUNCTION_NAME = "Array_MergeSort"
Dim lng_MiddleIndex
If rlng_LastIndex > rlng_FirstIndex Then
' Recursively sort the two halves of the list.
lng_MiddleIndex = ((rlng_FirstIndex + rlng_LastIndex) / 2)
Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex)
Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, lng_MiddleIndex + 1, rlng_LastIndex)
' Merge the results.
Call Array_Merge(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex + 1, rlng_LastIndex)
End If
End Function
Public Function Array_Push(ByRef rarr_Array, ByVal rstr_Value, ByVal rstr_Delimiter)
Const const_FUNCTION_NAME = "Array_Push"
Dim int_Loop
Dim str_Array_01
Dim str_Array_02
'If there is no delimiter passed in then set the default delimiter equal to a comma.
If rstr_Delimiter = "" Then
rstr_Delimiter = ","
End If
'Check to see if the rarr_Array is actually an Array.
If IsArray(rarr_Array) = True Then
'Verify that the rarr_Array variable is only a one dimensional array.
If Array_GetDimensions(rarr_Array) <> 1 Then
Array_Push = "ERR, the rarr_Array variable passed in was not a one dimensional array."
Exit Function
End If
If IsArray(rstr_Value) = True Then
'Verify that the rstr_Value variable is is only a one dimensional array.
If Array_GetDimensions(rstr_Value) <> 1 Then
Array_Push = "ERR, the rstr_Value variable passed in was not a one dimensional array."
Exit Function
End If
str_Array_01 = Split(rarr_Array, rstr_Delimiter)
str_Array_02 = Split(rstr_Value, rstr_Delimiter)
rarr_Array = Join(str_Array_01 & rstr_Delimiter & str_Array_02)
Else
On Error Resume Next
ReDim Preserve rarr_Array(UBound(rarr_Array) + 1)
If Err.Number <> 0 Then ' "Subscript out of range" An array that was passed in must have been Erased to re-create it with new elements (possibly when passing an array to be populated into a recursive function)
ReDim rarr_Array(0)
Err.Clear
End If
If IsObject(rstr_Value) = True Then
Set rarr_Array(UBound(rarr_Array)) = rstr_Value
Else
rarr_Array(UBound(rarr_Array)) = rstr_Value
End If
End If
Else
'Check to see if the rstr_Value is an Array.
If IsArray(rstr_Value) = True Then
'Verify that the rstr_Value variable is is only a one dimensional array.
If Array_GetDimensions(rstr_Value) <> 1 Then
Array_Push = "ERR, the rstr_Value variable passed in was not a one dimensional array."
Exit Function
End If
rarr_Array = rstr_Value
Else
rarr_Array = Split(rstr_Value, rstr_Delimiter)
End If
End If
Array_Push = UBound(rarr_Array)
End Function
Public Function Array_QuickSort(ByRef rarr_ArrayToSort(), ByVal rlng_Low, ByVal rlng_High)
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' Note :The rlng_Low variable should be the value of the LBound(rarr_ArrayToSort)
' and the rlng_High variable should be the value of the UBound(rarr_ArrayToSort)
' ==================================================================================
Const const_FUNCTION_NAME = "Array_QuickSort"
Dim var_Pivot
Dim lng_Swap
Dim lng_Low
Dim lng_High
lng_Low = rlng_Low
lng_High = rlng_High
var_Pivot = rarr_ArrayToSort((rlng_Low + rlng_High) / 2)
Do While lng_Low <= lng_High
Do While (rarr_ArrayToSort(lng_Low) < var_Pivot _
And lng_Low < rlng_High)
lng_Low = lng_Low + 1
Loop
Do While (var_Pivot < rarr_ArrayToSort(lng_High) _
And lng_High > rlng_Low)
lng_High = (lng_High - 1)
Loop
If lng_Low <= lng_High Then
lng_Swap = rarr_ArrayToSort(lng_Low)
rarr_ArrayToSort(lng_Low) = rarr_ArrayToSort(lng_High)
rarr_ArrayToSort(lng_High) = lng_Swap
lng_Low = (lng_Low + 1)
lng_High = (lng_High - 1)
End If
Loop
If rlng_Low < lng_High Then
Call Array_QuickSort(rarr_ArrayToSort, rlng_Low, lng_High)
End If
If lng_Low < rlng_High Then
Call Array_QuickSort(rarr_ArrayToSort, lng_Low, rlng_High)
End If
End Function
Public Function Array_SelectionSort(ByRef rarr_ArrayToSort())
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_SelectionSort"
Dim lng_ElementCount
Dim lng_Loop_01
Dim lng_Loop_02
Dim lng_Min
Dim var_Temp
lng_ElementCount = UBound(rarr_ArrayToSort) + 1
For lng_Loop_01 = 0 To (lng_ElementCount - 2)
lng_Min = lng_Loop_01
For lng_Loop_02 = (lng_Loop_01 + 1) To lng_ElementCount - 1
If rarr_ArrayToSort(lng_Loop_02) < rarr_ArrayToSort(lng_Min) Then
lng_Min = lng_Loop_02
End If
Next
var_Temp = rarr_ArrayToSort(lng_Loop_01)
rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Min)
rarr_ArrayToSort(lng_Min) = var_Temp
Next
End Function
Public Function Array_ShellSort(ByRef rarr_ArrayToSort())
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sorts an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_ShellSort"
Dim lng_Loop_01
Dim var_Temp
Dim lng_Hold
Dim lng_HValue
lng_HValue = LBound(rarr_ArrayToSort)
Do
lng_HValue = (3 * lng_HValue + 1)
Loop Until lng_HValue > UBound(rarr_ArrayToSort)
Do
lng_HValue = (lng_HValue / 3)
For lng_Loop_01 = (lng_HValue + LBound(rarr_ArrayToSort)) To UBound(rarr_ArrayToSort)
var_Temp = rarr_ArrayToSort(lng_Loop_01)
lng_Hold = lng_Loop_01
Do While rarr_ArrayToSort(lng_Hold - lng_HValue) > var_Temp
rarr_ArrayToSort(lng_Hold) = rarr_ArrayToSort(lng_Hold - lng_HValue)
lng_Hold = (lng_Hold - lng_HValue)
If lng_Hold < lng_HValue Then
Exit Do
End If
Loop
rarr_ArrayToSort(lng_Hold) = var_Temp
Next
Loop Until lng_HValue = LBound(rarr_ArrayToSort)
End Function
Private Function Array_SiftDown(ByRef rarr_ArrayToSort(), ByVal rlng_Root, ByVal rlng_Bottom)
' ==================================================================================
' Date : 03/18/2008
' Author : Christopher J. Scharer (CJS)
' Description : Sifts the elements down in an array.
' ==================================================================================
Const const_FUNCTION_NAME = "Array_SiftDown"
Dim bln_Done
Dim max_Child
Dim var_Temp
bln_Done = False
Do While ((rlng_Root * 2) <= rlng_Bottom) _
And bln_Done = False
If rlng_Root * 2 = rlng_Bottom Then
max_Child = (rlng_Root * 2)
ElseIf rarr_ArrayToSort(rlng_Root * 2) > rarr_ArrayToSort(rlng_Root * 2 + 1) Then
max_Child = (rlng_Root * 2)
Else
max_Child = (rlng_Root * 2 + 1)
End If
If rarr_ArrayToSort(rlng_Root) < rarr_ArrayToSort(max_Child) Then
var_Temp = rarr_ArrayToSort(rlng_Root)
rarr_ArrayToSort(rlng_Root) = rarr_ArrayToSort(max_Child)
rarr_ArrayToSort(max_Child) = var_Temp
rlng_Root = max_Child
Else
bln_Done = True
End If
Loop
End Function
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
For me my issue was that I had two of the same NuGet Packages installed with different Versions.
Useful thread and I don't bring much new to the table. The step I took is also part of the description Maxime helpfully points to but some may overlook it. The section is Adding your SSH key to the ssh-agent.
I had already generated my ssh-key but after a reboot I was unable to clone one of my own repositories.
I had to start the ssh-agent and add the private key to this agent in order to clone.
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa
Open python console:
import platform
platform.architecture()[0]
it should display the '64bit' or '32bit' according to your platform.
Alternatively( in case of OS X binaries ):
import sys
sys.maxsize > 2**32
# it should display True in case of 64bit and False in case of 32bit