I faced the same issue when I created a new react app, I tried all options in https://github.com/facebook/create-react-app/issues/2534 but it didn't help. I had to change the port for the new app and then it worked. By default, apps use the port 3000.I changed the port to 8001 in package.json as follows:
"scripts": {
"start": "PORT=8001 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
I've changed the recursion to iteration.
def MovingTheBall(listOfBalls,position,numCell):
while 1:
stop=1
positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
for i in range(0,len(listOfBalls)):
if positionTmp==listOfBalls[i].pos:
stop=0
if stop==1:
if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
stop=0
else:
return positionTmp
Works good :D
import pickle
f=open("filename.dat","rb")
try:
while True:
x=pickle.load(f)
print x
except EOFError:
pass
f.close()
Code to check whether two elements exist in array whose product equals k:
n = len(arr1)
for i in arr1:
if k%i==0:
print(i)
Python implicitly passes the object to method calls, but you need to explicitly declare the parameter for it. This is customarily named self
:
def updateVelocity(self):
You can just insert the following in to your main html page, or a function:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
Then to remove the margins on the page
html, body {
margin: 0 !important;
padding: 0 !important;
}
That should do the job
$('input[name="mygroup"]').val([5])
Such margin can be achieved by setting leftView
/ rightView
to UITextField
.
Updated For Swift 4
// Create a padding view for padding on left
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.leftViewMode = .always
// Create a padding view for padding on right
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
textField.rightViewMode = .always
I just added/placed an UIView
to left and right side of the textfield. So now the typing will start after the view.
Thanks
Hope this helped...
A pure python oneliner for cumulative sum:
cumsum = lambda X: X[:1] + cumsum([X[0]+X[1]] + X[2:]) if X[1:] else X
This is a recursive version inspired by recursive cumulative sums. Some explanations:
X[:1]
is a list containing the previous element and is almost the same as [X[0]]
(which would complain for empty lists).cumsum
call in the second term processes the current element [1]
and remaining list whose length will be reduced by one.if X[1:]
is shorter for if len(X)>1
.Test:
cumsum([4,6,12])
#[4, 10, 22]
cumsum([])
#[]
And simular for cumulative product:
cumprod = lambda X: X[:1] + cumprod([X[0]*X[1]] + X[2:]) if X[1:] else X
Test:
cumprod([4,6,12])
#[4, 24, 288]
To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.
Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y
But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.
An advantage of Qgram index technique is it supports for Fuzzy Search.
One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this. Following is a small example on storing of terms
col : colmbia, colombo, gancola, tacolama
Then when querying, we calculate the number of common Qgrams between query text and available terms.
Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4
number of q-grams in common = 4.
For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.
you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search
To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)
Simple way:
Fox example this is your html,
<div class='classname' id='your_id_name'>
</div>
Jquery code:
if($('.classname').prop('id')=='your_id_name')
{
//works your_id_name exist (true part)
}
else
{
//works your_id_name not exist (false part)
}
No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps
1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option.
3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.
Above process was to make build manually. If You want android studio to automatically Signing Your App
In Android Studio, you can configure your project to sign your release APK automatically during the build process:
On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. Figure 4. Create a signing configuration in Android Studio.
Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. Figure 5. Select a signing configuration in Android Studio.
4:Most Important thing that make debuggable=false at gradle.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard- android.txt'), 'proguard-rules.txt'
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
visit for more in info developer.android.com
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html
Things you need to be aware of:
Take a look at AlarmManager
, if you need scheduled execution of your code.
Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?
ydiff
Formerly called cdiff
, this tool can display side by side, incremental, and colorful diff.
Instead of doing git diff
, do:
ydiff -s -w0
This will launch ydiff
in side-by-side display mode for each of the files with differences.
Install with:
python3 -m pip install --user ydiff
-or-
brew install ydiff
For git log
, you can use:
ydiff -ls -w0
-w0
auto-detects your terminal width. See the ydiff
GitHub repository page for detail and demo.
Tested in Git 2.18.0, ydiff 1.1.
The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources
.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;
public class ImageDownloader
{
public static void main(String[] arguments) throws IOException
{
downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
new File("").getAbsolutePath());
}
public static void downloadImage(String sourceUrl, String targetDirectory)
throws MalformedURLException, IOException, FileNotFoundException
{
URL imageUrl = new URL(sourceUrl);
try (InputStream imageReader = new BufferedInputStream(
imageUrl.openStream());
OutputStream imageWriter = new BufferedOutputStream(
new FileOutputStream(targetDirectory + File.separator
+ FilenameUtils.getName(sourceUrl)));)
{
int readByte;
while ((readByte = imageReader.read()) != -1)
{
imageWriter.write(readByte);
}
}
}
}
var newTH = document.createElement('th');
newTH.onclick = function() {
//Your code here
}
Here comes a solution with XSLT
:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//element3">
<xsl:value-of select="element4/text()" />.<xsl:value-of select="element5/text()" />
</xsl:template>
</xsl:stylesheet>
you can use
empty($result)
to check if the main array is empty or not.
But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php
ex:
if (empty($result) || !isset($result['Tags'])) {
return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
return false;
}
return ($result['Tags']->count());
Swift 5.0, 4.0, 3.0 Updated Solution
Insert at Bottom
self.yourArray.append(msg)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()
Insert at Top of TableView
self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()
you can't force refresh but you can forward all old ip requests to new one. for a website:
replace [OLD_IP] with old server's ip
replace [NEW_IP] with new server's ip
run & win.
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
This:
SELECT col1 as a,
CASE WHEN a = 'test' THEN 'yes' END as value
FROM table;
...will not work. This will:
SELECT CASE WHEN a = 'test' THEN 'yes' END as value
FROM (SELECT col1 AS a
FROM TABLE)
Why you wouldn't use:
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
...I don't know.
you could do this, if you want to use the old syntax (or don't want to rewrite every template)
@for $i from 1 through $grid-columns {
@include media-breakpoint-up(xs) {
.col-xs-#{$i} {
@include make-col-ready();
@include make-col($i);
}
}
}
Its easy, dont Align it to anything
<Button_x000D_
android:id="@+id/the_button"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content" _x000D_
android:layout_centerInParent="true"_x000D_
android:text="Centered Button"/>
_x000D_
I had the same problem and setting the uploadReadAheadSize
solved it:
http://www.iis.net/configreference/system.webserver/serverruntime
"The value must be between 0 and 2147483647."
It is easily set it in the applicationHost.config-fle if you don't want to do a cmd-thing.
Its located in WindowsFOLDER\System32\inetsrv\config
(2008 server).
You must open it with notepad. Do a Backup of the file first.
According to the comments in config the recommended way to unlock sections is by using a location tag:
<location path="Default Web Site" overrideMode="Allow">
<system.webServer>
<asp />
</system.webServer>
</location>"
So you can write in the bottom (since it doesn't exist before). I write maxvalue
here - write your own value if you want.
<location path="THENAMEOFTHESITEYOUHAVE" overrideMode="Allow">
<system.webServer>
<asp />
<serverRuntime uploadReadAheadSize="2147483647" />
</system.webServer>
</location>
If you put it last before </configuration>
for example, you know where you have it.
Hope that solves your problems. It was an SSL overhead issue for me, where too much post freezed the application, raising a (413) Request Entity Too Large error.
You cannot create migration scripts for existing models.
Resources:
If going the classic way, you'll have to recreate the models via the CLI:
sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text
It will generate these files:
models/myuser.js:
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
var MyUser = sequelize.define("MyUser", {_x000D_
first_name: DataTypes.STRING,_x000D_
last_name: DataTypes.STRING,_x000D_
bio: DataTypes.TEXT_x000D_
}, {_x000D_
classMethods: {_x000D_
associate: function(models) {_x000D_
// associations can be defined here_x000D_
}_x000D_
}_x000D_
});_x000D_
return MyUser;_x000D_
};
_x000D_
migrations/20150210104840-create-my-user.js:
"use strict";_x000D_
module.exports = {_x000D_
up: function(migration, DataTypes, done) {_x000D_
migration.createTable("MyUsers", {_x000D_
id: {_x000D_
allowNull: false,_x000D_
autoIncrement: true,_x000D_
primaryKey: true,_x000D_
type: DataTypes.INTEGER_x000D_
},_x000D_
first_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
last_name: {_x000D_
type: DataTypes.STRING_x000D_
},_x000D_
bio: {_x000D_
type: DataTypes.TEXT_x000D_
},_x000D_
createdAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
},_x000D_
updatedAt: {_x000D_
allowNull: false,_x000D_
type: DataTypes.DATE_x000D_
}_x000D_
}).done(done);_x000D_
},_x000D_
down: function(migration, DataTypes, done) {_x000D_
migration.dropTable("MyUsers").done(done);_x000D_
}_x000D_
};
_x000D_
As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $
whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.
$location / switching between html5 and hashbang mode / link rewriting
Try this:
function createcodes() {
$('.authors-list tr').each(function () {
//processing this row
//how to process each cell(table td) where there is checkbox
$(this).find('td input:checked').each(function () {
// it is checked, your code here...
});
});
}
Make sure to be careful when editing your model file. For example, in your post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $table = 'posts';
}
You need to pay close attention to the class Post extend Model
line. The class Post
defined here will be your namespace for your controller.
you have to do
sSource.replaceAll("\\\\/", "/");
because the backshlash should be escaped twice one for string in source one in regular expression
create a package protected (assumes test class in same package) method in the sub class that calls the super class method and then call that method in your overridden sub class method. you can then set expectations on this method in your test through the use of the spy pattern. not pretty but certainly better than having to deal with all the expectation setting for the super method in your test
The preceding 0 is used to indicate a number in base 2, 8, or 16.
In my opinion, 0x was chosen to indicate hex because 'x' sounds like hex.
Just my opinion, but I think it makes sense.
Good Day!
I think it is dangerous to use $.isEmptyObject from jquery to check whether the array is empty, as @jesenko mentioned. I just met that problem.
In the isEmptyObject doc, it mentions:
The argument should always be a plain JavaScript Object
which you can determine by $.isPlainObject
. The return of $.isPlainObject([])
is false.
Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.
https://github.com/marcj/css-element-queries
It contains a ResizeSensor class you can use for that purpose.
new ResizeSensor(jQuery('#mainContent'), function(){
console.log('main content dimension changed');
});
Disclaimer: I wrote this library
In psql alter column query syntax like this
Alter table users add column priv_user boolean default false ;
boolean value (true-false) save in DB like (t-f) value .
Just write this line:
System.IO.Directory.CreateDirectory("my folder");
Reference: Article about Directory.CreateDirectory at MSDN
Of course, you can also write using System.IO;
at the top of the source file and then just write Directory.CreateDirectory("my folder");
every time you want to create a folder.
If you want to increase your heap space, you can use java -Xms<initial heap size> -Xmx<maximum heap size>
on the command line. By default, the values are based on the JRE version and system configuration. You can find out more about the VM options on the Java website.
However, I would recommend profiling your application to find out why your heap size is being eaten. NetBeans has a very good profiler included with it. I believe it uses the jvisualvm
under the hood. With a profiler, you can try to find where many objects are being created, when objects get garbage collected, and more.
https://usefulaspandcsharp.wordpress.com/tag/session-timeout/
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ASPXFORMSAUTH" timeout="60" slidingExpiration="true" />
</authentication>
<sessionState mode="InProc" timeout="60" />
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for(double a : data)
sum += a;
return sum/size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for(double a :data)
temp += (a-mean)*(a-mean);
return temp/(size-1);
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if (data.length % 2 == 0)
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
return data[data.length / 2];
}
}
Not sure if I get you right, but the simplest way would be something like:
<c:if test="${languageBean.locale == 'en'">
<f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>
Just a quick copy and paste from an app of mine...
HTH
This also happens when the Response-Type is not public! I returned an internal class as I used Visual Studio to generate me the type.
internal class --> public class
I know that some may want to smack me for re-opening old post, but if you feel so do it I just hope this may help someone else trying to set JDK 7 on Mac OS (using IntelliJ).
What I did to get this working on my machine is to:
If you are using Underscore JS, just use :
var result = _.chunk(arr,elements_per_chunk)
Most projects already use underscore as a dependency, anyways.
This is a more abstract method:
super(self.__class__,self).baz(arg)
It is a defect of Selenium.
I have the same problem in Ubuntu 12.04 behind the proxy.
Problem is in incorrect processing proxy exclusions. Default Ubuntu exclusions are located in no_proxy environment variable:
no_proxy=localhost,127.0.0.0/8
But it seems that /8 mask doesn't work for selenium. To workaround the problem it is enough to change no_proxy to the following:
no_proxy=localhost,127.0.0.1
Removing proxy settings before running python script also helps:
http_proxy= python script.py
DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = (TestRunner)Activator.CreateInstance(type);
obj.Run();
}
}
Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...
Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.
With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.
These declarations are very similar (but not the same - e.g., sizeof
will return different values):
char* a = "Hello";
char a[] = "Hello";
You can reach any element in the array like this
printf("Second char is: %c", a[1]);
Index 1 since the array starts with element 0. :-)
Or you could equally do this
printf("Second char is: %c", *(a+1));
The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:
printf("Second char is: %s", (a+1)); /* WRONG */
But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?
char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);
This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).
Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:
char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);
Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
torch.reshape() is made to dupe the numpy reshape method.
It came after the view() and torch.resize_() and it is inside the dir(torch)
package.
import torch
x=torch.arange(24)
print(x, x.shape)
x_view = x.view(1,2,3,4) # works on is_contiguous() tensor
print(x_view.shape)
x_reshaped = x.reshape(1,2,3,4) # works on any tensor
print(x_reshaped.shape)
x_reshaped2 = torch.reshape(x_reshaped, (-1,)) # part of torch package, while view() and resize_() are not
print(x_reshaped2.shape)
Out:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23]) torch.Size([24])
torch.Size([1, 2, 3, 4])
torch.Size([1, 2, 3, 4])
torch.Size([24])
But did you know it can also work as a replacement for squeeze() and unsqueeze()
x = torch.tensor([1, 2, 3, 4])
print(x.shape)
x1 = torch.unsqueeze(x, 0)
print(x1.shape)
x2 = torch.unsqueeze(x1, 1)
print(x2.shape)
x3=x.reshape(1,1,4)
print(x3.shape)
x4=x.reshape(4)
print(x4.shape)
x5=x3.squeeze()
print(x5.shape)
Out:
torch.Size([4])
torch.Size([1, 4])
torch.Size([1, 1, 4])
torch.Size([1, 1, 4])
torch.Size([4])
torch.Size([4])
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
The formula is
minSdkVersion <= targetSdkVersion <= compileSdkVersion
minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.
targetSdkVersion - If AndroidOS version is >=
targetSdkVersion
it says Android system to turn on specific(new) behavior
changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion
is <
, you should read official doc.
For example:
Starting in Android 6.0 (API level 23) Runtime Permissions
were introduced. If you set targetSdkVersion
to 22 or lower your application does not ask a user for some permission in run time.
Starting in Android 8.0 (API level 26), all notifications
must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).
Starting in Android 9 (API level 28), Web-based data directories separated by process
. If targetSdkVersion
is 28+ and you create several WebView
in different processes you will get java.lang.RuntimeException
compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java
files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion
- level 28. compileSdkVersion
is not included in your APK: it is purely used at compile time
. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version
You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
Log4j or slf4j can also be used as logging frameworks in Android together with logcat. See the project android-logging-log4j or log4j support in android
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
You can use the setTimeout
or setInterval
functions.
df[df['B']==3]['A']
, assuming df is your pandas.DataFrame.
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Don't forget to set table name da.Fill(ds,"tablename");
So you return data using table name instead of 0
if (ds.Tables["tablename"].Rows.Count == 0)
{
MessageBox.Show("No result found");
}
package com.keshav.datePicker_With_Hide_Future_Past_Date;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
EditText ed_date;
int year;
int month;
int day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_date=(EditText) findViewById(R.id.et_date);
ed_date.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
final DatePickerDialog mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
int month_k=selectedmonth+1;
}
},year, month, day);
mDatePicker.setTitle("Please select date");
// TODO Hide Future Date Here
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
// TODO Hide Past Date Here
// mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
mDatePicker.show();
}
});
}
}
// Its Working
Let's say you have a tag someplace on the page which contains your loading message:
<div id='loadingmessage' style='display:none'>
<img src='loadinggraphic.gif'/>
</div>
You can add two lines to your ajax call:
function getData(p){
var page=p;
$('#loadingmessage').show(); // show the loading message.
$.ajax({
url: "loadData.php?id=<? echo $id; ?>",
type: "POST",
cache: false,
data: "&page="+ page,
success : function(html){
$(".content").html(html);
$('#loadingmessage').hide(); // hide the loading message
}
});
This is kind of hacky, but it works.
I used JavascriptExecutor
and added a div
to the HTML, and changed the text in the div
to $('#prettyTime').val()
I then used Selenium to retrieve the div
and grab its value. After testing the correctness of the value, I removed the div that was just created.
You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.
The trick with img::after
is a good stuff, but has at least 2 downsides:
I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:
img:-moz-broken{
opacity: 0;
}
I had the same problem on Ubuntu
and the other solutions didn't help me.
I finally realized what my problem was. I had created my ssh
keys in /root/.ssh
folder, So even when I ran ssh-add
as root, it couldn't do its work and keep saying
Could not open a connection to your authentication agent.
I created my ssh public and private keys in /home/myUsername/
folder and I used
ssh-agent /bin/sh
then I ran
ssh-add /home/myUsername/.ssh/id_rsa
and problem was solved this way.
Note: For accessing your repository on git
add your git password when you are creating ssh
keys with ssh-keygen -t rsa -C "your git email here"
.
If you want maximum performance when doing conversion from hex to decimal number, you can use the approach with pre-populated table of hex-to-decimal values.
Here is the code that illustrates that idea. My performance tests showed that it can be 20%-40% faster than Convert.ToInt32(...):
class TableConvert
{
static sbyte[] unhex_table =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
public static int Convert(string hexNumber)
{
int decValue = unhex_table[(byte)hexNumber[0]];
for (int i = 1; i < hexNumber.Length; i++)
{
decValue *= 16;
decValue += unhex_table[(byte)hexNumber[i]];
}
return decValue;
}
}
This is how you access the dictionary to do what you want:
list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for age in list:
if list[age] == search_age:
print age
of course, your names are so off it looks like it would be printing an age, but it DOES print the name. Since you are accessing by name, it becomes more understandable if you write:
list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for name in list:
if list[name] == search_age:
print name
Better yet:
people = {'george': {'age': 16}, 'amber': {'age': 19}}
search_age = raw_input("Provide age")
for name in people:
if people[name]['age'] == search_age:
print name
The simplest answer to this problem is specifying the correct path to flask in your environment. Make sure the script you are running knows how to get to the flask installation. Using print(sys.path) as mentioned above certainly helped to figure out the path(s) the script was using.
The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T>
and a T[]
can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.
For example, suppose you have a List<string>
and wish to have every string in the list which starts with T
be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:
int srcPtr,destPtr;
string[] arr;
srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
string st = arr[srcPtr];
char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
if (ch != 'U')
arr[destPtr++] = st;
if (ch == 'T')
arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
theList = new List<String>(arr); // Adds extra elements
if (destPtr != arr.Length)
theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
Array.Resize(ref arr, destPtr);
theList = new List<String>(arr); // Adds extra elements
}
It would have been helpful if List<T>
provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.
The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in
/proc/pid/environ
This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do
cat /proc/3940/environ | tr '\0' '\n'
Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.
To change the text;
multipleLine.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.myArray.set(pickId,String.valueOf(s));
MainActivity.myAdapt.notifyDataSetChanged();
}
@Override
public void afterTextChanged(Editable s) {
}
you have to do like this...
if not "A%1" == "A"
if the input argument %1 is null, your code will have problem.
cvWaitKey(x) / cv::waitKey(x)
does two things:
cv::imshow()
). Note that it does not listen on stdin for console input. If a key was pressed during that time, it returns the key's ASCII code. Otherwise, it returns -1
. (If x is zero, it waits indefinitely for the key press.)cv::namedWindow()
, or showing images with cv::imshow()
.A common mistake for opencv newcomers is to call cv::imshow()
in a loop through video frames, without following up each draw with cv::waitKey(30)
. In this case, nothing appears on screen, because highgui is never given time to process the draw requests from cv::imshow()
.
Same problem here, this worked just fine:
$('input[name="someRadioGroup"]').change(function() {
$('#r1edit:input').prop('disabled', !$("#r1").is(':checked'));
});
Putting the call to mysql_insert_id()
inside a transaction, should do it:
mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.
If you have sed:
sed -e '/REFERENCE/d' -e '/ERROR/d' [FILENAME]
Where FILENAME
is the name of the text file with the good & bad lines
Since Django 2.x, on_delete
is required.
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
// Reference
var e = f[ i ];
// Actions
e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
/*
<input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
e.disabled === true
*/
e.removeAttribute( "disabled" );
/*
<input>
e.getAttribute( "disabled" ) === null
e.disabled === false
*/
e.disabled = false|null|undefined|""|0;
/*
<input>
e.getAttribute( "disabled" ) === null|null|null|null|null
e.disabled === false
*/
e.disabled = true|" "|"disabled"|1;
/*
<input disabled>
e.getAttribute( "disabled" ) === ""|""|""|""
e.disabled === true
*/
}
You can use array_intersect()
.
$result = !empty(array_intersect($people, $criminals));
There are two problems in your code:
scanf
must be checked%d
conversion does not take overflows into account (blindly applying *10 + newdigit
for each consecutive numeric character)The first value you got (-104204697
) is equals to 5623125698541159
modulo 2^32
; it is thus the result of an overflow (if int
where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.
The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf
, the number of items successfully matched):
#include <stdio.h>
int main(int argc, char *argv[]) {
int i, j;
short unsigned digitArray[16];
i = 0;
while (
i != sizeof(digitArray) / sizeof(digitArray[0])
&& 1 == scanf("%1hu", digitArray + i)
) {
i++;
}
for (j = 0; j != i; j++) {
printf("%hu\n", digitArray[j]);
}
return 0;
}
Thanks for the really useful script.
You may need to add the following modification to the code if your tables have non-convertable fields:
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE NOT IN ('text', 'image', 'ntext')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
Chris
Angular 2 and Angular 4
In a ngFor loop it must be look like this:
<div class="column" *ngFor="let u of events ">
<div class="thumb">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
</div>
<div class="info">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
<p>{{u.text}}</p>
</div>
</div>
The quick answer on how to prevent it is that you most likely need to stop JBoss before starting it again.
You should be able to call the "Terminate" button in the Console view to shutdown the server.
Short Answer:
res.setHeaders
- calls the native Node.js method
res.set
- sets headers
res.headers
- an alias to res.set
Use
/js/bootstrap.bundle.min.js
instead of
/js/bootstrap.min.js
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
I used this extension method a lot in my project. Hope it will help one of you guys.
public static bool HasClass(this HtmlNode node, params string[] classValueArray)
{
var classValue = node.GetAttributeValue("class", "");
var classValues = classValue.Split(' ');
return classValueArray.All(c => classValues.Contains(c));
}
numpy.dot(a, b, out=None)
Dot product of two arrays.
For N dimensions it is a sum product over the last axis of a
and the second-to-last of b
.
Documentation: numpy.dot.
This seems simpler to me
<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>
Closer to your approach
<ng-container *ngFor="let item of list" let-i="index">
<li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>
If you use constants then you have no choice:
const numbers = [1, 2, 3]
You can not reasign:
numbers = []
You can only truncate:
numbers.length = 0
This Module can easily handle mostly every case there is. It is part of a bigger npm package, by Locutus, which includes a variety of functions, but can be used totally independent of the package it self, just copy paste/ adapt a little if not working with npm (change from module to just a function)
As a second parameter it accepts a timestamp, which can come from anywhere, such as Date.getTime()
Also, Locutus maintains a bigger datetime module, also inside the locutus package which will give a more object oriented way to use it
Here you can see other datetime functions, as modules, that proved to be very usefull too.
You can find documentation on parameters and format strings here (note that the doc site is a php site, but the locutus implementation follows exactly the same specs)
Examples of date Module
date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400)//'07:09:40 m is month'
date('F j, Y, g:i a', 1062462400)//'September 2, 2003, 12:26 am'
date('Y W o', 1062462400)//'2003 36 2003'
var $x = date('Y m d', (new Date()).getTime() / 1000) $x = $x + '' var $result = $x.length // 2009 01 09 10
date('W', 1104534000) //'52'
date('B t', 1104534000) //'999 31'
date('W U', 1293750000.82); // 2010-12-31 '52 1293750000'
date('W', 1293836400); // 2011-01-01 '52'
date('W Y-m-d', 1293974054); // 2011-01-02 '52 2011-01-02'
Let's say you have an array of data:
n = [1 2 3 4 6 12 18 51 69 81 ]
then you can 'foreach' it like this:
for i = n, i, end
This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)
This error happens because you didn't install composer on your project.
run composer install
command in your project path.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
In cases where reads greatly outnumber writes, or (however frequent) writes are non-concurrent, a copy-on-write approach may be appropriate.
The implementation shown below is
var snap = _list; snap[snap.Count - 1];
will never (well, except for an empty list of course) throw, and you also get thread-safe enumeration with snapshot semantics for free.. how I LOVE immutability!For copy-on-write to work, you have to keep your data structures effectively immutable, i.e. no one is allowed to change them after you made them available to other threads. When you want to modify, you
Code
static class CopyOnWriteSwapper
{
public static void Swap<T>(ref T obj, Func<T, T> cloner, Action<T> op)
where T : class
{
while (true)
{
var objBefore = Volatile.Read(ref obj);
var newObj = cloner(objBefore);
op(newObj);
if (Interlocked.CompareExchange(ref obj, newObj, objBefore) == objBefore)
return;
}
}
}
Usage
CopyOnWriteSwapper.Swap(ref _myList,
orig => new List<string>(orig),
clone => clone.Add("asdf"));
If you need more performance, it will help to ungenerify the method, e.g. create one method for every type of modification (Add, Remove, ...) you want, and hard code the function pointers cloner
and op
.
N.B. #1 It is your responsibility to make sure the no one modifies the (supposedly) immutable data structure. There's nothing we can do in a generic implementation to prevent that, but when specializing to List<T>
, you could guard against modification using List.AsReadOnly()
N.B. #2 Be careful about the values in the list. The copy on write approach above guards their list membership only, but if you'd put not strings, but some other mutable objects in there, you have to take care of thread safety (e.g. locking). But that is orthogonal to this solution and e.g. locking of the mutable values can be easily used without issues. You just need to be aware of it.
N.B. #3 If your data structure is huge and you modify it frequently, the copy-all-on-write approach might be prohibitive both in terms of memory consumption and the CPU cost of copying involved. In that case, you might want to use MS's Immutable Collections instead.
May be there no need for JS. You can achieve this with css also. Write like this:
.flyout {
position: absolute;
width: 1000px;
height: 450px;
background: red;
overflow: hidden;
z-index: 10000;
display: none;
}
#menu:hover + .flyout {
display: block;
}
If you have multiple files and you don't want to have to type each file, I would recommend that you follow these simple steps (I am using clang-3.8
but you can use any other version):
generate all .ll
files
clang-3.8 -S -emit-llvm *.c
link them into a single one
llvm-link-3.8 -S -v -o single.ll *.ll
(Optional) Optimise your code (maybe some alias analysis)
opt-3.8 -S -O3 -aa -basicaaa -tbaa -licm single.ll -o optimised.ll
Generate assembly (generates a optimised.s
file)
llc-3.8 optimised.ll
Create executable (named a.out
)
clang-3.8 optimised.s
For CURLOPT_POSTFIELDS
, the parameters can either be passed as a urlencoded string like para1=val1¶2=val2&..
or as an array with the field name as key and field data as value
Try the following format :
$data = json_encode(array(
"first" => "John",
"last" => "Smith"
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
I got this error "Could not open input file: composer.phar" while installing Yii2 using below mentioned command.
php composer.phar create-project yiisoft/yii2-app-basic basic
Solutions which worked for me was, I changed the command to
composer create-project yiisoft/yii2-app-basic basic
I hope it help!
You can also use the furl module https://github.com/gruns/furl
>>> from furl import furl
>>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url
http://example.com/search?q=question&lang=en&tag=python
For Bootstrap v4 check this:
https://v4-alpha.getbootstrap.com/components/pagination/#alignment
only add class to ul.pagination:
<nav">
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">Previous</a>
</li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</nav>
Matplotlib related
from matplotlib.dates import drange
import datetime
base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)
The official solution (and others) were incomplete when I first visited, so I came back, years later, to post this alternate approach in case any others wound up here intending to use a public/private key-pair:
Execute this from the target backup machine, which pulls from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' [email protected]:/home/user/Server/ /home/keith/Server/
Execute this from the source machine, which sends from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' /home/user/Server/ [email protected]:/home/user/Server/
And, if you are not using an alternate port for ssh, then consider the more elegant examples below:
Execute this from the target backup machine, which pulls from source to target backup:
sudo rsync -avi --delete [email protected]:/var/www/ /media/sdb1/backups/www/
Execute this from the source machine, which sends from source to target backup:
sudo rsync -avi --delete /media/sdb1/backups/www/ [email protected]:/var/www/
If you are still getting prompted for a password, then you need to check your ssh configuration in /etc/ssh/sshd_config
and verify that the users in source and target each have the others' respective public ssh key by sending each over with ssh-copy-id [email protected]
.
(Again, this is for using ssh key-pairs without a password, as an alternate approach, and not for passing the password over via a file.)
You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:
onchange="this.form.submit()"
Example:
<form>
<div>
<input type="checkbox">
</div>
</form>
If you read through any of the discussions on the android development group you will see that they discourage the use of anything that isn't in the public SDK because the rest is subject to extensive change.
There is another scenario here that would apply. A file that was checked out of Visual Source Safe, for anyone still using it, that was not given "Writeablity", either in the View option or Check Out, will also recieve this error message.
Solution is to re-acquire the file from Source Safe and apply the Writeability setting.
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
You can pass a password into pg_dump directly by using the following:
pg_dump "host=localhost port=5432 dbname=mydb user=myuser password=mypass" > mydb_export.sql
Thanks for your question. I'am using wamp 3 now. And I find an simple answer to do this under your question. But that answer should change a little on wamp 3. The steps are as following:
Actually a more refined solution is use the build-in function sumif, this function does exactly what you need, will only sum those expenses of a specified month.
example
=SUMIF(A2:A100,"=January",B2:B100)
For JavaFx based applications.
//returns System Clipboard
final Clipboard clipboard = Clipboard.getSystemClipboard();
// ClipboardContent provides flexibility to store data in different formats
final ClipboardContent content = new ClipboardContent();
content.putString("Some text");
content.putHtml("<b>Some</b> text");
//this will be replaced by previous putString
content.putString("Some different text");
//set the content to clipboard
clipboard.setContent(content);
// validate before retrieving it
if(clipboard.hasContent(DataFormat.HTML)){
System.out.println(clipboard.getHtml());
}
if(clipboard.hasString()){
System.out.println(clipboard.getString());
}
ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).
For more information see official documentation
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
If you are using SQL Azure Reporting Services, the "format" function is unsupported. This is really the only way to format a tooltip in a chart in SSRS. So the workaround is to return a column that has a string representation of the formatted number to use for the tooltip. So, I do agree that SQL is not the place for formatting. Except in cases like this where the tool does not have proper functions to handle display formatting.
In my case I needed to show a number formatted with commas and no decimals (type decimal 2) and ended up with this gem of a calculated column in my dataset query:
,Fmt_DDS=reverse(stuff(reverse(CONVERT(varchar(25),cast(SUM(kv.DeepDiveSavingsEst) as money),1)), 1, 3, ''))
It works, but is very ugly and non-obvious to whoever maintains the report down the road. Yay Cloud!
You should also consider that in some Opera versions onload is fired several times and add some hooks:
// fixing Opera 9.26, 10.00
if (doc.readyState && doc.readyState != 'complete') {
// Opera fires load event multiple times
// Even when the DOM is not ready yet
// this fix should not affect other browsers
return;
}
// fixing Opera 9.64
if (doc.body && doc.body.innerHTML == "false") {
// In Opera 9.64 event was fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
return;
}
Code borrowed from Ajax Upload
I solved this by using this way -
@RunWith(SpringRunner.class)
@EnableJpaRepositories(basePackages={"com.path.repositories"})
@EntityScan(basePackages={"com.model"})
@TestPropertySource("classpath:application.properties")
@ContextConfiguration(classes = {ApiTestConfig.class,SaveActionsServiceImpl.class})
public class SaveCriticalProcedureTest {
@Autowired
private SaveActionsService saveActionsService;
.......
.......
}
Possible Cause #1 (same as the first 3 answers for this question): Project Structure Settings
File > Project Structure > Under Project Settings, go to Project > set Project SDK to 1.8 (with version 65 or above, latest is 112) and set Project Language Level to 8.
File > Project Structure > Under Platform Settings, go to Project > ensure that your JDK home path is set to 1.8 (with version 65 or above, latest is 112).
If the above does not work, check the target bytecode version of your compiler and move on to Possible Cause #2.
Possible Cause #2: Compiler
Best wishes :)
Anaconda's website addresses this problem here: https://anaconda.org/anaconda/py-xgboost.
conda install -c anaconda py-xgboost
This fixed the problem for me with no problems.
http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.
i'd just do a simple check to see if d[a] exists and if not initialize it...
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
if (d[a] === undefined) {
d[a] = {}
};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
Use the code
x = seq(0,100,5) #this means (starting number, ending number, interval)
the output will be
[1] 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
[17] 80 85 90 95 100
To expand on Craig Glennie's answer:
in Python 3.6.1 on MacOs Sierra
Entering this in the bash terminal solved the problem:
pip install certifi
/Applications/Python\ 3.6/Install\ Certificates.command
here's how you can do it with a cool shell trick:
mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
'<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.
use the -t flag to enable table-format output
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
or you can set pointer-events:none
to your a
element and pointer-event:all
to your a:before
element, and then add hover CSS to a element
a{
pointer-events:none;
}
a:before{
pointer-events:all
}
a:hover:before{
background:blue;
}
Presumably you're passing the arguments in on the command line as follows:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
... and then accessing them in the script thusly:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:
Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
... and access:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
This seems to work for me:
LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>
short form:
LANG=C grep -obUaP "<\x-hex pattern>" <file>
Example:
LANG=C grep -obUaP "\x01\x02" /bin/grep
Output (cygwin binary):
153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>
So you can grep this again to extract offsets. But don't forget to use binary mode again.
Note: LANG=C
is needed to avoid utf8 encoding issues.
As an aside, when trying to diagnose a similar bug I realised that jquery's ajax error callback returns a status of "timeout" if it failed due to a timeout.
Here's an example:
$.ajax({
url: "/ajax_json_echo/",
timeout: 500,
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus); // this will be "timeout"
}
});
Better late than never: I created the "Android-SharedPreferences-Helper" library to help reduce the complexity and effort of using SharedPreferences
. It also provides some extended functionality. Few things that it offers are as follows:
- One line initialization and setup
- Easily selecting whether to use default preferences or a custom preference file
- Predefined (data type defaults) and customizable (what you may choose) default values for each datatype
- Ability to set different default value for single use with just an additional param
- You can register and unregister OnSharedPreferenceChangeListener as you do for default class
dependencies {
...
...
compile(group: 'com.viralypatel.sharedpreferenceshelper', name: 'library', version: '1.1.0', ext: 'aar')
}
Declaration of SharedPreferencesHelper object: (recommended at class level)
SharedPreferencesHelper sph;
Instantiation of the SharedPreferencesHelper object: (recommended in onCreate() method)
// use one of the following ways to instantiate
sph = new SharedPreferencesHelper(this); //this will use default shared preferences
sph = new SharedPreferencesHelper(this, "myappprefs"); // this will create a named shared preference file
sph = new SharedPreferencesHelper(this, "myappprefs", 0); // this will allow you to specify a mode
Putting values into shared preferences
Fairly simple! Unlike the default way (when using the SharedPreferences class) you'll NOT need to call .edit()
and .commit()
ever time.
sph.putBoolean("boolKey", true);
sph.putInt("intKey", 123);
sph.putString("stringKey", "string value");
sph.putLong("longKey", 456876451);
sph.putFloat("floatKey", 1.51f);
// putStringSet is supported only for android versions above HONEYCOMB
Set name = new HashSet();
name.add("Viral");
name.add("Patel");
sph.putStringSet("name", name);
That's it! Your values are stored in the shared preferences.
Getting values from shared preferences
Again, just one simple method call with the key name.
sph.getBoolean("boolKey");
sph.getInt("intKey");
sph.getString("stringKey");
sph.getLong("longKey");
sph.getFloat("floatKey");
// getStringSet is supported only for android versions above HONEYCOMB
sph.getStringSet("name");
It has a lot of other extended functionality
Check the details of extended functionality, usage and installation instructions etc on the GitHub Repository Page.
It looks like you indented so_far = new
too much. Try this:
if guess in word:
print("\nYes!", guess, "is in the word!")
# Create a new variable (so_far) to contain the guess
new = ""
i = 0
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new # unindented this
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
Kotlin has a built-in function for this, removeSuffix
(Documentation)
var text = "filename.xml"
text = text.removeSuffix(".xml") // "filename"
If the suffix does not exist in the string, it just returns the original
var text = "not_a_filename"
text = text.removeSuffix(".xml") // "not_a_filename"
You can also check out removePrefix
and removeSurrounding
which are similar
first, you have to create a handler.
var specialElementHandlers = {
'#editor': function(element, renderer){
return true;
}
};
then write this code in click event:
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
var pdfOutput = doc.output();
console.log(">>>"+pdfOutput );
assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.
Also malloc and realloc are useful if you don't know ahead of time how many strings are being concatenated.
#include <stdio.h>
#include <string.h>
void example(const char *header, const char **words, size_t num_words)
{
size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
char *message = (char*) malloc(message_len);
strncat(message, header, message_len);
for(int i = 0; i < num_words; ++i)
{
message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
message = (char*) realloc(message, message_len);
strncat(strncat(message, ";", message_len), words[i], message_len);
}
puts(message);
free(message);
}
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…
<body ng-app="">
<div ng-include="'myFile.htm'"></div>
</body>
You could also just do this:
mysql_query("
UPDATE member_profile
SET points = points + 1
WHERE user_id = '".$userid."'
");
There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.
If it confuses readers of your code (because String[] instanceof Object[]
is true), you may want to use the first to be more explicit if code reviewers keep asking about it.
You can create elements to the DOM, which loads items.
Like such:
var myScript = document.createElement('script'); // Create new script element
myScript.type = 'text/javascript'; // Set appropriate type
myScript.src = './js/myclass.js'; // Load javascript file
You may use Request.Cookies collection to read the cookies.
if(Request.Cookies["key"]!=null)
{
var value=Request.Cookies["key"].Value;
}
As explained above, using new Array(size)
is somewhat dangerous. Instead of using it directly, place it inside an "array creator function". You can easily make sure that this function is bug-free and you avoid the danger of calling new Array(size)
directly. Also, you can give it an optional default initial value. This createArray
function does exactly that:
function createArray(size, defaultVal) {
const arr = new Array(size);
if (defaultVal !== undefined) {
// optional default value
for (let i = 0; i < size; ++i) {
arr[i] = defaultVal;
}
}
return arr;
}
See ?order
. You just need the last index (or first, in decreasing order), so this should do the trick:
order(matrix[,2],decreasing=T)[1]
To Answer your first question, Jenkins variables are case sensitive. However, if you are writing a windows batch script, they are case insensitive, because Windows doesn't care about the case.
Since you are not very clear about your setup, let's make the assumption that you are using an ant build step to fire up your ant task. Have a look at the Jenkins documentation (same page that Adarsh gave you, but different chapter) for an example on how to make Jenkins variables available to your ant task.
EDIT:
Hence, I will need to access the environmental variable ${BUILD_NUMBER} to construct the URL.
Why don't you use $BUILD_URL
then? Isn't it available in the extended email plugin?
MySQL uses double for all floats ... So use type double. Using float will lead to unpredictable rounded values in most situations
I had this problem too and couldn't solve it without using VBA.
In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.
i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."
Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.
Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
'clean
.FormatConditions.Delete
'green rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""GREEN"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -11489280
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
'amber rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""AMBER"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.ThemeColor = xlThemeColorAccent6
.TintAndShade = -0.249946592608417
End With
.FormatConditions(1).StopIfTrue = False
'red rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""RED"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -16776961
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
End With
Next Cell
End Sub
I prefer to use a utility function which uses GSON to de-serialize the Java object into JSON string.
/**
* This class provides basic/common functionalities to be applied on Java Objects.
*/
public final class ObjectUtils {
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private ObjectUtils() {
throw new UnsupportedOperationException("Instantiation of this class is not permitted in case you are using reflection.");
}
/**
* This method is responsible for de-serializing the Java Object into Json String.
*
* @param object Object to be de-serialized.
* @return String
*/
public static String deserializeObjectToString(final Object object) {
return GSON.toJson(object);
}
}
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
String num = "10";
Integer.parseInt(num );
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
Change the start field in package.json from:
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "
To:
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "
It really helped.
Yet another 3rd party lib not mentioned here is mxDateTime (predecessor of both python datetime
and 3rd party timeutil
) could be used for this task.
The aforementioned yearsago
would be:
from mx.DateTime import now, RelativeDateTime
def years_ago(years, from_date=None):
if from_date == None:
from_date = now()
return from_date-RelativeDateTime(years=years)
First parameter is expected to be a DateTime
instance.
To convert ordinary datetime
to DateTime
you could use this for 1 second precision):
def DT_from_dt_s(t):
return DT.DateTimeFromTicks(time.mktime(t.timetuple()))
or this for 1 microsecond precision:
def DT_from_dt_u(t):
return DT.DateTime(t.year, t.month, t.day, t.hour,
t.minute, t.second + t.microsecond * 1e-6)
And yes, adding the dependency for this single task in question would definitely be an overkill compared even with using timeutil (suggested by Rick Copeland).
If error is like Author=models.ForeignKey(User, related_names='blog_posts') TypeError:init() missing 1 required positional argument:'on_delete'
Then the solution will be like, you have to add one argument Author=models.ForeignKey(User, related_names='blog_posts', on_delete=models.DO_NOTHING)
Use mongoexport/mongoimport to dump/restore a collection:
Export JSON File:
mongoexport --db <database-name> --collection <collection-name> --out output.json
Import JSON File:
mongoimport --db <database-name> --collection <collection-name> --file input.json
WARNING
mongoimport
andmongoexport
do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity.
Also, http://bsonspec.org/
BSON is designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.
In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.
Does this help you:
<script type="text/javascript">
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
I'm not sure how it handles Flash errors though...
Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:
I have a angular 5 + spring boot app(application.properties 1.3+) with help of compression(link attached below) was able to reduce the size of main.bundle.ts size from 2.7 MB to 530 KB.
Also by default --aot and --build-optimizer are enabled with --prod mode you need not specify those separately.
If you have an unsorted vector, then you can simply swap with the last vector element then resize()
.
With an ordered container, you'll be best off with ?std::vector::erase()
. Note that there is a std::remove()
defined in <algorithm>
, but that doesn't actually do the erasing. (Read the documentation carefully).
Update for transposition:
You should use cvTranspose()
or cv::transpose()
because (as you rightly pointed out) it's more efficient. Again, I recommend upgrading to OpenCV2.0 since most of the cvXXX
functions just convert IplImage*
structures to Mat
objects (no deep copies). If you stored the image in a Mat
object, Mat.t()
would return the transpose.
Any rotation:
You should use cvWarpAffine by defining the rotation matrix in the general framework of the transformation matrix. I would highly recommend upgrading to OpenCV2.0 which has several features as well as a Mat
class which encapsulates matrices and images. With 2.0 you can use warpAffine to the above.
I came across .netrc
and found it relevant to this.
Create a file ~/.netrc
with the following content:
machine github.com
login <github username>
password <github password or Personal access tokens >
Done!
Additionally, for latest GO versions, you might need to add this to the environment variables GOPRIVATE=github.com
(I've added it to my .zshrc
)
netrc
also makes my development environment setup better as my personal github access for HTTPS is been configured now to be used across the machine (just like my SSH configuration).
Generate GitHub personal access tokens: https://github.com/settings/tokens
See this answer for its use with Git on Windows specifically
Ref: netrc man page
If you want to stick with the SSH authentication, then mask the request to use ssh forcefully
git config --global url."[email protected]:".insteadOf "https://github.com/"
More methods for setting up git access: https://gist.github.com/technoweenie/1072829#gistcomment-2979908
This question has been already answered with very good examples. The only example that might be missing is one where the functions return pointers. I wrote another example with this, and added lots of comments, in case someone finds it helpful:
#include <stdio.h>
char * func1(char *a) {
*a = 'b';
return a;
}
char * func2(char *a) {
*a = 'c';
return a;
}
int main() {
char a = 'a';
/* declare array of function pointers
* the function pointer types are char * name(char *)
* A pointer to this type of function would be just
* put * before name, and parenthesis around *name:
* char * (*name)(char *)
* An array of these pointers is the same with [x]
*/
char * (*functions[2])(char *) = {func1, func2};
printf("%c, ", a);
/* the functions return a pointer, so I need to deference pointer
* Thats why the * in front of the parenthesis (in case it confused you)
*/
printf("%c, ", *(*functions[0])(&a));
printf("%c\n", *(*functions[1])(&a));
a = 'a';
/* creating 'name' for a function pointer type
* funcp is equivalent to type char *(*funcname)(char *)
*/
typedef char *(*funcp)(char *);
/* Now the declaration of the array of function pointers
* becomes easier
*/
funcp functions2[2] = {func1, func2};
printf("%c, ", a);
printf("%c, ", *(*functions2[0])(&a));
printf("%c\n", *(*functions2[1])(&a));
return 0;
}
This is the best method to download and view PDF file.You can just call it from anywhere as like
PDFTools.showPDFUrl(context, url);
here below put the code. It will works fine
public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";
public static void showPDFUrl(final Context context, final String pdfUrl ) {
if ( isPDFSupported( context ) ) {
downloadAndOpenPDF(context, pdfUrl);
} else {
askToOpenPDFThroughGoogleDrive( context, pdfUrl );
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
// Get filename
//final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
String filename = "";
try {
filename = new GetFileInfo().execute(pdfUrl).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// The place where the downloaded PDF file will be put
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
Log.e(TAG,"File Path:"+tempFile);
if ( tempFile.exists() ) {
// If we have downloaded the file before, just go ahead and show it.
openPDF( context, Uri.fromFile( tempFile ) );
return;
}
// Show progress dialog while downloading
final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );
// Create the download request
DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
BroadcastReceiver onComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if ( !progress.isShowing() ) {
return;
}
context.unregisterReceiver( this );
progress.dismiss();
long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );
if ( c.moveToFirst() ) {
int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
openPDF( context, Uri.fromFile( tempFile ) );
}
}
c.close();
}
};
context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );
// Enqueue the request
dm.enqueue( r );
}
public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
new AlertDialog.Builder( context )
.setTitle( R.string.pdf_show_online_dialog_title )
.setMessage( R.string.pdf_show_online_dialog_question )
.setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
.setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
openPDFThroughGoogleDrive(context, pdfUrl);
}
})
.show();
}
public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
context.startActivity( i );
}
public static final void openPDF(Context context, Uri localUri ) {
Intent i = new Intent( Intent.ACTION_VIEW );
i.setDataAndType( localUri, PDF_MIME_TYPE );
context.startActivity( i );
}
public static boolean isPDFSupported( Context context ) {
Intent i = new Intent( Intent.ACTION_VIEW );
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
protected String doInBackground(String... urls)
{
URL url;
String filename = null;
try {
url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
conn.setInstanceFollowRedirects(false);
if(conn.getHeaderField("Content-Disposition")!=null){
String depo = conn.getHeaderField("Content-Disposition");
String depoSplit[] = depo.split("filename=");
filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
}else{
filename = "download.pdf";
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
}
return filename;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// use result as file name
}
}
}
try it. it will works, enjoy
In kotlin:
override fun onBackPressed() {
when {
webView.canGoBack() -> webView.goBack()
else -> super.onBackPressed()
}
}
webView - id of the webview component in xml, if using synthetic reference.
You should include bootstrap-datepicker.js
after bootstrap.js
and you should bind the datepicker
to your control.
$(function(){
$('.datepicker').datepicker({
format: 'mm-dd-yyyy'
});
});
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.
Bind the click event:
$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
e.preventDefault();
$("#dialog-confirm")
.data('link', this) // The important part .data() method
.dialog('open');
});
And your dialog:
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height:200,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog('close');
},
'Delete': function() {
$(this).dialog('close');
var path = $(this).data('link').href; // Get the stored result
$(location).attr('href', path);
}
}
});
Building off of Mamboking's answer:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(anyString())).thenReturn("Some result");
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Addressing your request to verify whether the argument contains a certain value, I could assume you mean that the argument is a String and you want to test whether the String argument contains a substring. For this you could do:
ArgumentCaptor<String> savedCaptor = ArgumentCaptor.forClass(String.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains("substring I want to find");
If that assumption was wrong, and the argument to save()
is a collection of some kind, it would be only slightly different:
ArgumentCaptor<Collection<MyType>> savedCaptor = ArgumentCaptor.forClass(Collection.class);
verify(mock_contractsDao).save(savedCaptor.capture());
assertTrue(savedCaptor.getValue().contains(someMyTypeElementToFindInCollection);
You might also check into ArgumentMatchers, if you know how to use Hamcrest matchers.
Maybe Series would provide all the functions you need:
pd.Series({'A':a,'B':b})
DataFrame can be thought of as a collection of Series hence you can :
Concatenate multiple Series into one data frame (as described here )
Add a Series variable into existing data frame ( example here )
For me / had to be in a new line.
For example
create type emp_t;/
didn't work
but
create type emp_t;
/
worked.
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
Apparently you want:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
Have a further read in Jeez People, Stop Fretting Over Installing RMagic.
I have made this like that.
Random random = new Random();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
while (arrayList.size() < 6) { // how many numbers u need - it will 6
int a = random.nextInt(49)+1; // this will give numbers between 1 and 50.
if (!arrayList.contains(a)) {
arrayList.add(a);
}
}
The time.Parse
function does not do Unix timestamps. Instead you can use strconv.ParseInt
to parse the string to int64
and create the timestamp with time.Unix
:
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm)
}
Output:
2014-07-16 20:55:46 +0000 UTC
Playground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from strconv.Atoi
to strconv.ParseInt
to avoid int overflows on 32 bit systems.
Use dateutil as described in Python datetime.datetime.now() that is timezone aware:
from dateutil.tz import tzlocal
# Get the current date/time with the timezone.
now = datetime.datetime.now(tzlocal())
Trim()
will only remove leading or trailing spaces.
Try .Contains()
to check if a string contains white space
"sossjjs sskkk".Contains(" ") // returns true
After reading a lot of these answers I thought I would share my resulting solution. All I added is /bin/bash
before the heredoc and it doesn't give the error anymore.
Use this:
ssh user@machine /bin/bash <<'ENDSSH'
hostname
ENDSSH
Instead of this (gives error):
ssh user@machine <<'ENDSSH'
hostname
ENDSSH
Or use this:
ssh user@machine /bin/bash < run-command.sh
Instead of this (gives error):
ssh user@machine < run-command.sh
EXTRA:
If you still want a remote interactive prompt e.g. if the script you're running remotely prompts you for a password or other information, because the previous solutions won't allow you to type into the prompts.
ssh -t user@machine "$(<run-command.sh)"
And if you also want to log the entire session in a file logfile.log
:
ssh -t user@machine "$(<run-command.sh)" | tee -a logfile.log
If you want to use the same set of arguments all the time, the following is all you need.
run {
args = ["--myarg1", "--myarg2"]
}
This only works if you control both the outside page and the iframe page.
On the outside page, make the iframe
unscrollable.
<iframe src="" height=200 scrolling=no></iframe>
On the iframe page, add this.
<!doctype html>
...
<style>
html, body {height:100%; overflow:hidden}
body {overflow:auto; -webkit-overflow-scrolling:touch}
</style>
This works because modern browsers uses html
to determine the height, so we just give that a fixed height and turn the body
into a scrollable node.
There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV
) file with the XChart library. Disclaimer: I'm the lead developer of the project.
In this example, two text files exist in ./CSV/CSVChartRows/
. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1
contains x
, y
, and error bar
data, whereas series2
contains just x
and y
, data.
1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5
1,56
2,34
3,12
4,26
public class CSVChartRows {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);
// Show it
new SwingWrapper(chart).displayChart();
}
}
You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.
WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.
Generally speaking, many configurations files also go into WEB-INF.
As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).
The best way to get the text value from a <label>
element is as follows.
if you will be getting element ids frequently it's best to have a function to return the ids:
function id(e){return document.getElementById(e)}
Assume the following structure:
<label for='phone'>Phone number</label>
<input type='text' id='phone' placeholder='Mobile or landline numbers...'>
This code will extract the text value 'Phone number' from the<label>:
var text = id('phone').previousElementSibling.innerHTML;
This code works on all browsers, and you don't have to give each<label>
element a unique id.
You can change the decimal separator by changing the culture used to display the number. Beware however that this will change everything else about the number (eg. grouping separator, grouping sizes, number of decimal places). From your question, it looks like you are defaulting to a culture that uses a comma as a decimal separator.
To change just the decimal separator without changing the culture, you can modify the NumberDecimalSeparator
property of the current culture's NumberFormatInfo
.
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
This will modify the current culture of the thread. All output will now be altered, meaning that you can just use value.ToString()
to output the format you want, without worrying about changing the culture each time you output a number.
(Note that a neutral culture cannot have its decimal separator changed.)
You can do that by using this simple code:
Object.keys(myObject).length
python pydash
package could be a good choice.
from pydash.arrays import chunk
ids = ['22', '89', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '1']
chunk_ids = chunk(ids,5)
print(chunk_ids)
# output: [['22', '89', '2', '3', '4'], ['5', '6', '7', '8', '9'], ['10', '11', '1']]
for more checkout pydash chunk list
If you're having this problem in a stored procedure and you aren't able to use the key in the WHERE clause, you can solve this by declaring a variable that will hold the limit of the rows that should be updated and then use it in the update/delete query.
DELIMITER $
CREATE PROCEDURE myProcedure()
BEGIN
DECLARE the_limit INT;
SELECT COUNT(*) INTO the_limit
FROM my_table
WHERE my_column IS NULL;
UPDATE my_table
SET my_column = true
WHERE my_column IS NULL
LIMIT the_limit;
END$
Var Obj = {};
This is the most used and simplest method.
Using
var Obj = new Obj()
is not preferred.
There is no need to use new Object()
.
For simplicity, readability and execution speed, use the first one (the object literal method).
To get the value, we can use multiple attributes, one of them being the name attribute. E.g
$("input[name='nameOfElement']").val();
We can also use other attributes to get values
HTML
<input type="text" id="demoText" demo="textValue" />
JS
$("[demo='textValue']").val();
SELECT *
FROM table
ORDER BY id DESC
LIMIT 0, 1
Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).
If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.
I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.
It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:
1) You can change the recursion limit with sys.setrecursionlimit(n)
until the maximum allowed for your platform:
sys.setrecursionlimit(limit)
:Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.
Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a ~
to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.
import shutil
shutil.move( afile, afile+"~" )
destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
destination.write( line )
if <some condition>:
destination.write( >some additional line> + "\n" )
source.close()
destination.close()
Instead of shutil
, you can use the following.
import os
os.rename( aFile, aFile+"~" )
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Bable.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();
Bart Kiers, your regex has a couple issues. The best way to do that is this:
(.*[a-z].*) // For lower cases
(.*[A-Z].*) // For upper cases
(.*\d.*) // For digits
In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.
The legacy solution in the top answer didn't work for me because I wanted to affect multiple lists on the page and the answer assumes a single list plus it uses a fair bit of global state. In this case I wanted to alter every list inside a <section class="list-content">
:
const columns = 2;
$("section.list-content").each(function (index, element) {
let section = $(element);
let items = section.find("ul li").detach();
section.find("ul").detach();
for (let i = 0; i < columns; i++) {
section.append("<ul></ul>");
}
let lists = section.find("ul");
for (let i = 0; i < items.length; i++) {
lists.get(i % columns).append(items[i]);
}
});
Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.
Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.