In my case i removed
Restart=always
added
tty: true
And executed the below command to open shell (daemon process, because docker reads the compose file and stops the container once it reaches the last line of the file).
docker-compose up -d
I would personally use http://www.datejs.com/, really handy. Specifically, look at the time.js file: http://code.google.com/p/datejs/source/browse/trunk/src/time.js
I am assuming you have site key and secret in place. Follow this step.
In your HTML file, add the script.
<script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
Also, do use jQuery for easy event handling.
Here is the simple form.
<form id="comment_form" action="form.php" method="post" >
<input type="email" name="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
</form>
You need to initialize the Google recaptcha and listen for the ready event. Here is how to do that.
<script>
// when form is submit
$('#comment_form').submit(function() {
// we stoped it
event.preventDefault();
var email = $('#email').val();
var comment = $("#comment").val();
// needs for recaptacha ready
grecaptcha.ready(function() {
// do request for recaptcha token
// response is promise with passed token
grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
// add token to form
$('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
$.post("form.php",{email: email, comment: comment, token: token}, function(result) {
console.log(result);
if(result.success) {
alert('Thanks for posting comment.')
} else {
alert('You are spammer ! Get the @$%K out.')
}
});
});
});
});
</script>
Here is the sample PHP file. You can use Servlet or Node or any backend language in place of it.
<?php
$email;$comment;$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['comment'])){
$comment=$_POST['comment'];
}if(isset($_POST['token'])){
$captcha=$_POST['token'];
}
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$secretKey = "put your secret key here";
$ip = $_SERVER['REMOTE_ADDR'];
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
header('Content-type: application/json');
if($responseKeys["success"]) {
echo json_encode(array('success' => 'true'));
} else {
echo json_encode(array('success' => 'false'));
}
?>
Here is the tutorial link: https://codeforgeek.com/2019/02/google-recaptcha-v3-tutorial/
Hope it helps.
svn move
— Move a file or directory.
expression
is your friend:
plot(1,1, main=expression('title'^2)) #superscript
plot(1,1, main=expression('title'[2])) #subscript
More complete sample from here and here.
Or you can check out my layout sample. p.s no need to put API key in the map view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="@+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
/>
<ListView android:id="@+id/nearby_lv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:layout_weight="1"
/>
</LinearLayout>
Solution using pointers:
#include<stdio.h>
#include<stdlib.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double *mass;
};
int main()
{
struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
What you are looking for is called Geocoding.
Google provides a Geocoding Web Service which should do what you're looking for. You will be able to do geocoding on your server.
JSON Example:
http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
XML Example:
http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
Edit:
Please note that this is now a deprecated method and you must provide your own Google API key to access this data.
try (without format
step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");_x000D_
_x000D_
console.log( new Date(d) );_x000D_
console.log( new Date(moment()) );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
_x000D_
Apache commons to the rescue again.
assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));
Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2)
doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
You want
strchr (const char *s, int c)
If the character c is in the string s it returns a pointer to the location in s. Otherwise it returns NULL. So just use your list of invalid characters as the string.
This works. Try it.
<BODY ondragstart="return false;" ondrop="return false;">
If you want to check if your -vm eclipse.ini
option worked correctly you can use this to see under what JVM the IDE itself runs: menu Help > About Eclipse > Installation Details > Configuration tab. Locate the line that says: java.runtime.version=...
.
DESC KEYSPACES will do the job.
Also, If you want to describe schema of a particular keyspace you can use
DESC
Try this in your CSS:
input {
text-align: right;
}
To align the text in the center:
input {
text-align: center;
}
But, it should be left-aligned, as that is the default - and appears to be the most user friendly.
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".
Static storage duration means that the variable resides in the same place in memory through the lifetime of the program.
Linkage is orthogonal to this.
I think this is the most important distinction you can make. Understand this and the rest, as well as remembering it, should come easy (not addressing @Tony directly, but whoever might read this in the future).
The keyword static
can be used to denote internal linkage and static storage, but in essence these are different.
What does it mean with local variable? Is that a function local variable?
Yes. Regardless of when the variable is initialized (on first call to the function and when execution path reaches the declaration point), it will reside in the same place in memory for the life of the program. In this case, static
gives it static storage.
Now what about the case with static and file scope? Are all global variables considered to have static storage duration by default?
Yes, all globals have by definition static storage duration (now that we cleared up what that means). But namespace scoped variables aren't declared with static
, because that would give them internal linkage, so a variable per translation unit.
How does static relate to the linkage of a variable?
It gives namespace-scoped variables internal linkage. It gives members and local variables static storage duration.
Let's expand on all this:
//
static int x; //internal linkage
//non-static storage - each translation unit will have its own copy of x
//NOT A TRUE GLOBAL!
int y; //static storage duration (can be used with extern)
//actual global
//external linkage
struct X
{
static int x; //static storage duration - shared between class instances
};
void foo()
{
static int x; //static storage duration - shared between calls
}
This whole static keyword is downright confusing
Definitely, unless you're familiar with it. :) Trying to avoid adding new keywords to the language, the committee re-used this one, IMO, to this effect - confusion. It's used to signify different things (might I say, probably opposing things).
There are a couple of different ways to approach the problem:
Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.
NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.
I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.
If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.
Use:
git remote add upstream ORIGINAL_REPOSITORY_URL
This will set your upstream to the repository you forked from. Then do this:
git fetch upstream
This will fetch all the branches including master from the original repository.
Merge this data in your local master branch:
git merge upstream/master
Push the changes to your forked repository i.e. to origin:
git push origin master
Voila! You are done with the syncing the original repository.
Using pieces from all of these answers and the comments, I put this together for anyone who sees this question in the future. It covers all of the situations listed in the other answers
# If using ISE
if ($psISE) {
$ScriptPath = Split-Path -Parent $psISE.CurrentFile.FullPath
# If Using PowerShell 3 or greater
} elseif($PSVersionTable.PSVersion.Major -gt 3) {
$ScriptPath = $PSScriptRoot
# If using PowerShell 2 or lower
} else {
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Path
}
Just to add to the other answers: In case you don't like the onload
callback approach, you can "promisify" it like so:
let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img
If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)
Of course all choices of a formborderstyle beginning with Fixed will do.
Selection(1, 1).Select
will select only the top left cell of your current selection.
Something like this would work
/^\d{2}$/
Use a DateFormat
. In an internationalized application, use the format provide by getInstance
. If you want to explicitly control the format, create a new SimpleDateFormat
yourself.
For a nice quick and dirty creation/replacement of a crontab from with a BASH script, I used this notation:
crontab <<EOF
00 09 * * 1-5 echo hello
EOF
This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?
github.com
or cloud.githubusercontent.com
or the like work.
Steps that worked for me in a gist:
Mygist.md
(and optionally more files)Mygist.md
.But: GitHub people may change this behavior tomorrow, without documenting it.
If all you need to do is wait for the html on the page to become stable before trying to interact with elements, you can poll the DOM periodically and compare the results, if the DOMs are the same within the given poll time, you're golden. Something like this where you pass in the maximum wait time and the time between page polls before comparing. Simple and effective.
public void waitForJavascript(int maxWaitMillis, int pollDelimiter) {
double startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + maxWaitMillis) {
String prevState = webDriver.getPageSource();
Thread.sleep(pollDelimiter); // <-- would need to wrap in a try catch
if (prevState.equals(webDriver.getPageSource())) {
return;
}
}
}
I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important
(to override the default style on bootstrap.css).
Example code
.nav {_x000D_
background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
background-color: #666 !important;_x000D_
color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
<!-- Nav tabs -->_x000D_
<ul class="nav nav-tabs" role="tablist">_x000D_
<li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
<li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
<li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
<li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
</ul>_x000D_
_x000D_
<!-- Tab panes -->_x000D_
<div class="tab-content">_x000D_
<div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
<div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
<div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
<div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/zjjpocv6/2/
It's about your way of reading it. not
operator is dynamic, that's why you are able to apply it in
if not x == 'val':
But !=
could be read in a better context as an operator which does the opposite of what ==
does.
More accurately, your mod1
and lib
directories are not modules, they are packages. The file mod11.py
is a module.
Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
>>> import lib
>>> dir(lib)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
>>> import lib.pkg1
>>> import lib.pkg1.mod11
>>> lib.pkg1.mod11.mod12()
mod12
An alternative is to use the from
syntax to "pull" a module from a package into you scripts namespace.
>>> from lib.pkg1 import mod11
Then reference the function as simply mod11.mod12()
.
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
They're not actually characters, they're hexadecimal digits.
Although the current answers are great, none of them did quite what I was looking for, I wanted to open the maps app only, add a name for each of the source location and destination, using the geo URI scheme wouldn't work for me at all and the maps web link didn't have labels so I came up with this solution, which is essentially an amalgamation of the other solutions and comments made here, hopefully it's helpful to others viewing this question.
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?saddr=%f,%f(%s)&daddr=%f,%f (%s)", sourceLatitude, sourceLongitude, "Home Sweet Home", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
To use your current location as the starting point (unfortunately I haven't found a way to label the current location) then use the following
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", destinationLatitude, destinationLongitude, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
For completeness, if the user doesn't have the maps app installed then it's going to be a good idea to catch the ActivityNotFoundException, then we can start the activity again without the maps app restriction, we can be pretty sure that we will never get to the Toast at the end since an internet browser is a valid application to launch this url scheme too.
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?daddr=%f,%f (%s)", 12f, 2f, "Where the party is at");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
try
{
startActivity(intent);
}
catch(ActivityNotFoundException ex)
{
try
{
Intent unrestrictedIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(unrestrictedIntent);
}
catch(ActivityNotFoundException innerEx)
{
Toast.makeText(this, "Please install a maps application", Toast.LENGTH_LONG).show();
}
}
P.S. Any latitudes or longitudes used in my example are not representative of my location, any likeness to a true location is pure coincidence, aka I'm not from Africa :P
EDIT:
For directions, a navigation intent is now supported with google.navigation
Uri navigationIntentUri = Uri.parse("google.navigation:q=" + 12f +"," + 2f);//creating intent with latlng
Intent mapIntent = new Intent(Intent.ACTION_VIEW, navigationIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
Go to /etc/apache2/apache2.conf
You have to edit that file (you should have root permission). Change directory text as bellow:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Now you have to restart apache.
service apache2 restart
The documentation is misleading.
I have the following code running in production
DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
SET @sql = 'SELECT UserID FROM UserTable'
*/
INSERT INTO @table
EXEC(@sql)
SELECT * FROM @table
There are plenty of good answers given here for loading controllers within controllers, but for me, this contradicts the mvc pattern.
The sentence that worries me is;
(filled with data processed by the product controller)
The models are there for processing and returning data. If you put this logic into your product model then you can call it from any controller you like without having to try to pervert the framework.
Once of the most helpful quotes I read was that the controller was like the 'traffic cop', there to route requests and responses between models and views.
While doing production config i got the permission issue.I tried below solution to resolve the issue.
Error Message
ubuntu@node1:~$ docker run hello-world
docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.38/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
See 'docker run --help'.
Solution: permissions of the socket indicated in the error message, /var/run/docker.sock:
ubuntu@ip-172-31-21-106:/var/run$ ls -lrth docker.sock
srw-rw---- 1 root root 0 Oct 17 11:08 docker.sock
ubuntu@ip-172-31-21-106:/var/run$ sudo chmod 666 /var/run/docker.sock
ubuntu@ip-172-31-21-106:/var/run$ ls -lrth docker.sock
srw-rw-rw- 1 root root 0 Oct 17 11:08 docker.sock
After changes permission for docket.sock then execute below command to check permissions.
ubuntu@ip-172-31-21-106:/var/run$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:c3b4ada4687bbaa170745b3e4dd8ac3f194ca95b2d0518b417fb47e5879d9b5f
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.
So they should be exactly equivalent performance wise.
http://dev.mysql.com/doc/refman/5.6/en/insert.html says:
INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.
assertNotNull
asserts that the object is not null. If it is null the test fails, so you want that.
Yes there is a performance hit when using Reflection but a possible workaround for optimization is caching the method:
Method md = null; // Call while looking up the method at each iteration.
millis = System.currentTimeMillis( );
for (idx = 0; idx < CALL_AMOUNT; idx++) {
md = ri.getClass( ).getMethod("getValue", null);
md.invoke(ri, null);
}
System.out.println("Calling method " + CALL_AMOUNT+ " times reflexively with lookup took " + (System.currentTimeMillis( ) - millis) + " millis");
// Call using a cache of the method.
md = ri.getClass( ).getMethod("getValue", null);
millis = System.currentTimeMillis( );
for (idx = 0; idx < CALL_AMOUNT; idx++) {
md.invoke(ri, null);
}
System.out.println("Calling method " + CALL_AMOUNT + " times reflexively with cache took " + (System.currentTimeMillis( ) - millis) + " millis");
will result in:
[java] Calling method 1000000 times reflexively with lookup took 5618 millis
[java] Calling method 1000000 times reflexively with cache took 270 millis
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
If you've included the file correctly and file exists and still getting error:
Then make sure:
Your included file contains the class and is not defined within any namespace.
If the class is in a namespace then:
instead of new YourClass()
you've to do new YourNamespace\YourClass()
A New Laravel Blade Error Directive comes to Laravel 5.8.13
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
There are two ways to delete a stash:
$ git stash drop <stash_id>
. $ git stash clear
.Use both of them with caution, it maybe is difficult to revert the once deleted stashes.
Here is the reference article.
You likely forgot to #include <stdlib.h>
I had the same issue and I used this function to compress individual pages which results in the file size being compressed by upto 1/3 of the original size.
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
theDoc.Flatten();
}
For iOS 13.6
Go to settings -> General -> Device Management -> Click on Trust « Apple Development » -> Click on the red trust button and you’re all set! Enjoy
var nameList = [_x000D_
{name:'x', age:20, email:'[email protected]'},_x000D_
{name:'y', age:60, email:'[email protected]'},_x000D_
{name:'Joe', age:22, email:'[email protected]'},_x000D_
{name:'Abc', age:40, email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var filteredValue = nameList.filter(function (item) {_x000D_
return item.name == "Joe" && item.age < 30;_x000D_
});_x000D_
_x000D_
//To See Output Result as Array_x000D_
console.log(JSON.stringify(filteredValue));
_x000D_
You can simply use javascript :)
<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));
//Iterate through an array declared above
foreach($php_multi_array as $key => $value)
{
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";
foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}
echo ")";
}
}
?>
OUTPUT:
lang => PHP
type => array(
c_type => MULTI
p_type => ARRAY
)
Since Java 8, you can use:
String String.join(CharSequence delimiter, CharSequence... elements)
String String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
If you want to take non-String
s and join them to a String
, you can use Collectors.joining(CharSequence delimiter)
, e.g.:
String joined = anyCollection.stream().map(Object::toString).collect(Collectors.joining(","));
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
public class FileFinder extends SimpleFileVisitor<Path> {
private PathMatcher matcher;
public ArrayList<Path> foundPaths = new ArrayList<>();
public FileFinder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path name = file.getFileName();
if (matcher.matches(name)) {
foundPaths.add(file);
}
return FileVisitResult.CONTINUE;
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
FileFinder finder = new FileFinder("*.txt");
Files.walkFileTree(fileDir, finder);
ArrayList<Path> foundFiles = finder.foundPaths;
if (foundFiles.size() > 0) {
for (Path path : foundFiles) {
System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
}
} else {
System.out.println("No files were founds!");
}
}
}
UPDATE db.tablename SET columnID = (SELECT UUID()) where columnID is not null
You can use the query
function, so if your data were in col A where the first row was the column title...
=query(A2:A,"select A, count(A) where A != '' group by A order by count(A) desc label A 'City'", 0)
yields
City count
London 2
Paris 2
Berlin 1
Rome 1
Link to working Google Sheet.
https://docs.google.com/spreadsheets/d/1N5xw8-YP2GEPYOaRkX8iRA6DoeRXI86OkfuYxwXUCbc/edit#gid=0
I take it you can modify MyScript.ps1
. Then try to change it like so:
$(
Here is your current script
) *>&1 > output.txt
I just tried this with PowerShell 3. You can use all the redirect options as in Nathan Hartley's answer.
Another possibility is that you are missing an .npmrc
file if you are pulling any packages that are not publicly available.
You will need to add an .npmrc
file at the root directory and add the private/internal registry inside of the .npmrc
file like this:
registry=http://private.package.source/secret/npm-packages/
Check if scp
is installed or not on from where you want want to copy
check using which scp
If it's already installed, it will print you a path like /usr/bin/scp
Else, install scp using:
yum -y install openssh-clients
Then copy command
scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql /var/www/html/db_bkp/
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
As others have said, the minumum/maximum values the column can store and how much storage it takes in bytes is only defined by the type, not the length.
A lot of these answers are saying that the (11)
part only affects the display width which isn't exactly true, but mostly.
A definition of int(2)
with no zerofill specified will:
100
100
when output (not 0
or 00
)The only thing the (2)
will do is if zerofill is also specified:
1
will be shown 01
. The best way to see all the nuances is to run:
CREATE TABLE `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`int1` int(10) NOT NULL,
`int2` int(3) NOT NULL,
`zf1` int(10) ZEROFILL NOT NULL,
`zf2` int(3) ZEROFILL NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `mytable`
(`int1`, `int2`, `zf1`, `zf2`)
VALUES
(10000, 10000, 10000, 10000),
(100, 100, 100, 100);
select * from mytable;
which will output:
+----+-------+-------+------------+-------+
| id | int1 | int2 | zf1 | zf2 |
+----+-------+-------+------------+-------+
| 1 | 10000 | 10000 | 0000010000 | 10000 |
| 2 | 100 | 100 | 0000000100 | 100 |
+----+-------+-------+------------+-------+
This answer is tested against MySQL 5.7.12 for Linux and may or may not vary for other implementations.
If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.
If you rely only on javascript, then some users who browse without it won't be able to click your links.
In some cases - when not so many columns - useful the WINDOW functions FIRST_VALUE() and LAST_VALUE().
SELECT
FIRST_VALUE(timestamp) over (ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (ORDER BY timestamp ASC) as last_action
FROM events
This query sort data only once.
It can be used for getting fisrt and last rows by some ID
SELECT DISTINCT
order_id,
FIRST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_action
FROM events as x
I'm using the Hibernate 4.2.7.SP1 with Postgres 9.3 and following works for me:
@Entity
public class ConfigAttribute {
@Lob
public byte[] getValueBuffer() {
return m_valueBuffer;
}
}
as Oracle has no trouble with that, and for Postgres I'm using custom dialect:
public class PostgreSQLDialectCustom extends PostgreSQL82Dialect {
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (sqlTypeDescriptor.getSqlType() == java.sql.Types.BLOB) {
return BinaryTypeDescriptor.INSTANCE;
}
return super.remapSqlTypeDescriptor(sqlTypeDescriptor);
}
}
the advantage of this solution I consider, that I can keep hibernate jars untouched.
For more Postgres/Oracle compatibility issues with Hibernate, see my blog post.
use Regex.Split(string,"#|#");
For Left indent
Shift + Tab
For Right indent
simple Tab
My solution is to use ggplot2
. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))
Then use ggplot2
to plot it
library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()
This is saying plot the data in df
, and separate the points by class
.
The plot generated is
you can declare time in two ways for this problem..
1) either give too long time that your file reading is complete in between that time.
<session-config>
<session-timeout> 1000 </session-timeout>
</session-config>
2)declare time which is never expires your session.
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
SSH based git access method can be specified in <repo_path>/.git/config
using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:
URL style:
url = ssh://[user@]host.xz[:port]/path/to/repo.git/
SCP style:
url = [user@]host.xz:path/to/repo.git/
Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config
host definition in your ~/.ssh/config
such as:
Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user
Then you can test in a shell with:
ssh my_git_host
and alter your SCP-style URI in <repo_path>/.git/config
as:
url = my_git_host:path/to/repo.git/
You can get the index of the current iteration by adding another parameter to your iterator function
, e.g.
_.each(['foo', 'bar', 'baz'], function (val, i) {
console.log(i + ": " + val); // 0: foo, 1: bar, 2: baz
});
Here's what I would use:
(?<!\S)stackoverflow(?!\S)
In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.
This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b
approach does.
Even better:
DataTable DTable = new DataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = DTable;
DataGridView ServersTable = new DataGridView();
ServersTable.AutoGenerateColumns = false;
ServersTable.DataSource = DTable;
ServersTable.DataSource = SBind;
ServersTable.Refresh();
You're telling the bindable source that it's bound to the DataTable, in-turn you need to tell your DataGridView not to auto-generate columns, so it will only pull the data in for the columns you've manually input into the control... lastly refresh the control to update the databind.
circle.xml (drawable)
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid
android:color="#000"/>
<size
android:width="10dp"
android:height="10dp"/>
</shape>
layout
<ImageView
android:id="@+id/circleColor"
android:layout_width="15dp"
android:layout_height="15dp"
android:textSize="12dp"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:background="@drawable/circle"/>
in activity
circleColor = (ImageView) view.findViewById(R.id.circleColor);
int color = Color.parseColor("#00FFFF");
((GradientDrawable)circleColor.getBackground()).setColor(color);
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
I tried to see all connections for mongo database by following command.
netstat -anp --tcp --udp | grep mongo
This command can show every tcp connection for mongodb in more detail.
tcp 0 0 10.26.2.185:27017 10.26.2.1:2715 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.1:1702 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.185:39506 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.185:40021 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.185:39509 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.184:46062 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.184:46073 ESTABLISHED 1442/./mongod
tcp 0 0 10.26.2.185:27017 10.26.2.184:46074 ESTABLISHED 1442/./mongod
From Node.js website
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Event-driven means that the server only reacts when an event occurs. This allow us to create high performance, highly scalable, “real-time” applications.
Finally, this is probably the best article that will get you excited about Node.js
This is answered in the comments; package-lock.json
is a feature in npm
v5 and higher. npm shrinkwrap
is how you create a lockfile in all versions of npm
.
I believe in your case something like
sort -t@ -k1.1,1.4 -k1.5,1.7 ... <inputfile
will work better. @ is the field separator, make sure it is a character that appears nowhere. then your input is considered as consisting of one column.
Edit: apparently clintp already gave a similar answer, sorry. As he points out, the flags 'n' and 'r' can be added to every -k.... option.
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
I chose cut
here because you could simply extend the code for a few more variables...
As another answer already said, call select myfunc(:y) from dual;
, but you might find declaring and setting a variable in sqlplus a little tricky:
sql> var y number
sql> begin
2 select 7 into :y from dual;
3 end;
4 /
PL/SQL procedure successfully completed.
sql> print :y
Y
----------
7
sql> select myfunc(:y) from dual;
People have mentioned make
but bjam
also supports a similar concept. Using bjam -jx
instructs bjam to build up to x
concurrent commands.
We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.
we can use express-session to send the required data
when you initialise the app
const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));
so before redirection just save the context for the session
app.post('/category', function(req, res) {
// add your context here
req.session.context ='your context here' ;
res.redirect('/');
});
Now you can get the context anywhere for the session. it can get just by req.session.context
app.get('/', function(req, res) {
// So prepare the context
var context=req.session.context;
res.render('home.jade', context);
});
ObervableCollection have constructor in which you can pass your list. Quoting MSDN:
public ObservableCollection(
List<T> list
)
Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.
My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.
Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.
In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)
To me, there are as many pros as there are cons to using maven vs ant for in-house projects. For open source projects however, I think Maven has had a great impact in making many projects much easier to build. It wasn't too long ago that it took hours get the average OSS Java (ant based) project to compile, having to set a ton of variables, downloading dependent projects, etc.
You can do anything with Maven you can do with Ant, but where Ant doesn't encourage any standards, Maven strongly suggests you to follow it's structure, or it'll be more work. True, some things are a pain to set up with Maven that would be easy to do with Ant, but the end result is almost always something that is easier to build from the perspective of people who just want to check out a project and go.
You may also want to be aware of the difference between, for example, Sys.setenv(LANG = "ru")
and Sys.setlocale(locale = "ru_RU.utf8")
.
> Sys.setlocale(locale = "ru_RU.utf8")
[1] "LC_CTYPE=ru_RU.utf8;LC_NUMERIC=C;LC_TIME=ru_RU.utf8;LC_COLLATE=ru_RU.utf8;LC_MONETARY=ru_RU.utf8;LC_MESSAGES=en_IE.utf8;LC_PAPER=en_IE.utf8;LC_NAME=en_IE.utf8;LC_ADDRESS=en_IE.utf8;LC_TELEPHONE=en_IE.utf8;LC_MEASUREMENT=en_IE.utf8;LC_IDENTIFICATION=en_IE.utf8"
If you are interested in changing the behaviour of functions that refer to one of these elements (e.g strptime
to extract dates), you should use Sys.setlocale()
.
See ?Sys.setlocale
for more details.
In order to see all available languages on a linux system, you can run
system("locale -a", intern = TRUE)
Java Usage example: myMenuItem.setIcon(android.R.drawable.ic_menu_save);
Resource Usage example: android:icon="@android:drawable/ic_menu_save"
This is my solution. I Hide and then confirm check
onclick="return ConfirmSubmit(this);" />
function ConfirmSubmit(sender)
{
sender.disabled = true;
var displayValue = sender.style.
sender.style.display = 'none'
if (confirm('Seguro que desea entregar los paquetes?')) {
sender.disabled = false
return true;
}
sender.disabled = false;
sender.style.display = displayValue;
return false;
}
This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.
ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');
This is my version, quite similar to the upper one, but I think good for reference.
if (mob_url == "") {
lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
lt_url = mob_url;
} else {
lt_url = desk_url;
}
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
Actually, this is very easy:
Good luck!
Try setting your ScriptManager to this.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
If you want to build DOM you can use jsdom.
There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.
You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.
parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.
And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.
If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.
Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.
There's a nettuts+ toturial for the latter solutions.
1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source
Check if your .pbd file is missing in your bin/Debug folder. If it is then go to "Properties" of your project, selected "Build" and then "Advanced" at the bottom. Choose "full" under "Debug info" in the new window that appeared. This was my issue and solved it for me.
There is another case where 'Java Class' don't show, maybe some reserved words exist in the package name, for example:
com.liuyong.package.case
com.liuyong.import.package
It's the same reason as @kuporific 's answer: the package name is invalid.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
A socket is a structure in your software. It's more-or-less a file; it has operations like read and write. It isn't a physical thing; it's a way for your software to refer to physical things.
A port is a device-like thing. Each host has one or more networks (those are physical); a host has an address on each network. Each address can have thousands of ports.
One socket only may be using a port at an address. The socket allocates the port approximately like allocating a device for file system I/O. Once the port is allocated, no other socket can connect to that port. The port will be freed when the socket is closed.
Take a look at TCP/IP Terminology.
Not the best answer, but it's an option anyway:
Comment the given line in the web.config.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/**********************************************************************
Naziv procedure : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja : 13.06.2013.
Namena : Traži sql objekat na celom serveru
Tabele :
Ulazni parametri :
Izlazni parametri :
Datum zadnje izmene :
Opis izmene :
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] ( @SEARCHSTRING VARCHAR(255),
@notcontain Varchar(255)
)
AS
declare @text varchar(1500),@textinit varchar (1500)
set @textinit=
'USE @sifra
insert into ##temp2
select ''@sifra''as dbName,a.[Object Name],a.[Object Type]
from(
SELECT DISTINCT sysobjects.name AS [Object Name] ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''@SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''@notcontain'',sysobjects.name)=0 or
CHARINDEX(''@notcontain'',sysobjects.name)<>0))
)a'
set @textinit=replace(@textinit,'@SEARCHSTRING',@SEARCHSTRING)
set @textinit=replace(@textinit,'@notcontain',@notcontain)
SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType
into ##temp1
from master.dbo.sysdatabases order by name
SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0
declare @sifra VARCHAR(255),@suma int,@brojac int
set @suma=(select count(dbName) from ##temp1)
DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC
OPEN c_k
FETCH NEXT FROM c_K INTO @sifra
SET @brojac = 1
WHILE (@@fetch_status = 0 ) AND (@brojac <= @suma)
BEGIN
set @text=replace(@textinit,'@sifra',@sifra)
exec (@text)
SET @brojac = @brojac +1
DELETE FROM ##temp1 WHERE dbName = @sifra
FETCH NEXT FROM c_k INTO @sifra
END
close c_k
DEALLOCATE c_k
select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1
Double click "ASP" in the site's Home screen in IIS admin, expand "Debugging Properties", enable "Send errors to browser", and click "Apply".
Under "Error Pages" on the home screen select "500", then "Edit feature settings" and select "Detailed Errors".
Note that the same steps apply for IIS 8.0 (Windows Server 2012).
:unchecked
is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.
In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked)
, it's safe to assume that there is no corresponding :unchecked
pseudo. Browser support for :not()
and :checked
is identical, so that shouldn't be a problem.
This may seem inconsistent with the :enabled
and :disabled
states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.
(:indeterminate
does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)
The problem here is
if (stop = true)
is an assignation not a comparision.
Try if (stop == true)
Also take a look to the Top Ten Errors Java Programmers Make.
Best as an out parameter:
void testfunc(char* outStr){
char str[10];
for(int i=0; i < 10; ++i){
outStr[i] = str[i];
}
}
Called with
int main(){
char myStr[10];
testfunc(myStr);
// myStr is now filled
}
You can use attrchange jQuery plugin. The main function of the plugin is to bind a listener function on attribute change of HTML elements.
Code sample:
$("#myDiv").attrchange({
trackValues: true, // set to true so that the event object is updated with old & new values
callback: function(evnt) {
if(evnt.attributeName == "display") { // which attribute you want to watch for changes
if(evnt.newValue.search(/inline/i) == -1) {
// your code to execute goes here...
}
}
}
});
One can define a function called shuffled
(in the same sense of sort
vs sorted
)
def shuffled(x):
import random
y = x[:]
random.shuffle(y)
return y
x = shuffled([1, 2, 3, 4])
print x
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
def xy(r,phi):
return r*np.cos(phi), r*np.sin(phi)
fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')
phis=np.arange(0,6.28,0.01)
r =1.
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()
Or, if you prefer, look at the path
s, http://matplotlib.sourceforge.net/users/path_tutorial.html
Mozilla currently only supports CSS gradients as values of the background-image property, as well as within the shorthand background.
— https://developer.mozilla.org/en/CSS/-moz-linear-gradient
Example 3 - Gradient Borders
border: 8px solid #000;
-moz-border-bottom-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-top-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-left-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
-moz-border-right-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc;
padding: 5px 5px 5px 15px;
I had a similar problem.
I would also look at this answer: Is there a high resolution (microsecond, nanosecond) DateTime object available for the CLR?.
About half-way down is an answer by "Robert P" with some extension functions I found useful.
If you don't care about the order of the array, then you may want to get the difference between arr1
and arr2
by id
using differenceBy() and then simply use concat() to append all the updated objects.
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();
var arr1 = [{_x000D_
id: '124',_x000D_
name: 'qqq'_x000D_
}, {_x000D_
id: '589',_x000D_
name: 'www'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'eee'_x000D_
}, {_x000D_
id: '567',_x000D_
name: 'rrr'_x000D_
}]_x000D_
_x000D_
var arr2 = [{_x000D_
id: '124',_x000D_
name: 'ttt'_x000D_
}, {_x000D_
id: '45',_x000D_
name: 'yyy'_x000D_
}];_x000D_
_x000D_
var result = _(arr1).differenceBy(arr2, 'id').concat(arr2).value();_x000D_
_x000D_
console.log(result);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.js"></script>
_x000D_
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
if you need to you can cast the dtype
back again calling astype(int)
on the column
Just add a css property:
<style>
a {
pointer-events: none;
}
</style>
Doing so you can disable the anchor tag.
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
In my case, the target phone had the app already installed, but in a "disabled" state. So the user thought it was already uninstalled, but it wasn't. I went to the main app list, clicked on the "disabled" app, uninstalled it, and then the APK would go on.
![pic][logo]{.classname}
[logo]: (picurl)
<style type="text/css">
.classname{
width: 200px;
}
</style>
You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.
Instead try:
void action(const typename Subclass::mytype &var) {
(static_cast<Subclass*>(this))->do_action();
}
This is Atharva's answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView. Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:
$('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
I would suggest Smoothie Charts.
It's very simple to use, easily and widely configurable, and does a great job of streaming real time data.
There's a builder that lets you explore the options and generate code.
Disclaimer: I am a contributor to the library.
Map :
- It processes one row at a time , very similar to map() method of MapReduce.
- You return from the transformation after every row.
MapPartitions
- It processes the complete partition in one go.
- You can return from the function only once after processing the whole partition.
- All intermediate results needs to be held in memory till you process the whole partition.
- Provides you like setup() map() and cleanup() function of MapReduce
Map Vs mapPartitions
http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/
Spark Map
http://bytepadding.com/big-data/spark/spark-map/
Spark mapPartitions
http://bytepadding.com/big-data/spark/spark-mappartitions/
HTML:
<form>
<textarea id='text' maxlength='10'></textarea>
<div id='msg'>10 characters left</div>
<div id='lastChar'></div>
</form>
JS:
function charCount() {
var textEntered = document.getElementById('text').value;
var msg = document.getElementById('msg');
var counter = (10-(textEntered.length));
msg.textContent = counter+' characters left';
}
var el = document.getElementById('text');
el.addEventListener('keyup',charCount,false);
Here's how I did it:
This is my PostsController
Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
And this is my Post Model.
protected $fillable = ['title', 'body','user_id'];
And try refreshing the migration if its just on test instance
$ php artisan migrate:refresh
Note: migrate: refresh will delete all the previous posts, users
Option 3
To update current iframe
$("iframe").wrap('<div class="embed-responsive embed-responsive-16by9"/>');
$("iframe").addClass('embed-responsive-item');
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
if ( $("#txt").val().length == 0 )
{
// do something
}
I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.
Try the following parameter:
-nc
,--no-clobber
: skip downloads that would download to existing files.
Sample usage:
wget -nc http://example.com/pic.png
TLDR; Pandas groupby.agg
has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use
df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))
Mean Sum
dummy
1 0.036901 0.369012
OR
df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')
Mean Sum
dummy
1 0.036901 0.369012
Pandas has changed the behavior of GroupBy.agg
in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.
From the documentation,
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in
GroupBy.agg()
, known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>)
.
import pandas as pd
pd.__version__
# '0.25.0.dev0+840.g989f912ee'
# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]
})
df.groupby('kind').agg(
max_height=('height', 'max'), min_weight=('weight', 'min'),)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
Alternatively, you can use pd.NamedAgg
(essentially a namedtuple) which makes things more explicit.
df.groupby('kind').agg(
max_height=pd.NamedAgg(column='height', aggfunc='max'),
min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
It is even simpler for Series, just pass the aggfunc to a keyword argument.
df.groupby('kind')['height'].agg(max_height='max', min_height='min')
max_height min_height
kind
cat 9.5 9.1
dog 34.0 6.0
Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:
df.groupby('kind')['height'].agg(**{'max height': 'max', ...})
In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning
:
df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed
# in a future version
Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.
df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})
returns
op1 op2
dummy
1 0.328953 0.032895
Or,
df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])
op1 op2
dummy
1 0.328953 0.032895
As per Nawfal's answer, IF statements need to be in a procedure. I found this post that shows a brilliant example of using your script in a procedure while still developing and testing. Basically, you create, call then drop the procedure:
i am going with @Hiren Patel answer but slightly change in android studio 2.2 and later
@ThoAppelsin in his comment to question posted is right. The code snippet posted in the question it is valid and with no errors. The error you have must be because other bad syntax in any other place of your c source file. enum{a,b,c};
defines three symbolic constants (a
, b
and c
) which are integers with values 0
,1
and 2
respectively, but when we use enum
it is because we don't usually care about the specific integer value, we care more about the meaning of the symbolic constant name.
This means you can have this:
#include <stdio.h>
enum {a,b,c};
int main(){
printf("%d\n",b);
return 0;
}
and this will output 1
.
This also will be valid:
#include <stdio.h>
enum {a,b,c};
int bb=b;
int main(){
printf("%d\n",bb);
return 0;
}
and will output the same as before.
If you do this:
enum {a,b,c};
enum {a,b,c};
you will have an error, but if you do this:
enum alfa{a,b,c};
enum alfa;
you will not have any error.
you can do this:
enum {a,b,c};
int aa=a;
and aa
will be an integer variable with value 0
. but you can also do this:
enum {a,b,c} aa= a;
and will have the same effect (that is, aa
being an int
with 0
value).
you can also do this:
enum {a,b,c} aa= a;
aa= 7;
and aa
will be int
with value 7
.
because you cannot repeat symbolic constant definition with the use of enum
, as i have said previously, you must use tags if you want to declare int
vars with the use of enum
:
enum tag1 {a,b,c};
enum tag1 var1= a;
enum tag1 var2= b;
the use of typedef
it is to safe you from writing each time enum tag1
to define variable. With typedef
you can just type Tag1
:
typedef enum {a,b,c} Tag1;
Tag1 var1= a;
Tag1 var2= b;
You can also have:
typedef enum tag1{a,b,c}Tag1;
Tag1 var1= a;
enum tag1 var2= b;
Last thing to say it is that since we are talking about defined symbolic constants it is better to use capitalized letters when using enum
, that is for example:
enum {A,B,C};
instead of
enum {a,b,c};
Check the MySQL Datetime Functions:
Try this:
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:
plt.title(figure_title, y=1.08)
This also works for plt.suptitle()
, but not (yet) for plt.xlabel()
, etc.
It looks like what you want to do is remove your first merge. You could follow the following procedure:
git checkout master # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull # or git merge remote/master
git merge topic
That would give you what you want.
I've had success with
<span class="someclass"></span>
Caveat : the class must already exist on the site.
Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.
Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way
$('#submitform').click(function() {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType : "html",
success: function (data){
$('#showresults').html($('#showresults',data).html());
// similar to $(data).find('#showresults')
},
});
or with replaceWith()
// codes
success: function (data){
$('#showresults').replaceWith($('#showresults',data));
},
How about:
update table
set columnname = columnname + 1
where id = <some id>
You can use a cast to char to see the date results
select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
Use whichever suits your need.
GridView.count(...)
GridView.count(
crossAxisCount: 2,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.builder(...)
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (_, index) => FlutterLogo(),
itemCount: 4,
)
GridView(...)
GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
GridView.custom(...)
GridView.custom(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
childrenDelegate: SliverChildListDelegate(
[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
),
)
GridView.extent(...)
GridView.extent(
maxCrossAxisExtent: 400,
children: <Widget>[
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
FlutterLogo(),
],
)
Output (same for all):
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
It happens because of the reason mentioned below :
If you see the mvn script: The code fails here ---
Steps for debugging and fixing:
Step 1: Open the mvn script /Users/Username/apache-maven-3.0.5/bin/mvn (Open with the less command like: less /Users/Username/apache-maven-3.0.5/bin/mvn)
Step 2: Find out the below code in the script:
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly."
echo " We cannot execute $JAVACMD"
exit 1
fi
Step3: It is happening because JAVACMD
variable was not set. So it displays the error.
Note: To Fix it
export JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin/java
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/
Key: If you want it to be permanent open emacs .profile
post the commands and press Ctrl-x Ctrl-c ( save-buffers-kill-terminal ).
here is the code
import React, { Component } from 'react';
import logo from './logo.svg';
import './image.css';
import Dropdown from 'react-dropdown';
import axios from 'axios';
let obj = {};
class App extends Component {
constructor(){
super();
this.state = {
selectedFiles: []
}
this.fileUploadHandler = this.fileUploadHandler.bind(this);
}
fileUploadHandler(file){
let selectedFiles_ = this.state.selectedFiles;
selectedFiles_.push(file);
this.setState({selectedFiles: selectedFiles_});
}
render() {
let Images = this.state.selectedFiles.map(image => {
<div className = "image_parent">
<img src={require(image.src)}
/>
</div>
});
return (
<div className="image-upload images_main">
<input type="file" onClick={this.fileUploadHandler}/>
{Images}
</div>
);
}
}
export default App;
between 0 and 100
/^(\d{1,2}|100)$/
or between 1 and 100
/^([1-9]{1,2}|100)$/
The self answer given by MagngooSasa did the trick, but for anyone else trying to understand the answer, here are a few bit more details:
When developing Cordova apps with Visual Studio, I tried to import a remote JavaScript file [located here http://Guess.What.com/MyScript.js], but I have the error mentioned in the title.
Here is the meta tag before, in the index.html file of the project:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
Here is the corrected meta tag, to allow importing a remote script:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;**script-src 'self' http://onlineerp.solution.quebec 'unsafe-inline' 'unsafe-eval';** ">
And no more error!
I ended up finding git attributes
. Trying it. Working so far. Did not check all scenarios yet. But it should be the solution.
Do it in the controller ( controller as syntax below)
controller:
vm.question= {};
vm.question.active = true;
form
<input ng-model="vm.question.active" type="checkbox" id="active" name="active">
You can always create an array of pointers , pointing to car objects and then create objects, in a for loop, as you want and save their address in the array , for example :
#include <iostream>
class Car
{
private:
Car(){};
int _no;
public:
Car(int no)
{
_no=no;
}
void printNo()
{
std::cout<<_no<<std::endl;
}
};
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i<length;i++)
std::cout<<cars[i].printNo();
}
int main()
{
int userInput = 10;
Car **mycars = new Car*[userInput];
int i;
for(i=0;i<userInput;i++)
mycars[i] = new Car(i+1);
note new method !!!
printCarNumbers_new(mycars,userInput);
return 0;
}
All you have to change in new method is handling cars as pointers than static objects in parameter and when calling method printNo() for example :
void printCarNumbers_new(Car **cars, int length)
{
for(int i = 0; i<length;i++)
std::cout<<cars[i]->printNo();
}
at the end of main is good to delete all dynamicly allocated memory like this
for(i=0;i<userInput;i++)
delete mycars[i]; //deleting one obgject
delete[] mycars; //deleting array of objects
Hope I helped, cheers!
I have "experienced" this error on Windows because my name (and hence %HOMEPATH%
) contains a non ascii character (é
). Either git or cmd.exe or anything else could not cope with this.
I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.
#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))
This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it...
public static void callJVisualVM() {
System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
//next search current jdk/jre
String jre_root = null;
String start = "vir";
try {
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
String jvmName = runtime.getName();
System.out.println("JVM Name = " + jvmName);
long pid = Long.valueOf(jvmName.split("@")[0]);
System.out.println("JVM PID = " + pid);
Runtime thisRun = Runtime.getRuntime();
jre_root = System.getProperty("java.home");
System.out.println("jre_root:" + jre_root);
start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
thisRun.exec(start);
} catch (Exception e) {
System.getProperties().list(System.out);
e.printStackTrace();
}
}
Element
objects have no .getroot()
method. Drop that call, and the .tostring()
call works:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
You only need to use .getroot()
if you have an ElementTree
instance.
Other notes:
This produces a bytestring, which in Python 3 is the bytes
type.
If you must have a str
object, you have two options:
Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")
Use encoding='unicode'
; this avoids an encode / decode cycle:
xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8
as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?>
declaration. Use utf-8
or UTF-8
(with a dash) if you want to prevent this. When using encoding="unicode"
no declaration header is added.
The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:
median(x = 1:10)
x
## Error: object 'x' not found
In this case, x
is declared within the scope of the function, so it does not exist in the user workspace.
median(x <- 1:10)
x
## [1] 1 2 3 4 5 6 7 8 9 10
In this case, x
is declared in the user workspace, so you can use it after the function call has been completed.
There is a general preference among the R community for using <-
for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like
x<-3
# Does this mean assignment?
x <- 3
# Or less than?
x < -3
Most R IDEs have keyboard shortcuts to make <-
easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.
If you prefer writing =
to <-
but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_*
functions in the formatR
package to automatically replace =
with <-
.
library(formatR)
tidy_source(text = "x=1:5", arrow = TRUE)
## x <- 1:5
The answer to the question "Why does x <- y = 5
throw an error but not x <- y <- 5
?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether =
or <-
was used.
To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3)
.
Secondly, it's clearer if we use prefix notation for assignment. So
x <- 5
`<-`(x, 5) #same thing
y = 5
`=`(y, 5) #also the same thing
The parser interprets x <- y <- 5
as
`<-`(x, `<-`(y, 5))
We might expect that x <- y = 5
would then be
`<-`(x, `=`(y, 5))
but actually it gets interpreted as
`=`(`<-`(x, y), 5)
This is because =
is lower precedence than <-
, as shown on the ?Syntax
help page.
int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);
this code gives the output as b=3669 only you check it clearly.
POCO stands for "Plain Old CLR Object".
I think you could use Spring's
@Lazy
annotation on one of the autowired fields to break circular dependency.
I'm not sure if this works/exists in mentioned Spring version.
Non of these solutions worked for me. What DID eventually work was checking the string encoding by saving it to a local file and opening with Notepad++. I found out it was 'UTF-16', so I was able to convert it this way:
$str = mb_convert_encoding($str,'UTF-8','UTF-16');
Html a tag
Link in html
<a href="index1.php">page1</a>
<a href="page2.php">page2</a>
Html in php
echo ' <a href="index1.php">page1</a>';
echo '<a href="page2.php">page2</a>';
I had a similar case, what worked for me was:
name.firstChild.childNodes[0].data
XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made
I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.
CSS
@media(min-width: 1400px){
.my-modal > .modal-lg {
width: 1308px;
}
}
JS is the same:
var modal = $modal.open({
animation: true,
templateUrl: 'modalTemplate.html',
controller: 'modalController',
size: 'lg',
windowClass: 'my-modal'
});
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
To be able to use std::unordered_map
(or one of the other unordered associative containers) with a user-defined key-type, you need to define two things:
A hash function; this must be a class that overrides operator()
and calculates the hash value given an object of the key-type. One particularly straight-forward way of doing this is to specialize the std::hash
template for your key-type.
A comparison function for equality; this is required because the hash cannot rely on the fact that the hash function will always provide a unique hash value for every distinct key (i.e., it needs to be able to deal with collisions), so it needs a way to compare two given keys for an exact match. You can implement this either as a class that overrides operator()
, or as a specialization of std::equal
, or – easiest of all – by overloading operator==()
for your key type (as you did already).
The difficulty with the hash function is that if your key type consists of several members, you will usually have the hash function calculate hash values for the individual members, and then somehow combine them into one hash value for the entire object. For good performance (i.e., few collisions) you should think carefully about how to combine the individual hash values to ensure you avoid getting the same output for different objects too often.
A fairly good starting point for a hash function is one that uses bit shifting and bitwise XOR to combine the individual hash values. For example, assuming a key-type like this:
struct Key
{
std::string first;
std::string second;
int third;
bool operator==(const Key &other) const
{ return (first == other.first
&& second == other.second
&& third == other.third);
}
};
Here is a simple hash function (adapted from the one used in the cppreference example for user-defined hash functions):
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
}
With this in place, you can instantiate a std::unordered_map
for the key-type:
int main()
{
std::unordered_map<Key,std::string> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
It will automatically use std::hash<Key>
as defined above for the hash value calculations, and the operator==
defined as member function of Key
for equality checks.
If you don't want to specialize template inside the std
namespace (although it's perfectly legal in this case), you can define the hash function as a separate class and add it to the template argument list for the map:
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using std::size_t;
using std::hash;
using std::string;
return ((hash<string>()(k.first)
^ (hash<string>()(k.second) << 1)) >> 1)
^ (hash<int>()(k.third) << 1);
}
};
int main()
{
std::unordered_map<Key,std::string,KeyHasher> m6 = {
{ {"John", "Doe", 12}, "example"},
{ {"Mary", "Sue", 21}, "another"}
};
}
How to define a better hash function? As said above, defining a good hash function is important to avoid collisions and get good performance. For a real good one you need to take into account the distribution of possible values of all fields and define a hash function that projects that distribution to a space of possible results as wide and evenly distributed as possible.
This can be difficult; the XOR/bit-shifting method above is probably not a bad start. For a slightly better start, you may use the hash_value
and hash_combine
function template from the Boost library. The former acts in a similar way as std::hash
for standard types (recently also including tuples and other useful standard types); the latter helps you combine individual hash values into one. Here is a rewrite of the hash function that uses the Boost helper functions:
#include <boost/functional/hash.hpp>
struct KeyHasher
{
std::size_t operator()(const Key& k) const
{
using boost::hash_value;
using boost::hash_combine;
// Start with a hash value of 0 .
std::size_t seed = 0;
// Modify 'seed' by XORing and bit-shifting in
// one member of 'Key' after the other:
hash_combine(seed,hash_value(k.first));
hash_combine(seed,hash_value(k.second));
hash_combine(seed,hash_value(k.third));
// Return the result.
return seed;
}
};
And here’s a rewrite that doesn’t use boost, yet uses good method of combining the hashes:
namespace std
{
template <>
struct hash<Key>
{
size_t operator()( const Key& k ) const
{
// Compute individual hash values for first, second and third
// http://stackoverflow.com/a/1646913/126995
size_t res = 17;
res = res * 31 + hash<string>()( k.first );
res = res * 31 + hash<string>()( k.second );
res = res * 31 + hash<int>()( k.third );
return res;
}
};
}
You have forgotten a *
between -3.7
and (prof[x])
.
Thus:
for x in range(len(prof)):
PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))
Also, there seems to be missing an (
as I count 6 times (
and 7 times )
, and I think (math.e, (0/2.25))
is missing a function call (probably math.pow
, but thats just a wild guess).
Not for entire application or particular class.
CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture
at all.
Sample code to change cultures for current thread:
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:
(3.3).ToString(new CultureInfo("fr-FR"))
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
I use to detect Apple browser engine, this simple JavaScript condition:
navigator.vendor.startsWith('Apple')
Other folks have suggested array_search()
which gives the key of the array element where the value is found. You can ensure that the array keys are contiguous integers by using array_values()
:
$list = array(0=>'string1', 'foo'=>'string2', 42=>'string3');
$index = array_search('string2', array_values($list));
print "$index\n";
// result: 1
You said in your question that array_search()
was no use. Can you explain why? What did you try and how did it not meet your needs?
implementation 'com.treebo:internetavailabilitychecker:1.0.4'
InternetConnectivityListener
.public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InternetAvailabilityChecker.init(this);
mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
mInternetAvailabilityChecker.addInternetConnectivityListener(this);
}
@Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" internet is connected or not");
alertDialog.setMessage("connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
else {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet is connected or not");
alertDialog.setMessage("not connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
Even though this is an old question, I had to do something similar today but I prefer JSTL:
<c:forEach var="par" items="${paramValues}">
<c:if test="${fn:startsWith(par.key, 'question')}">
${par.key} = ${par.value[0]}; //whatever
</c:if>
</c:forEach>
it work in my case, oldSensor and newSnsor - oldView and newView:
private void replaceSensors(View oldSensor, View newSensor) {
ViewGroup parent = (ViewGroup) oldSensor.getParent();
if (parent == null) {
return;
}
int indexOldSensor = parent.indexOfChild(oldSensor);
int indexNewSensor = parent.indexOfChild(newSensor);
parent.removeView(oldSensor);
parent.addView(oldSensor, indexNewSensor);
parent.removeView(newSensor);
parent.addView(newSensor, indexOldSensor);
}
For those who were having trouble parsing other answers:
eval "for _,k in ipairs(redis.call('keys','key:*:pattern')) do redis.call('del',k) end" 0
Replace key:*:pattern
with your own pattern and enter this into redis-cli
and you are good to go.
Credit lisco from: http://redis.io/commands/del
I felt a like I needed to share this manipulated code to the accepted answer - as I have no reputation, I'm unable to comment..
using System;
using System.Xml.Serialization;
using System.IO;
namespace ObjectSerialization
{
public static class ObjectSerialization
{
// THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
/// <summary>
/// A helper to serialize an object to a string containing XML data of the object.
/// </summary>
/// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
/// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
/// <returns>A string containing XML data of the object.</returns>
public static string SerializeObject<T>(this T toSerialize)
{
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
// using is necessary with classes which implement the IDisposable interface..
using (StringWriter stringWriter = new StringWriter())
{
// serialize a class to a StringWriter class instance..
xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
return stringWriter.ToString(); // return the value..
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
/// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
/// </summary>
/// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
/// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
{
// if a null instance of an object called this try to create a "default" instance for it with typeof(T),
// this will throw an exception no useful constructor is found..
object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return (T)xmlSerializer.Deserialize(stringReader);
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string.
/// </summary>
/// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static object DeserializeObject(Type toDeserialize, string xmlData)
{
// create an instance of a XmlSerializer class with the given type toDeserialize..
XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return xmlSerializer.Deserialize(stringReader);
}
}
}
}
I think the simplest way which worked for me to find Command line tools is installed or not and its version irrespective of what macOS version is
$brew config
macOS: 10.14.2-x86_64
CLT: 10.1.0.0.1.1539992718
Xcode: 10.1
This when you have Command Line tools properly installed and paths set properly.
Earlier i got output as below
macOS: 10.14.2-x86_64
CLT: N/A
Xcode: 10.1
CLT was shown as N/A in spite of having gcc and make working fine and below outputs
$xcode-select -p
/Applications/Xcode.app/Contents/Developer
$pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
$brew doctor
Your system is ready to brew.
Finally doing xcode-select --install resolved my issue of brew unable to find CLT for installing packages as below.
Installing sphinx-doc dependency: python
Warning: Building python from source:
The bottle needs the Apple Command Line Tools to be installed.
You can install them, if desired, with:
xcode-select --install
Blast from the past but I think I found an easy answer to this. The following worked for me. I think it's the equivalent of selecting the cell hitting F2 and then hitting enter, which makes Excel recognize the text as a date.
Columns("A").Select
Selection.Value = Selection.Value
The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:
IN | OUT | TOT | LEAF | INT
1 | 1 | 1 | 1 | 0
2 | 1 | 1 | 1 | 0
3 | 2 | 3 | 2 | 1
4 | 3 | 5 | 3 | 2
5 | 5 | 9 | 5 | 4
6 | 8 | 15 | 8 | 7
7 | 13 | 25 | 13 | 12
8 | 21 | 41 | 21 | 20
9 | 34 | 67 | 34 | 33
10 | 55 | 109 | 55 | 54
What immediately leaps out is that the number of leaf nodes is fib(n)
. What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1
. Therefore the total number of nodes is 2 * fib(n) - 1
.
Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n))
.
try this
Calendar c = Calendar.getInstance();
int mseconds = c.get(Calendar.MILLISECOND)
an alternative would be
Calendar rightNow = Calendar.getInstance();
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMid = (rightNow.getTimeInMils() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMid + " milliseconds since midnight");
An alternative that I used instead of FFServer was Red5 Pro, on Ubuntu, I used this line:
ffmpeg -f pulse -i default -f video4linux2 -thread_queue_size 64 -framerate 25 -video_size 640x480 -i /dev/video0 -pix_fmt yuv420p -bsf:v h264_mp4toannexb -profile:v baseline -level:v 3.2 -c:v libx264 -x264-params keyint=120:scenecut=0 -c:a aac -b:a 128k -ar 44100 -f rtsp -muxdelay 0.1 rtsp://localhost:8554/live/paul
SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
(SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
ON t1.ProdId = t2.ProdId
AND t1.Quantity = t2.MaxQuantity
ORDER BY t1.ProdId
this will give you the idea.
Stack:
Heap:
delete
, delete[]
, or free
.new
or malloc
respectively.Example:
int foo()
{
char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
bool b = true; // Allocated on the stack.
if(b)
{
//Create 500 bytes on the stack
char buffer[500];
//Create 500 bytes on the heap
pBuffer = new char[500];
}//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;
It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.
This will work:
DECLARE @MyValue NVarChar(4000) = 'something';
SELECT S.name SchemaName, T.name TableName
INTO #T
FROM sys.schemas S INNER JOIN
sys.tables T ON S.schema_id = T.schema_id;
WHILE (EXISTS (SELECT * FROM #T)) BEGIN
DECLARE @SQL NVarChar(4000) = 'SELECT * FROM $$TableName WHERE (0 = 1) ';
DECLARE @TableName NVarChar(1000) = (
SELECT TOP 1 SchemaName + '.' + TableName FROM #T
);
SELECT @SQL = REPLACE(@SQL, '$$TableName', @TableName);
DECLARE @Cols NVarChar(4000) = '';
SELECT
@Cols = COALESCE(@Cols + 'OR CONVERT(NVarChar(4000), ', '') + C.name + ') = CONVERT(NVarChar(4000), ''$$MyValue'') '
FROM sys.columns C
WHERE C.object_id = OBJECT_ID(@TableName);
SELECT @Cols = REPLACE(@Cols, '$$MyValue', @MyValue);
SELECT @SQL = @SQL + @Cols;
EXECUTE(@SQL);
DELETE FROM #T
WHERE SchemaName + '.' + TableName = @TableName;
END;
DROP TABLE #T;
A couple caveats, though. First, this is outrageously slow and non-optimized. All values are being converted to nvarchar
simply so that they can be compared without error. You may run into problems with values like datetime
not converting as expected and therefore not being matched when they should be (false negatives).
The WHERE (0 = 1)
is there to make building the OR
clause easier. If there are not matches you won't get any rows back.
When you try to access it as $result['context']
, you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context
Thank you for the suggested solutions! Unfortunately, none of them worked for my case: receiving a list of CLOB objects from Oracle database through JPA - Hibernate, using a native query.
All of the proposed approaches gave me either a ClassCastException or just returned java Proxy object (which deeply inside contained the desired Clob).
So my solution is the following (based on several above approaches):
Query sqlQuery = manager.createNativeQuery(queryStr);
List resultList = sqlQuery.getResultList();
for ( Object resultProxy : resultList ) {
String unproxiedClob = unproxyClob(resultProxy);
if ( unproxiedClob != null ) {
resultCollection.add(unproxiedClob);
}
}
private String unproxyClob(Object proxy) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
Method readMethod = property.getReadMethod();
if ( readMethod.getName().contains("getWrappedClob") ) {
Object result = readMethod.invoke(proxy);
return clobToString((Clob) result);
}
}
}
catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException e) {
LOG.error("Unable to unproxy CLOB value.", e);
}
return null;
}
private String clobToString(Clob data) throws SQLException, IOException {
StringBuilder sb = new StringBuilder();
Reader reader = data.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String line;
while( null != (line = br.readLine()) ) {
sb.append(line);
}
br.close();
return sb.toString();
}
Hope this will help somebody!
While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.
example:
$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();
if ($proc.ExitCode -ne 0) {
Write-Warning "$_ exited with status code $($proc.ExitCode)"
}
For a sanity check, try creating a new Web Application Project, open the code behind for the Default.aspx page. Add a line in Page_Load to access your connection string.
It should have System.Configuration added as reference by default. You should also see the using statement at the top of your code file already.
My code behind file now looks like this and compiles with no problems.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
}
}
}
This assumes I have a connection string in my web.config with a name equal to "MyConnectionStringName" like so...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="MyConnectionStringName"
connectionString="Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Yeah, it's elementary I know. But if you don't have any better ideas sometimes it helps to check against something really simple that you know should work.
Reset XAMPP MySQL root password through SQL update phpmyadmin to work with it:
-Start the Apache Server and MySQL instances from the XAMPP control panel. After the server started, open any web browser and go to http://localhost/phpmyadmin/. This will open the phpMyAdmin interface. Using this interface we can manager the MySQL server from the web browser.
-In the phpMyAdmin window, select SQL tab from the right panel. This will open the SQL tab where we can run the SQL queries.
-Now type the following query in the textarea and click Go
"UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';"
hit go
"FLUSH PRIVILEGES;"
hit go
-Now you will see a message saying that the query has been executed successfully.
-If you refresh the page, you will be getting a error message. This is because the phpMyAdmin configuration file is not aware of our newly set root passoword. To do this we have to modify the phpMyAdmin config file.
-Open the file C:\xampp\phpMyAdmin\config.inc.php in your favorite text editor. Search for the string:
$cfg\['Servers'\]\[$i\]['password'] = ''; and change it to like this,
$cfg\['Servers'\]\[$i\]['password'] = 'password'; Here the ‘password’ is what we set to the root user using the SQL query.
$cfg['Servers'][$i]['AllowNoPassword'] = false; // set to false for password required
$cfg['Servers'][$i]['auth_type'] = 'cookie'; // web cookie auth
-Now all set to go. Save the config.inc.php file and restart the XAMPP server.
Modified from Source: http://veerasundar.com/blog/2009/01/how-to-change-the-root-password-for-mysql-in-xampp/
CN refers to class name, so put in your LDAP query CN=Users. Should work.
To change into another directory use WORKDIR. All the RUN, CMD and ENTRYPOINT commands after WORKDIR will be executed from that directory.
RUN git clone XYZ
WORKDIR "/XYZ"
RUN make
Finally, Works!
Put smtpClient.UseDefaultCredentials = false;
after smtpClient.Credentials = credentials;
then problem resolved!
SmtpClient smtpClient = new SmtpClient(smtpServerName);
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpUName, smtpUNamePwd);
smtpClient.Credentials = credentials;
smtpClient.UseDefaultCredentials = false; <-- Set This Line After Credentials
smtpClient.Send(mailMsg);
smtpClient = null;
mailMsg.Dispose();
Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach
that is not an array.
Look at what you're passing into foreach
, determine what it is (with var_export
), find out why it's not an array... and fix it.
Basic, basic debugging.
Using Google Collections:
class Person {
private int age;
public static Function<Person, Integer> GET_AGE =
new Function<Person, Integer> {
public Integer apply(Person p) { return p.age; }
};
}
public static void main(String[] args) {
ArrayList<Person> people;
// Populate the list...
Collections.sort(people, Ordering.natural().onResultOf(Person.GET_AGE).reverse());
}
Winand, Quality was also an issue for me so I did this:
For Each ws In ActiveWorkbook.Worksheets
If ws.PageSetup.PrintArea <> "" Then
'Reverse the effects of page zoom on the exported image
zoom_coef = 100 / ws.Parent.Windows(1).Zoom
areas = Split(ws.PageSetup.PrintArea, ",")
areaNo = 0
For Each a In areas
Set area = ws.Range(a)
' Change xlPrinter to xlScreen to see zooming white space
area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
chartobj.Chart.Paste
'scale the image before export
ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
chartobj.delete
areaNo = areaNo + 1
Next
End If
Next
See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/
Based on https://github.com/antonyt/InfiniteViewPager I wrote up this which works nicely:
class InfiniteViewPager @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
// Allow for 100 back cycles from the beginning.
// This should be enough to create an illusion of infinity.
// Warning: scrolling to very high values (1,000,000+) results in strange drawing behaviour.
private val offsetAmount get() = if (adapter?.count == 0) 0 else (adapter as InfinitePagerAdapter).realCount * 100
override fun setAdapter(adapter: PagerAdapter?) {
super.setAdapter(if (adapter == null) null else InfinitePagerAdapter(adapter))
currentItem = 0
}
override fun setCurrentItem(item: Int) = setCurrentItem(item, false)
override fun setCurrentItem(item: Int, smoothScroll: Boolean) {
val adapterCount = adapter?.count
if (adapterCount == null || adapterCount == 0) {
super.setCurrentItem(item, smoothScroll)
} else {
super.setCurrentItem(offsetAmount + item % adapterCount, smoothScroll)
}
}
override fun getCurrentItem(): Int {
val adapterCount = adapter?.count
return if (adapterCount == null || adapterCount == 0) {
super.getCurrentItem()
} else {
val position = super.getCurrentItem()
position % (adapter as InfinitePagerAdapter).realCount
}
}
fun animateForward() {
super.setCurrentItem(super.getCurrentItem() + 1, true)
}
fun animateBackwards() {
super.setCurrentItem(super.getCurrentItem() - 1, true)
}
internal class InfinitePagerAdapter(private val adapter: PagerAdapter) : PagerAdapter() {
internal val realCount: Int get() = adapter.count
override fun getCount() = if (realCount == 0) 0 else Integer.MAX_VALUE
override fun instantiateItem(container: ViewGroup, position: Int) = adapter.instantiateItem(container, position % realCount)
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) = adapter.destroyItem(container, position % realCount, `object`)
override fun finishUpdate(container: ViewGroup) = adapter.finishUpdate(container)
override fun isViewFromObject(view: View, `object`: Any) = adapter.isViewFromObject(view, `object`)
override fun restoreState(bundle: Parcelable?, classLoader: ClassLoader?) = adapter.restoreState(bundle, classLoader)
override fun saveState(): Parcelable? = adapter.saveState()
override fun startUpdate(container: ViewGroup) = adapter.startUpdate(container)
override fun getPageTitle(position: Int) = adapter.getPageTitle(position % realCount)
override fun getPageWidth(position: Int) = adapter.getPageWidth(position)
override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) = adapter.setPrimaryItem(container, position, `object`)
override fun unregisterDataSetObserver(observer: DataSetObserver) = adapter.unregisterDataSetObserver(observer)
override fun registerDataSetObserver(observer: DataSetObserver) = adapter.registerDataSetObserver(observer)
override fun notifyDataSetChanged() = adapter.notifyDataSetChanged()
override fun getItemPosition(`object`: Any) = adapter.getItemPosition(`object`)
}
}
For consuming it simply change your ViewPager to InfiniteViewPager and that's all you need to change.
A simple work around(it worked for me) is use the IP address instead of localhost. This should be fine for your development tasks.
Personally this query has solved my problem:
SELECT `SUB_ID`, COUNT(SRV_KW_ID) as subscriptions FROM `SUB_SUBSCR` group by SUB_ID, SRV_KW_ID HAVING subscriptions > 1;
What this script does is showing all the subscriber ID's that exists more than once into the table and the number of duplicates found.
This are the table columns:
| SUB_SUBSCR_ID | int(11) | NO | PRI | NULL | auto_increment |
| MSI_ALIAS | varchar(64) | YES | UNI | NULL | |
| SUB_ID | int(11) | NO | MUL | NULL | |
| SRV_KW_ID | int(11) | NO | MUL | NULL | |
Hope it will be helpful for you either!
Go strings are not null terminated, and to remove the last char of a string you can simply do:
s = s[:len(s)-1]
Installing the following packages:
adds MySQL Database to the data sources list (Visual Studio 2017)
You have to use RegExp object if your pattern is string
var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);
If pattern is not dynamic string:
var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);
...this reproduced the error:
$foo = 'bar';
$foo[0] = 'bar';
...this reproduced the error:
$foo = 'bar';
if (is_array($foo['bar']))
echo 'bar-array';
if (is_array($foo['bar']['foo']))
echo 'bar-foo-array';
if (is_array($foo['bar']['foo']['bar']))
echo 'bar-foo-bar-array';
(From bugs.php.net actually)
so why doesn't the error appear in the first if condition even though it is a string.
Because PHP is a very forgiving programming language, I'd guess. I'll illustrate with code of what I think is going on:
$foo = 'bar';
// $foo is now equal to "bar"
$foo['bar'] = 'foo';
// $foo['bar'] doesn't exists - use first index instead (0)
// $foo['bar'] is equal to using $foo[0]
// $foo['bar'] points to a character so the string "foo" won't fit
// $foo['bar'] will instead be set to the first index
// of the string/array "foo", i.e 'f'
echo $foo['bar'];
// output will be "f"
echo $foo;
// output will be "far"
echo $foo['bar']['bar'];
// $foo['bar'][0] is equal calling to $foo['bar']['bar']
// $foo['bar'] points to a character
// characters can not be represented as an array,
// so we cannot reach anything at position 0 of a character
// --> fatal error
If you don't feel like importing anything, you can try:
raise SystemExit, 0