I had this error when I tried to create a replicationcontroller
. The issue was, I wrongly spelt the nginx image name in template definition.
Note: This error occurs when kubernetes is unable to pull the specified image from the repository.
One way to achieve this is using a position:fixed
container for the background image and place it outside of the .jumbotron
. Make the bg
container the same height as the .jumbotron
and center the background image:
background: url('/assets/example/...jpg') no-repeat center center;
CSS
.bg {
background: url('/assets/example/bg_blueplane.jpg') no-repeat center center;
position: fixed;
width: 100%;
height: 350px; /*same height as jumbotron */
top:0;
left:0;
z-index: -1;
}
.jumbotron {
margin-bottom: 0px;
height: 350px;
color: white;
text-shadow: black 0.3em 0.3em 0.3em;
background:transparent;
}
Then use jQuery to decrease the height of the .jumbtron
as the window scrolls. Since the background image is centered in the DIV it will adjust accordingly -- creating a parallax affect.
JavaScript
var jumboHeight = $('.jumbotron').outerHeight();
function parallax(){
var scrolled = $(window).scrollTop();
$('.bg').css('height', (jumboHeight-scrolled) + 'px');
}
$(window).scroll(function(e){
parallax();
});
Demo
Note, until now posted solutions only work for png and jpg!
If you want it even easier without importing further libraries or you want to display an animated or not animated GIF File in your Ipython Notebook. Transform the line where you want to display it to markdown and use this nice short hack!
![alt text](test.gif "Title")
(For completeness) If you want to remove columns by name, you can do this:
cols.dont.want <- "genome"
cols.dont.want <- c("genome", "region") # if you want to remove multiple columns
data <- data[, ! names(data) %in% cols.dont.want, drop = F]
Including drop = F
ensures that the result will still be a data.frame
even if only one column remains.
Below function to save files, just pass your base64 file, it return filename save it in DB.
import fs from 'fs';
const uuid = require('uuid/v1');
/*Download the base64 image in the server and returns the filename and path of image.*/
function saveImage(baseImage) {
/*path of the folder where your project is saved. (In my case i got it from config file, root path of project).*/
const uploadPath = "/home/documents/project";
//path of folder where you want to save the image.
const localPath = `${uploadPath}/uploads/images/`;
//Find extension of file
const ext = baseImage.substring(baseImage.indexOf("/")+1, baseImage.indexOf(";base64"));
const fileType = baseImage.substring("data:".length,baseImage.indexOf("/"));
//Forming regex to extract base64 data of file.
const regex = new RegExp(`^data:${fileType}\/${ext};base64,`, 'gi');
//Extract base64 data.
const base64Data = baseImage.replace(regex, "");
const filename = `${uuid()}.${ext}`;
//Check that if directory is present or not.
if(!fs.existsSync(`${uploadPath}/uploads/`)) {
fs.mkdirSync(`${uploadPath}/uploads/`);
}
if (!fs.existsSync(localPath)) {
fs.mkdirSync(localPath);
}
fs.writeFileSync(localPath+filename, base64Data, 'base64');
return filename;
}
There are a couple of mysql functions you need to look into.
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false
value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..)
to get the row in an associative array.
Links:
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
The pipe character |
has a special meaning in regular expressions. a|b
means "match either a
or b
". If you want to match a literal |
character, you need to escape it:
... | Select-String -Pattern 'H\|159' -NotMatch | ...
I usually do it this way...
#include <string>
#include <vector>
int main( int argc, char* argv[] )
{
std::vector<char> vec;
//... do something with vec
std::string str(vec.begin(), vec.end());
//... do something with str
return 0;
}
I'm assuming you're still asking about the same situation as in your previous question. That is, master-new will not contain master-old in its history.* If you call master-new "master", you will effectively have rewritten history. It does not matter how you get into a state in which master is not a descendant of a previous position of master, simply that it is in that state.
Other users attempting to pull while master does not exist will simply have their pulls fail (no such ref on remote), and once it exists again in a new place, their pulls will have to attempt to merge their master with the new remote master, just as if you merged master-old and master-new in your repository. Given what you're trying to do here, the merge would have conflicts. (If they were resolved, and the result was pushed back into the repository, you'd be in an even worse state - both versions of history there.)
To answer your question simply: you should accept that sometimes there will be mistakes in your history. This is okay. It happens to everyone. There are reverted commits in the git.git repository. The important thing is that once we publish history, it is something everyone can trust.
*If it did, this would be equivalent to pushing some changes onto master, and then creating a new branch where it used to be. No problem.
From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):
ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.
http://ora-06512.ora-code.com/:
ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.
Actually the purpose of np.meshgrid
is already mentioned in the documentation:
Return coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2,..., xn.
So it's primary purpose is to create a coordinates matrices.
You probably just asked yourself:
The reason you need coordinate matrices with Python/NumPy is that there is no direct relation from coordinates to values, except when your coordinates start with zero and are purely positive integers. Then you can just use the indices of an array as the index. However when that's not the case you somehow need to store coordinates alongside your data. That's where grids come in.
Suppose your data is:
1 2 1
2 5 2
1 2 1
However, each value represents a 3 x 2 kilometer area (horizontal x vertical). Suppose your origin is the upper left corner and you want arrays that represent the distance you could use:
import numpy as np
h, v = np.meshgrid(np.arange(3)*3, np.arange(3)*2)
where v is:
array([[0, 0, 0],
[2, 2, 2],
[4, 4, 4]])
and h:
array([[0, 3, 6],
[0, 3, 6],
[0, 3, 6]])
So if you have two indices, let's say x
and y
(that's why the return value of meshgrid
is usually xx
or xs
instead of x
in this case I chose h
for horizontally!) then you can get the x coordinate of the point, the y coordinate of the point and the value at that point by using:
h[x, y] # horizontal coordinate
v[x, y] # vertical coordinate
data[x, y] # value
That makes it much easier to keep track of coordinates and (even more importantly) you can pass them to functions that need to know the coordinates.
However, np.meshgrid
itself isn't often used directly, mostly one just uses one of similar objects np.mgrid
or np.ogrid
.
Here np.mgrid
represents the sparse=False
and np.ogrid
the sparse=True
case (I refer to the sparse
argument of np.meshgrid
). Note that there is a significant difference between
np.meshgrid
and np.ogrid
and np.mgrid
: The first two returned values (if there are two or more) are reversed. Often this doesn't matter but you should give meaningful variable names depending on the context.
For example, in case of a 2D grid and matplotlib.pyplot.imshow
it makes sense to name the first returned item of np.meshgrid
x
and the second one y
while it's
the other way around for np.mgrid
and np.ogrid
.
np.ogrid
and sparse grids>>> import numpy as np
>>> yy, xx = np.ogrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5],
[-4],
[-3],
[-2],
[-1],
[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5]])
As already said the output is reversed when compared to np.meshgrid
, that's why I unpacked it as yy, xx
instead of xx, yy
:
>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6), sparse=True)
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5],
[-4],
[-3],
[-2],
[-1],
[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5]])
This already looks like coordinates, specifically the x and y lines for 2D plots.
Visualized:
yy, xx = np.ogrid[-5:6, -5:6]
plt.figure()
plt.title('ogrid (sparse meshgrid)')
plt.grid()
plt.xticks(xx.ravel())
plt.yticks(yy.ravel())
plt.scatter(xx, np.zeros_like(xx), color="blue", marker="*")
plt.scatter(np.zeros_like(yy), yy, color="red", marker="x")
np.mgrid
and dense/fleshed out grids>>> yy, xx = np.mgrid[-5:6, -5:6]
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
[-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
[-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]])
The same applies here: The output is reversed compared to np.meshgrid
:
>>> xx, yy = np.meshgrid(np.arange(-5, 6), np.arange(-5, 6))
>>> xx
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
>>> yy
array([[-5, -5, -5, -5, -5, -5, -5, -5, -5, -5, -5],
[-4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4],
[-3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3],
[-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2],
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
[ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
[ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]])
Unlike ogrid
these arrays contain all xx
and yy
coordinates in the -5 <= xx <= 5; -5 <= yy <= 5 grid.
yy, xx = np.mgrid[-5:6, -5:6]
plt.figure()
plt.title('mgrid (dense meshgrid)')
plt.grid()
plt.xticks(xx[0])
plt.yticks(yy[:, 0])
plt.scatter(xx, yy, color="red", marker="x")
It's not only limited to 2D, these functions work for arbitrary dimensions (well, there is a maximum number of arguments given to function in Python and a maximum number of dimensions that NumPy allows):
>>> x1, x2, x3, x4 = np.ogrid[:3, 1:4, 2:5, 3:6]
>>> for i, x in enumerate([x1, x2, x3, x4]):
... print('x{}'.format(i+1))
... print(repr(x))
x1
array([[[[0]]],
[[[1]]],
[[[2]]]])
x2
array([[[[1]],
[[2]],
[[3]]]])
x3
array([[[[2],
[3],
[4]]]])
x4
array([[[[3, 4, 5]]]])
>>> # equivalent meshgrid output, note how the first two arguments are reversed and the unpacking
>>> x2, x1, x3, x4 = np.meshgrid(np.arange(1,4), np.arange(3), np.arange(2, 5), np.arange(3, 6), sparse=True)
>>> for i, x in enumerate([x1, x2, x3, x4]):
... print('x{}'.format(i+1))
... print(repr(x))
# Identical output so it's omitted here.
Even if these also work for 1D there are two (much more common) 1D grid creation functions:
Besides the start
and stop
argument it also supports the step
argument (even complex steps that represent the number of steps):
>>> x1, x2 = np.mgrid[1:10:2, 1:10:4j]
>>> x1 # The dimension with the explicit step width of 2
array([[1., 1., 1., 1.],
[3., 3., 3., 3.],
[5., 5., 5., 5.],
[7., 7., 7., 7.],
[9., 9., 9., 9.]])
>>> x2 # The dimension with the "number of steps"
array([[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.],
[ 1., 4., 7., 10.]])
You specifically asked about the purpose and in fact, these grids are extremely useful if you need a coordinate system.
For example if you have a NumPy function that calculates the distance in two dimensions:
def distance_2d(x_point, y_point, x, y):
return np.hypot(x-x_point, y-y_point)
And you want to know the distance of each point:
>>> ys, xs = np.ogrid[-5:5, -5:5]
>>> distances = distance_2d(1, 2, xs, ys) # distance to point (1, 2)
>>> distances
array([[9.21954446, 8.60232527, 8.06225775, 7.61577311, 7.28010989,
7.07106781, 7. , 7.07106781, 7.28010989, 7.61577311],
[8.48528137, 7.81024968, 7.21110255, 6.70820393, 6.32455532,
6.08276253, 6. , 6.08276253, 6.32455532, 6.70820393],
[7.81024968, 7.07106781, 6.40312424, 5.83095189, 5.38516481,
5.09901951, 5. , 5.09901951, 5.38516481, 5.83095189],
[7.21110255, 6.40312424, 5.65685425, 5. , 4.47213595,
4.12310563, 4. , 4.12310563, 4.47213595, 5. ],
[6.70820393, 5.83095189, 5. , 4.24264069, 3.60555128,
3.16227766, 3. , 3.16227766, 3.60555128, 4.24264069],
[6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
2.23606798, 2. , 2.23606798, 2.82842712, 3.60555128],
[6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
1.41421356, 1. , 1.41421356, 2.23606798, 3.16227766],
[6. , 5. , 4. , 3. , 2. ,
1. , 0. , 1. , 2. , 3. ],
[6.08276253, 5.09901951, 4.12310563, 3.16227766, 2.23606798,
1.41421356, 1. , 1.41421356, 2.23606798, 3.16227766],
[6.32455532, 5.38516481, 4.47213595, 3.60555128, 2.82842712,
2.23606798, 2. , 2.23606798, 2.82842712, 3.60555128]])
The output would be identical if one passed in a dense grid instead of an open grid. NumPys broadcasting makes it possible!
Let's visualize the result:
plt.figure()
plt.title('distance to point (1, 2)')
plt.imshow(distances, origin='lower', interpolation="none")
plt.xticks(np.arange(xs.shape[1]), xs.ravel()) # need to set the ticks manually
plt.yticks(np.arange(ys.shape[0]), ys.ravel())
plt.colorbar()
And this is also when NumPys mgrid
and ogrid
become very convenient because it allows you to easily change the resolution of your grids:
ys, xs = np.ogrid[-5:5:200j, -5:5:200j]
# otherwise same code as above
However, since imshow
doesn't support x
and y
inputs one has to change the ticks by hand. It would be really convenient if it would accept the x
and y
coordinates, right?
It's easy to write functions with NumPy that deal naturally with grids. Furthermore, there are several functions in NumPy, SciPy, matplotlib that expect you to pass in the grid.
I like images so let's explore matplotlib.pyplot.contour
:
ys, xs = np.mgrid[-5:5:200j, -5:5:200j]
density = np.sin(ys)-np.cos(xs)
plt.figure()
plt.contour(xs, ys, density)
Note how the coordinates are already correctly set! That wouldn't be the case if you just passed in the density
.
Or to give another fun example using astropy models (this time I don't care much about the coordinates, I just use them to create some grid):
from astropy.modeling import models
z = np.zeros((100, 100))
y, x = np.mgrid[0:100, 0:100]
for _ in range(10):
g2d = models.Gaussian2D(amplitude=100,
x_mean=np.random.randint(0, 100),
y_mean=np.random.randint(0, 100),
x_stddev=3,
y_stddev=3)
z += g2d(x, y)
a2d = models.AiryDisk2D(amplitude=70,
x_0=np.random.randint(0, 100),
y_0=np.random.randint(0, 100),
radius=5)
z += a2d(x, y)
Although that's just "for the looks" several functions related to functional models and fitting (for example scipy.interpolate.interp2d
,
scipy.interpolate.griddata
even show examples using np.mgrid
) in Scipy, etc. require grids. Most of these work with open grids and dense grids, however some only work with one of them.
v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)
The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.
Form Post Action :
<form method="post" action="{{url('login')}}" accept-charset="UTF-8">
Change your Route : In Routes -> Web.php
Route::post('login','WelcomeController@log_in');
List<int> list = new List<int> { 5, 7, 3 };
list.Sort((x,y)=> y.CompareTo(x));
list.ForEach(action => { Console.Write(action + " "); });
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
To install the prerequisites for GPU support in TensorFlow 2.1:
pip install tensorflow
.There are many ways. You use RelativeLayout or AbsoluteLayout.
With relative, you can have the image align with parent on the left side for example and also have the text align to the parent left too... then you can use margins and padding and gravity on the text view to get it lined where you want over the image.
var lines = new List<string>();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
var header = string.Join(",", columnNames);
lines.Add(header);
var valueLines = dt.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv", lines);
Here dt refers to your DataTable pass as a paramter
The following way will take note of all requests, and hide only once all requests are done:
app.factory('httpRequestInterceptor', function(LoadingService, requestCount) {_x000D_
return {_x000D_
request: function(config) {_x000D_
if (!config.headers.disableLoading) {_x000D_
requestCount.increase();_x000D_
LoadingService.show();_x000D_
}_x000D_
return config;_x000D_
}_x000D_
};_x000D_
}).factory('httpResponseInterceptor', function(LoadingService, $timeout, error, $q, requestCount) {_x000D_
function waitAndHide() {_x000D_
$timeout(function() {_x000D_
if (requestCount.get() === 0){_x000D_
LoadingService.hide();_x000D_
}_x000D_
else{_x000D_
waitAndHide();_x000D_
}_x000D_
}, 300);_x000D_
}_x000D_
_x000D_
return {_x000D_
response: function(config) {_x000D_
requestCount.descrease();_x000D_
if (requestCount.get() === 0) {_x000D_
waitAndHide();_x000D_
}_x000D_
return config;_x000D_
},_x000D_
responseError: function(config) {_x000D_
requestCount.descrease();_x000D_
if (requestCount.get() === 0) {_x000D_
waitAndHide();_x000D_
}_x000D_
var deferred = $q.defer();_x000D_
error.show(config.data, function() {_x000D_
deferred.reject(config);_x000D_
});_x000D_
return deferred.promise;_x000D_
}_x000D_
};_x000D_
}).factory('requestCount', function() {_x000D_
var count = 0;_x000D_
return {_x000D_
increase: function() {_x000D_
count++;_x000D_
},_x000D_
descrease: function() {_x000D_
if (count === 0) return;_x000D_
count--;_x000D_
},_x000D_
get: function() {_x000D_
return count;_x000D_
}_x000D_
};_x000D_
})
_x000D_
If you just want to find and replace all environment variables ($ExampleEnvVar) in a Dockerfile then build it this would work:
envsubst < /path/to/Dockerfile | docker build -t myDockerImage . -f -
A today extension would be the most fitting solution.
Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.
var doc = new XmlDocument();
doc.Loadxml(@"c:\abc.xml");
toCharArray
followed by Arrays.sort
followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.
instead of using this
Vue.component('tabs', {
template: `
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
`,
});
you should use
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li class="is-active"><a>Pictures</a></li>
<li><a>Music</a></li>
<li><a>Videos</a></li>
<li><a>Documents</a></li>
</ul>
</div>
<div class="tabs-content">
<slot></slot>
</div>
</div>
`,
});
INSERT INTO Table1(Column1,Column2..) SELECT Column1,Column2.. FROM Table2 [WHERE <condition>]
you can also use the randomizeMatrix
function in the R package picante
example:
test <- matrix(c(1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,0),nrow=4,ncol=4)
> test
[,1] [,2] [,3] [,4]
[1,] 1 0 1 0
[2,] 1 1 0 1
[3,] 0 0 0 0
[4,] 1 0 1 0
randomizeMatrix(test,null.model = "frequency",iterations = 1000)
[,1] [,2] [,3] [,4]
[1,] 0 1 0 1
[2,] 1 0 0 0
[3,] 1 0 1 0
[4,] 1 0 1 0
randomizeMatrix(test,null.model = "richness",iterations = 1000)
[,1] [,2] [,3] [,4]
[1,] 1 0 0 1
[2,] 1 1 0 1
[3,] 0 0 0 0
[4,] 1 0 1 0
>
The option null.model="frequency"
maintains column sums and richness
maintains row sums.
Though mainly used for randomizing species presence absence datasets in community ecology it works well here.
This function has other null model options as well, check out following link for more details (page 36) of the picante
documentation
Bascially there is no concept of class in JS so we use function as a class constructor which is relevant with the existing design patterns.
//Constructor Pattern
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.doSomething = function(){
alert('I am Happy');
}
}
Till now JS has no clue that you want to create an object so here comes the new keyword.
var person1 = new Person('Arv', 30, 'Software');
person1.name //Arv
Ref : Professional JS for web developers - Nik Z
I resolved it by giving permission to the user on each of the directories that you're using, like so:
sudo chown user /home/user/git
and so on.
Leave the quotes off...
var a = {"b":function(){alert('hello world');} };
a.b();
the default encoding of a HTTP POST is ISO-8859-1.
else you have to look at the Content-Type header that will then look like
Content-Type: application/x-www-form-urlencoded ; charset=UTF-8
You can maybe declare your form with
<form enctype="application/x-www-form-urlencoded;charset=UTF-8">
or
<form accept-charset="UTF-8">
to force the encoding.
Some references :
I've adopted Crazy Yoghurt's answer to swift's extensions.
extension UILabel {
func boldRange(_ range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
func boldSubstring(_ substr: String) {
if let text = self.attributedText {
var range = text.string.range(of: substr)
let attr = NSMutableAttributedString(attributedString: text)
while range != nil {
let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
var nsRange = NSMakeRange(start, length)
let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
break
}
range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
}
if let r = range {
boldRange(r)
}
}
}
}
May be there is not good conversion between Range and NSRange, but I didn't found something better.
function daysInMonth (month, year) {_x000D_
return new Date(year, month, 0).getDate();_x000D_
}_x000D_
function getduration(){_x000D_
_x000D_
let A= document.getElementById("date1_id").value_x000D_
let B= document.getElementById("date2_id").value_x000D_
_x000D_
let C=Number(A.substring(3,5))_x000D_
let D=Number(B.substring(3,5))_x000D_
let dif=D-C_x000D_
let arr=[];_x000D_
let sum=0;_x000D_
for (let i=0;i<dif+1;i++){_x000D_
sum+=Number(daysInMonth(i+C,2019))_x000D_
}_x000D_
let sum_alter=0;_x000D_
for (let i=0;i<dif;i++){_x000D_
sum_alter+=Number(daysInMonth(i+C,2019))_x000D_
}_x000D_
let no_of_month=(Number(B.substring(3,5)) - Number(A.substring(3,5)))_x000D_
let days=[];_x000D_
if ((Number(B.substring(3,5)) - Number(A.substring(3,5)))>0||Number(B.substring(0,2)) - Number(A.substring(0,2))<0){_x000D_
days=Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter_x000D_
}_x000D_
_x000D_
if ((Number(B.substring(3,5)) == Number(A.substring(3,5)))){_x000D_
console.log(Number(B.substring(0,2)) - Number(A.substring(0,2)) + sum_alter)_x000D_
}_x000D_
_x000D_
time_1=[]; time_2=[]; let hour=[];_x000D_
time_1=document.getElementById("time1_id").value_x000D_
time_2=document.getElementById("time2_id").value_x000D_
if (time_1.substring(0,2)=="12"){_x000D_
time_1="00:00:00 PM"_x000D_
}_x000D_
if (time_1.substring(9,11)==time_2.substring(9,11)){_x000D_
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))_x000D_
}_x000D_
if (time_1.substring(9,11)!=time_2.substring(9,11)){_x000D_
hour=Math.abs(Number(time_2.substring(0,2)) - Number(time_1.substring(0,2)))+12_x000D_
}_x000D_
let min=Math.abs(Number(time_1.substring(3,5))-Number(time_2.substring(3,5)))_x000D_
document.getElementById("duration_id").value=days +" days "+ hour+" hour " + min+" min " _x000D_
}
_x000D_
<input type="text" id="date1_id" placeholder="28/05/2019">_x000D_
<input type="text" id="date2_id" placeholder="29/06/2019">_x000D_
<br><br>_x000D_
<input type="text" id="time1_id" placeholder="08:01:00 AM">_x000D_
<input type="text" id="time2_id" placeholder="00:00:00 PM">_x000D_
<br><br>_x000D_
<button class="text" onClick="getduration()">Submit </button>_x000D_
<br><br>_x000D_
<input type="text" id="duration_id" placeholder="days hour min">
_x000D_
json_decode
support second argument, when it set to TRUE
it will return an Array
instead of stdClass Object
. Check the Manual page of json_decode
function to see all the supported arguments and its details.
For example try this:
$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!
There's an alternative that's quite unreadable in my opinion but I'll share anyway just as a curiosity:
x = (i>100 and 2) or (i<100 and 1) or 0
More info here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
If the problem is that the label and input are wrapping to two lines when the window is too narrow, remove the whitespace between them; e.g.:
<label for="one">First Item</label>
<input type="radio" id="one" name="first_item" value="1" />
If you need space between the elements, use non-breaking spaces (&
nbsp;
) or CSS.
I has similar problem in context of Stripe:
Error: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.
Forcing TLS 1.2 using CURL parameter is temporary solution or even it can't be applied because of lack of room to place an update. By default TLS test function https://gist.github.com/olivierbellone/9f93efe9bd68de33e9b3a3afbd3835cf showed following configuration:
SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.0
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2
I updated libraries using following command:
yum update nss curl openssl
and then saw this:
SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.2
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2
Please notice that default TLS version changed to 1.2! That globally solved problem. This will help PayPal users too: https://www.paypal.com/au/webapps/mpp/tls-http-upgrade (update before end of June 2017)
By pressing 'Enter' on focused <input type="text">
you trigger 'click' event on the first positioned element: <button>
or <input type="submit">
. If you press 'Enter' in <textarea>
, you just make a new text line.
See the example here.
Your code prevents to make a new text line in <textarea>
, so you have to catch key press only for <input type="text">
.
But why do you need to press Enter
in text field? If you want to submit form by pressing 'Enter', but the <button>
must stay the first in the layout, just play with the markup: put the <input type="submit">
code before the <button>
and use CSS to save the layout you need.
Catching 'Enter' and saving markup:
$('input[type="text"]').keypress(function (e) {
var code = e.keyCode || e.which;
if (code === 13)
e.preventDefault();
$("form").submit(); /*add this, if you want to submit form by pressing `Enter`*/
});
Remove/Replace all special chars in Jquery :
If
str = My name is "Ghanshyam" and from "java" background
and want to remove all special chars (") then use this
str=str.replace(/"/g,' ')
result:
My name is Ghanshyam and from java background
Where g means Global
In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:
get-qadgroupmember 'Domain Admins' | foreach { $_.Name }
This will get you a simple string[]
without column headings or empty lines. The Format-*
cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.
For multiple properties I'd probably go with the -f
format operator. Something along the lines of
alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }
which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)
I'll answer my own questions and sponfeed my fellow linux users:
1- To point JAVA_HOME to the JRE included with Android Studio first locate the Android Studio installation folder, then find the /jre
directory. That directory's full path is what you need to set JAVA_PATH to (thanks to @TentenPonce for his answer).
On linux, you can set JAVA_HOME by adding this line to your .bashrc
or .bash_profile files
:
export JAVA_HOME=<Your Android Studio path here>/jre
This file (one or the other) is the same as the one you added ANDROID_HOME
to if you were following the React Native Getting Started for Linux. Both are hidden by default and can be found in your home directory. After adding the line you need to reload the terminal so that it can pick up the new environment variable. So type:
source $HOME/.bash_profile
or
source $HOME/.bashrc
and now you can run react-native run-android
in that same terminal. Another option is to restart the OS. Other terminals might work differently.
NOTE: for the project to actually run, you need to start an Android emulator in advance, or have a real device connected. The easiest way is to open an already existing Android Studio project and launch the emulator from there, then close Android Studio.
2- Since what react-native run-android
appears to do is just this:
cd android && ./gradlew installDebug
You can actually open the nested android project with Android Studio and run it manually. JS changes can be reloaded if you enable live reload in the emulator. Type CTRL + M (CMD + M on MacOS) and select the "Enable live reload" option in the menu that appears (Kudos to @BKO for his answer)
Remove pod name from Podfile
then
Open Terminal, set project folder path and
Run pod update
command.
NOTE: pod update
will update all the libraries to the latest version and will also remove those libraries whose name have been removed from podfile.
That's not yet implemented according this Microsoft Connect link: Microsoft Connect
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
As far as I know there are three methods you can do that.
1.use regular expression to get query string.
2.you can use the browser api. image the current url is like this:
http://www.google.com.au?token=123
we just want to get 123;
First
const query = new URLSearchParams(this.props.location.search);
Then
const token = query.get('token')
console.log(token)//123
3. use a third library called 'query-string'. First install it
npm i query-string
Then import it to the current javascript file:
import queryString from 'query-string'
Next step is to get 'token' in the current url, do the following:
const value=queryString.parse(this.props.location.search);
const token=value.token;
console.log('token',token)//123
Hope it helps.
Updated on 25/02/2019
http://www.google.com.au?app=home&act=article&aid=160990
we define a function to get the parameters:
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
console.log(query)//"app=article&act=news_content&aid=160990"
var vars = query.split("&");
console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ]
if(pair[0] == variable){return pair[1];}
}
return(false);
}
We can get 'aid' by :
getQueryVariable('aid') //160990
==
has higher precedence than &
. You might want to wrap your operations in ()
to specify how you want your operands to bind to the operators.
((a[0] & 1) == 0)
Similarly for all parts of the if
condition.
I assume you're trying to tunnel into some unix box.
Make sure X11 forwarding is enabled in your PuTTY settings.
I do not know how to solve this problem differently, but this is solved simply. The loader babel should be placed at the beginning of the array and everything works.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
You can try this:
echo n | copy /-y <SOURCE> <DESTINATION>
-y
simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)
$('form :input').change(function() {
// Something has changed
});
None of these worked for me in SSIS v18.0, so I would up doing something like this:
WHERE CHARINDEX('_', thingyoursearching) < 1
..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:
WHERE CHARINDEX('_', thingyoursearching) > 0
Using jquery, try this. if your button id is say id= clickme
$("clickme").on('çlick', function(){
$(this).css('background-color', 'grey'); .......
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
Check the column collation. This script might change the collation to the table default. Add the current collation to the script.
Just so you know the iPhone 6 lies about it's min-width. It thinks it is 320 instead of 375 it is suppose to be.
@media only screen and (max-device-width: 667px)
and (-webkit-device-pixel-ratio: 2) {
}
This was the only thing I could get to work to target the iPhone 6. The 6+ works fine the using this method:
@media screen and (min-device-width : 414px)
and (max-device-height : 736px) and (max-resolution: 401dpi)
{
}
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType
and set data
without double quotes.
Just use:
<TextBlock Text="{Binding Date, StringFormat=\{0:d\}}" />
In Eclipse Mars.2 Release (4.5.2):
Project Explorer -> Context menu -> Properties -> JavaBuildPath -> Libraries
select JRE... and press Edit: Switch to Workspace JRE (jdk1.8.0_77)
Works for me.
@samwize's solution in Swift (so upvote him!). Brilliant using same recycling mechanism also for header/footer sections:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell
return settingsHeaderSectionCell
}
The sane way to do this is to use zip()
and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array()
or numpy.array()
, then most likely you are using []
or list()
, which give you Lists, not Arrays. Not the same thing.
To print the second line:
awk 'FNR == 2 {print}'
To print the second field:
awk '{print $2}'
To print the third field of the fifth line:
awk 'FNR == 5 {print $3}'
Here's an example with a header line and (redundant) field descriptions:
awk 'BEGIN {print "Name\t\tAge"} FNR == 5 {print "Name: "$3"\tAge: "$2}'
There are better ways to align columns than "\t\t" by the way.
Use exit
to stop as soon as you've printed the desired record if there's no reason to process the whole file:
awk 'FNR == 2 {print; exit}'
I want to make some unit test to get maximal code coverage
Code coverage should never be the goal of writing unit tests. You should write unit tests to prove that your code is correct, or help you design it better, or help someone else understand what the code is meant to do.
but I dont see how I can test my method checkIfValidElements, it returns nothing or change nothing.
Well you should probably give a few tests, which between them check that all 7 methods are called appropriately - both with an invalid argument and with a valid argument, checking the results of ErrorFile
each time.
For example, suppose someone removed the call to:
method4(arg1, arg2);
... or accidentally changed the argument order:
method4(arg2, arg1);
How would you notice those problems? Go from that, and design tests to prove it.
The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).
This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
(emphasis mine)
If you use MVC 3 and .NET 4, you can use the new Display
attribute in the System.ComponentModel.DataAnnotations
namespace. This attribute replaces the DisplayName
attribute and provides much more functionality, including localization support.
In your case, you would use it like this:
public class MyModel
{
[Required]
[Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
public string name{ get; set; }
}
As a side note, this attribute will not work with resources inside App_GlobalResources
or App_LocalResources
. This has to do with the custom tool (GlobalResourceProxyGenerator
) these resources use. Instead make sure your resource file is set to 'Embedded resource' and use the 'ResXFileCodeGenerator' custom tool.
(As a further side note, you shouldn't be using App_GlobalResources
or App_LocalResources
with MVC. You can read more about why this is the case here)
In your CSS stylesheet, try adding:
input[type="text"] {
font-size:25px;
}
See this jsFiddle example
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
From JSP
<form method="post" id="myForm" action="someURL">
<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
</form>
This is the simplest way that worked for me after struggling for 3hrs, just get the token from input hidden field like this and while doing the AJAX request to just need to pass this token in header as follows:-
From Jquery
var token = $('input[name="csrfToken"]').attr('value');
From plain Javascript
var token = document.getElementsByName("csrfToken").value;
Final AJAX Request
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
Now you don't need to disable crsf security in web config, and also this will not give you 405( Method Not Allowed) error on console.
Hope this will help people..!!
Try disabling iptables: service iptables stop
If this works, enable TCP port 80 to your firewall rules: run system-config-selinux from root, and enable TCP port 80 (HTTP) on your firewall.
I found solution. The call:
-(void) someMethod{
UIButton * but;
but.tag = 1;//some id button that you choice
[but addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
And here the method called:
-(void) buttonPressed : (id) sender{
UIButton *clicked = (UIButton *) sender;
NSLog(@"%d",clicked.tag);//Here you know which button has pressed
}
For a 32-bit JVM running on a 64-bit host, I imagine what's left over for the heap will be whatever unfragmented virtual space is available after the JVM, it's own DLL's, and any OS 32-bit compatibility stuff has been loaded. As a wild guess I would think 3GB should be possible, but how much better that is depends on how well you are doing in 32-bit-host-land.
Also, even if you could make a giant 3GB heap, you might not want to, as this will cause GC pauses to become potentially troublesome. Some people just run more JVM's to use the extra memory rather than one giant one. I imagine they are tuning the JVM's right now to work better with giant heaps.
It's a little hard to know exactly how much better you can do. I guess your 32-bit situation can be easily determined by experiment. It's certainly hard to predict abstractly, as a lot of things factor into it, particularly because the virtual space available on 32-bit hosts is rather constrained.. The heap does need to exist in contiguous virtual memory, so fragmentation of the address space for dll's and internal use of the address space by the OS kernel will determine the range of possible allocations.
The OS will be using some of the address space for mapping HW devices and it's own dynamic allocations. While this memory is not mapped into the java process address space, the OS kernel can't access it and your address space at the same time, so it will limit the size of any program's virtual space.
Loading DLL's depends on the implementation and the release of the JVM. Loading the OS kernel depends on a huge number of things, the release, the HW, how many things it has mapped so far since the last reboot, who knows...
I bet you get 1-2 GB in 32-bit-land, and about 3 in 64-bit, so an overall improvement of about 2x.
You can decompile an apk on Android device using this : https://play.google.com/store/apps/details?id=com.njlabs.showjava
For more info look here: http://forum.xda-developers.com/showthread.php?t=2601315
EDIT: 28-02-2015
For decompiling an apk you can use this tool: https://apkstudio.codeplex.com/license
If that doesnt help check this link
You'll need to add a firewall rule to open inbound access to tcp:9090
to your instances. If you have more than the two instances, and you only want to open 9090 to those two, you'll want to make sure that there is a tag that those two instances share. You can add or update tags via the console or the command-line; I'd recommend using the GUI for that if needed because it handles the read-modify-write cycle with setinstancetags
.
If you want to open port 9090 to all instances, you can create a firewall rule like:
gcutil addfirewall allow-9090 --allowed=tcp:9090
which will apply to all of your instances.
If you only want to open port 9090 to the two instances that are serving your application, make sure that they have a tag like my-app
, and then add a firewall like so:
gcutil addfirewall my-app-9090 --allowed=tcp:9090 --target_tags=my-app
You can read more about creating and managing firewalls in GCE here.
In windows you should use %WORKSPACE%
.
Before trying to delete/rename any file, you must ensure that all the readers or writers (for ex: BufferedReader
/InputStreamReader
/BufferedWriter
) are properly closed.
When you try to read/write your data from/to a file, the file is held by the process and not released until the program execution completes. If you want to perform the delete/rename operations before the program ends, then you must use the close()
method that comes with the java.io.*
classes.
I had the same problem in Xcode 11.5 after revoking a certificate through Apple's developer homepage and adding it again (even though it looked different afterwards):
Every time I tried to archive my app, it would fail at the very end (not the pods but my actual app) with the same PhaseScriptExecution failed with a nonzero exit code
error message. There is/was a valid team with an "Apple Development" signing certificate in "Signing & Capabilities" (project file in Xcode) and locking & unlocking the keychain, cleaning & building the project, restarting,... didn't work.
The problem was caused by having two active certificates of the same type that I must have added on accident, in addition to the renewed one. I deleted both the renewed one and the duplicate and it worked again.
You can find your certificates here or find the page like this:
Also check that there aren't any duplicates in your keychain! Be careful though - don't delete or add anything unless you know what you're doing, otherwise you might create a huge mess!
I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.
Edit:
I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251
The cost of a connection(with epoll):
Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.
Functions that might be helpful:
open("file").read()
which reads the contents of the whole file at once'string'.splitlines()
which separates lines from each other (and discards empty lines)By using len() and those functions you could accomplish what you're doing.
You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.
6.7.8 Initialization
...
3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
Android Cloud to Device Messaging Framework
Important: C2DM has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.
Kindly check the following link:
I had Firefox 47 and Selenium 2.53, and i got the same error. My solution was change Firefox 47 to Firefox 46, the problem was solved.
require 'uri'
class Hash
def to_query_hash(key)
reduce({}) do |h, (k, v)|
new_key = key.nil? ? k : "#{key}[#{k}]"
v = Hash[v.each_with_index.to_a.map(&:reverse)] if v.is_a?(Array)
if v.is_a?(Hash)
h.merge!(v.to_query_hash(new_key))
else
h[new_key] = v
end
h
end
end
def to_query(key = nil)
URI.encode_www_form(to_query_hash(key))
end
end
2.4.2 :019 > {:a => "a", :b => "b"}.to_query_hash(nil)
=> {:a=>"a", :b=>"b"}
2.4.2 :020 > {:a => "a", :b => "b"}.to_query
=> "a=a&b=b"
2.4.2 :021 > {:a => "a", :b => ["c", "d", "e"]}.to_query_hash(nil)
=> {:a=>"a", "b[0]"=>"c", "b[1]"=>"d", "b[2]"=>"e"}
2.4.2 :022 > {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B0%5D=c&b%5B1%5D=d&b%5B2%5D=e"
I'd do it this way:
# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye', ''}
no = {'no','n'}
choice = raw_input().lower()
if choice in yes:
return True
elif choice in no:
return False
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
You have to go to the "Pricing" menu. Even if the availability date is in the past, sometimes you have to set it again for today's date. Apple doesn't tell you to do this, but I found that the app goes live after resetting the dates again, especially if there's been app rejections in the past. I guess it messes up with the dates. Looks like sometimes if you do nothing and just follow the instructions, the app will never go live.
Download javax.mail.jar
and add it to your project using the following steps:
Not pretty, but here is a way to implement an exit()
command in R which works for me.
exit <- function() {
.Internal(.invokeRestart(list(NULL, NULL), NULL))
}
print("this is the last message")
exit()
print("you should not see this")
Only lightly tested, but when I run this, I see this is the last message
and then the script aborts without any error message.
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo)
is invoked and the return value is assigned to onClick
What you have to provide for onClick
is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
Although there isn’t complete agreement on the distinction between the terms parallel and concurrent, many authors make the following distinctions:
So parallel programs are concurrent, but a program such as a multitasking operating system is also concurrent, even when it is run on a machine with only one core, since multiple tasks can be in progress at any instant.
Source: An introduction to parallel programming, Peter Pacheco
Try this is act as you have to press the back button
finish();
super.onBackPressed();
There are multiple horizontal centering methods in Bootstrap 4...
text-center
for center display:inline
elementsoffset-*
or mx-auto
can be used to center column (col-*
)justify-content-center
on the row
to center columns (col-*
)mx-auto
for centering display:block
elements inside d-flex
mx-auto
(auto x-axis margins) will center display:block
or display:flex
elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.
Demo of the Bootstrap 4 Centering Methods
In your case, use mx-auto
to center the col-3
and text-center
to center it's content..
<div class="row">
<div class="col-3 mx-auto">
<div class="text-center">
center
</div>
</div>
</div>
https://codeply.com/go/GRUfnxl3Ol
or, using justify-content-center
on flexbox elements (.row
):
<div class="container">
<div class="row justify-content-center">
<div class="col-3 text-center">
center
</div>
</div>
</div>
Also see:
Vertical Align Center in Bootstrap 4
If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.
If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.
Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.
In Android Studio:
Build
Build APK(s)
Wait and go to the location shown in a pop-up window. On right bottom side
In the Powershell, cd to the .exe file location. For example:
cd C:\Users\Administrators\Downloads
PS C:\Users\Administrators\Downloads> & '.\aaa.exe'
The installer pops up and follow the instruction on the screen.
i think you can use more than one class in a tag
for example:
<div class="whatever base"></div>
<div class="whatever2 base"></div>
so when you want to chage all div's color you can just change the .base
...i dont know how to inherit in CSS
Not all programs do the same thing or run on the same hardware.
This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.
In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.
When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.
I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.
I realize this is a very old question with an accepted answer, but none of these answers actually use the approach suggested by the hint.
It is a pretty simple argument:
n!
(= 1*2*3*...*n) is a product of n
numbers each less than or equal to n
. Therefore it is less than the product of n
numbers all equal to n
; i.e., n^n
.
Half of the numbers -- i.e. n/2
of them -- in the n!
product are greater than or equal to n/2
. Therefore their product is greater than the product of n/2
numbers all equal to n/2
; i.e. (n/2)^(n/2)
.
Take logs throughout to establish the result.
The following php snippets would return the text between html tags/elements.
regex : "/tagname(.*)endtag/" will return text between tags.
i.e.
$regex="/[start_tag_name](.*)[/end_tag_name]/";
$content="[start_tag_name]SOME TEXT[/end_tag_name]";
preg_replace($regex,$content);
It will return "SOME TEXT".
Oops, immediately found 2//2
.
JS .trim() is supported in basically everthing, except IE 8 and below.
If you want it to work with that, then, you can use JQuery, but it'll need to be <2.0.0 (as they removed support for IE8 in the 2.x.x line).
Your other option, if you care about IE7/8 (As you mention earlier), is to add trim yourself:
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
I faced same error but in a different way.
When you curl a page with a specific SSL protocol.
curl --sslv3 https://example.com
If --sslv3 is not supported by the target server then the error will be
curl: (35) TCP connection reset by peer
With the supported protocol, error will be gone.
curl --tlsv1.2 https://example.com
Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.
In the example below changes to the Controller $scope.count
variable will automatically be reflected in the Service count
variable.
In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.
The code below can be seen working at http://jsfiddle.net/xuUHS/163/
View:
<div ng-controller="ServiceCtrl">
<p> This is my countService variable : {{count}}</p>
<input type="number" ng-model="count">
<p> This is my updated after click variable : {{countS}}</p>
<button ng-click="clickC()" >Controller ++ </button>
<button ng-click="chkC()" >Check Controller Count</button>
</br>
<button ng-click="clickS()" >Service ++ </button>
<button ng-click="chkS()" >Check Service Count</button>
</div>
Service/Controller:
var app = angular.module('myApp', []);
app.service('testService', function(){
var count = 10;
function incrementCount() {
count++;
return count;
};
function getCount() { return count; }
return {
get count() { return count },
set count(val) {
count = val;
},
getCount: getCount,
incrementCount: incrementCount
}
});
function ServiceCtrl($scope, testService)
{
Object.defineProperty($scope, 'count', {
get: function() { return testService.count; },
set: function(val) { testService.count = val; },
});
$scope.clickC = function () {
$scope.count++;
};
$scope.chkC = function () {
alert($scope.count);
};
$scope.clickS = function () {
++testService.count;
};
$scope.chkS = function () {
alert(testService.count);
};
}
For anyone finding this, swipe on carousel appears to be native as of about 5 days ago (20 Oct 2018) as per
https://github.com/twbs/bootstrap/pull/25776
https://deploy-preview-25776--twbs-bootstrap4.netlify.com/docs/4.1/components/carousel/
Not sure where I picked up this pattern but for sharing data across controllers and reducing the $rootScope and $scope this works great. It is reminiscent of a data replication where you have publishers and subscribers. Hope it helps.
The Service:
(function(app) {
"use strict";
app.factory("sharedDataEventHub", sharedDataEventHub);
sharedDataEventHub.$inject = ["$rootScope"];
function sharedDataEventHub($rootScope) {
var DATA_CHANGE = "DATA_CHANGE_EVENT";
var service = {
changeData: changeData,
onChangeData: onChangeData
};
return service;
function changeData(obj) {
$rootScope.$broadcast(DATA_CHANGE, obj);
}
function onChangeData($scope, handler) {
$scope.$on(DATA_CHANGE, function(event, obj) {
handler(obj);
});
}
}
}(app));
The Controller that is getting the new data, which is the Publisher would do something like this..
var someData = yourDataService.getSomeData();
sharedDataEventHub.changeData(someData);
The Controller that is also using this new data, which is called the Subscriber would do something like this...
sharedDataEventHub.onChangeData($scope, function(data) {
vm.localData.Property1 = data.Property1;
vm.localData.Property2 = data.Property2;
});
This will work for any scenario. So when the primary controller is initialized and it gets data it would call the changeData method which would then broadcast that out to all the subscribers of that data. This reduces the coupling of our controllers to each other.
In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.
Use the title
attribute, for example:
<div title="them's hoverin' words">hover me</div>
_x000D_
or:
<span title="them's hoverin' words">hover me</span>
_x000D_
File > Settings > Editor > Code Style > Java > Tabs and Indents > Use tab character
Substitute weapon of choice for Java as required.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Just to add to the other examples, there are inner(nested) classes that appear with the $
sign. For example:
public class Test {
private static void privateMethod() {
throw new RuntimeException();
}
public static void main(String[] args) throws Exception {
Runnable runnable = new Runnable() {
@Override public void run() {
privateMethod();
}
};
runnable.run();
}
}
Will result in this stack trace:
Exception in thread "main" java.lang.RuntimeException
at Test.privateMethod(Test.java:4)
at Test.access$000(Test.java:1)
at Test$1.run(Test.java:10)
at Test.main(Test.java:13)
com.android.support:support-v4 just recently got update and maybe affect to plugin that use updated version in their dependencies. But if you cannot find in the dependencies (like if you use crosswalk plugin), just put this code in top of your code gradle plugin (no need to add on build.gradle).
configurations.all {
resolutionStrategy.force 'com.android.support:support-v4:24.0.0'
}
Example location to put the code in crosswalk plugin here
Feel free to edit version of com.android.support (DO NOT USE THE 28.0.0) because thats the problem
Yes, convert it to a string once the loop is done:
String str = data.ToString().TrimEnd(',');
For SQL Server, CROSS JOIN and FULL OUTER JOIN
are different.
CROSS JOIN
is simply Cartesian Product of two tables, irrespective of any filter criteria or any condition.
FULL OUTER JOIN
gives unique result set of LEFT OUTER JOIN and RIGHT OUTER JOIN
of two tables. It also needs ON clause to map two columns of tables.
Table 1 contains 10 rows and Table 2 contains 20 rows with 5 rows matching on specific columns.
Then
CROSS JOIN
will return 10*20=200 rows in result set.
FULL OUTER JOIN
will return 25 rows in result set.
FULL OUTER JOIN
(or any other JOIN) always returns result set with less than or equal toCartesian Product number
.Number of rows returned by
FULL OUTER JOIN
equal to (No. of Rows byLEFT OUTER JOIN
) + (No. of Rows byRIGHT OUTER JOIN
) - (No. of Rows byINNER JOIN
).
By merging some of the techniques over here I came up with the simplest form:
#define MACROSTR(k) #k
#define X_NUMBERS \
X(kZero ) \
X(kOne ) \
X(kTwo ) \
X(kThree ) \
X(kFour ) \
X(kMax )
enum {
#define X(Enum) Enum,
X_NUMBERS
#undef X
} kConst;
static char *kConstStr[] = {
#define X(String) MACROSTR(String),
X_NUMBERS
#undef X
};
int main(void)
{
int k;
printf("Hello World!\n\n");
for (k = 0; k < kMax; k++)
{
printf("%s\n", kConstStr[k]);
}
return 0;
}
VTD-XML is the heavy duty XML parsing lib... it is better than others in virtually every way... here is a 2013 paper that analyzes all XML processing frameworks available in java platform...
http://sdiwc.us/digitlib/journal_paper.php?paper=00000582.pdf
If you run into this issue in a fairly complex app it can be cumbersome to refactor all your imports. PyCharm offers a quickfix for this that will automatically change all usage of the imported symbols as well.
If the instance is in VPC, make sure both "DNS resolution" and "DNS hostnames" is set to "yes". You can do this in the Aws console UI. HTH!
It does not matter which extension you use. Either one is OK.
I use *.h
for C and *.hpp
for C++.
EDIT: This was written in 2014. You probably don't care about IE8 anymore and can forget about using innerText
. Just use textContent
and be done with it, hooray.
If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML
might be acceptable:
// * Fine for hardcoded text strings like this one or strings you otherwise
// control.
// * Not OK for user-supplied input or strings you don't control unless
// you know what you are doing and have sanitized the string first.
document.getElementById('myspan').innerHTML = 'newtext';
However, as others note, if you are not the source for any part of the text string, using innerHTML
can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.
If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:
var span = document.getElementById('myspan');
span.innerText = span.textContent = 'newtext';
Firefox doesn't support innerText
and IE8 doesn't support textContent
so you need to use both if you want to maintain cross-browser compatibility.
And if you want to avoid reflows (caused by innerText
) where possible:
var span = document.getElementById('myspan');
if ('textContent' in span) {
span.textContent = 'newtext';
} else {
span.innerText = 'newtext';
}
If you have url with path variables, example www.myexampl.com/item/12/update where 12 is the id and create is the variable you want to use for specifying your execution for instance in using a single form to do an update and create, you do this in your controller.
@PostMapping(value = "/item/{id}/{method}")
public String getForm(@PathVariable("id") String itemId ,
@PathVariable("method") String methodCall , Model model){
if(methodCall.equals("create")){
//logic
}
if(methodCall.equals("update")){
//logic
}
return "path to your form";
}
If you want all packages in that repository, use ...
to signify that, like:
go get code.google.com/p/go.text/...
I was not able to resolve this after several hours. Eventually I just did a select with the two tables joined, created an extract and created individual SQL update statements for the 500 rows in the table. Ugly but beats spending hours trying to get a query to work.
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
Also you can use agg function,
df.groupby(['Name', 'Fruit'])['Number'].agg('sum')
Just my 2 cents as stated in the answer above : The copy() method shouldn't be used as-is for copying files without a slight adjustment:
function copy(callback) {
var readStream = fs.createReadStream(oldPath);
var writeStream = fs.createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
// Do not callback() upon "close" event on the readStream
// readStream.on('close', function () {
// Do instead upon "close" on the writeStream
writeStream.on('close', function () {
callback();
});
readStream.pipe(writeStream);
}
The copy function wrapped in a Promise:
function copy(oldPath, newPath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(oldPath);
const writeStream = fs.createWriteStream(newPath);
readStream.on('error', err => reject(err));
writeStream.on('error', err => reject(err));
writeStream.on('close', function() {
resolve();
});
readStream.pipe(writeStream);
})
However, keep in mind that the filesystem might crash if the target folder doesn't exist.
Might it be possible that you're using a WCF-based web service reference? By default, the ServiceThrottlingBehavior.MaxConcurrentCalls is 16.
You could try updating your service reference behavior's <serviceThrottling>
element
<serviceThrottling
maxConcurrentCalls="999"
maxConcurrentSessions="999"
maxConcurrentInstances="999" />
(Note that I'd recommend the settings above.) See MSDN for more information how to configure an appropriate <behavior>
element.
Javascript is client-side, you cannot email with Javascript. Browser recognizes maybe only mailto:
and starts your default mail client.
That's because, it gets returned after validateView();;
Use this:
OnClientClick="var ret = validateView();ShowDiv1(); return ret;"
use the "maxlength" attribute as others have said.
if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript
I'm using boot2docker to run docker containers with Tomcat inside and I've got the same problem, the solution was to:
-Djava.rmi.server.hostname=192.168.59.103
docker run ... -p 9999:9999 ...
. Using different ports does not work.Why not simply
var item = $('.field-item');
for (var i = 0; i <= item.length; i++) {
if ($(item[i]).text() == 'someText') {
$(item[i]).addClass('thisClass');
//do some other stuff here
}
}
Standard Security
Data Source=serverName\instanceName;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Data Source=serverName\instanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;
Here's a good reference on connection strings that I keep handy: ConnectionStrings.com
I have found an app on the store which can show the name / process of a log. Since Android Studio just puts a (?) on the logs being generated by the other processes, I found it useful to know which process is generating this log. But still this app is missing the filter by the process name. You can find it here.
My solution (VS 2013) was to run as an administrator
In both Visual Basic 6.0 and VB.NET you would use:
Exit For
to break from For loopWend
to break from While loopExit Do
to break from Do loopdepending on the loop type. See Exit Statements for more details.
Actually, for functional component the best practice is like below, I create a sample Spinner component:
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { colors } from 'helpers/theme';
import type { FC } from 'types';
interface SpinnerProps {
color?: string;
size?: 'small' | 'large' | 1 | 0;
animating?: boolean;
hidesWhenStopped?: boolean;
}
const Spinner: FC<SpinnerProps> = ({
color,
size,
animating,
hidesWhenStopped,
}) => (
<ActivityIndicator
color={color}
size={size}
animating={animating}
hidesWhenStopped={hidesWhenStopped}
/>
);
Spinner.defaultProps = {
animating: true,
color: colors.primary,
hidesWhenStopped: true,
size: 'small',
};
export default Spinner;
I am not a coder, but you could save a few lines:
<div>
<select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
<option value="">hire me for real estate</option>
<option value="me!!!">Who is a good Broker? </option>
<option value="yes!!!">Can I buy a house with no down payment</option>
<option value="send me a note!">Get my contact info?</option>
</select>
</div>
<div id="less_is_more"></div>
Here is demo.
In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
If it's a query you run often, you can store it in a file. Then any time you want to run it:
mysql < thefile
(with all the login and database flags of course)
I finally figured it out doing this:
var $your-original-element = $('.your-original-element');
var data = $your-original-element.select2('data')[0]['text'];
alert(data);
if you also want the value:
var value = $your-original-element.select2('data')[0]['id'];
alert(value);
Using a vector
of shared_ptr
removes the possibility of leaking memory because you forgot to walk the vector and call delete
on each element. Let's walk through a slightly modified version of the example line-by-line.
typedef boost::shared_ptr<gate> gate_ptr;
Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vector<boost::shared_ptr<gate> >
and forgetting the space between the closing greater-than signs.
std::vector<gate_ptr> vec;
Creates an empty vector of boost::shared_ptr<gate>
objects.
gate_ptr ptr(new ANDgate);
Allocate a new ANDgate
instance and store it into a shared_ptr
. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr
"Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.
vec.push_back(ptr);
This creates a new shared pointer in the vector and copies ptr
into it. The reference counting in the guts of shared_ptr
ensures that the allocated object inside of ptr
is safely transferred into the vector.
What is not explained is that the destructor for shared_ptr<gate>
ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector<T>
ensures that the destructor for T
is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*
) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr
or ptr_vector
.
It's not really an IDE per se, but I really like TextMate, and with the C++ bundle that ships with it, it can do a lot of the things you'd find in an IDE (without all the bloat!).
Although the answers are 100% correct, a small suggestion to improve null
case handling of the list itself with Optional:
List<String> listOfStuffFiltered = Optional.ofNullable(listOfStuff)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
The part Optional.ofNullable(listOfStuff).orElseGet(Collections::emptyList)
will allow you to handle nicely the case when listOfStuff
is null and return an emptyList instead of failing with NullPointerException.
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.
This depends a bit from your package system ... if the java
command works, you can type readlink -f $(which java)
to find the location of the java command. On the OpenSUSE system I'm on now it returns /usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/bin/java
(but this is not a system which uses apt-get
).
On Ubuntu, it looks like it is in /usr/lib/jvm/java-6-openjdk/
for OpenJDK, and in some other subdirectory of /usr/lib/jvm/
for Suns JDK (and other implementations as well, I think).
For any given package you can determine what files it installs and where it installs them by querying dpkg. For example for the package 'openjdk-6-jdk': dpkg -L openjdk-6-jdk
Use
:set wrap
To wrap lines visually, i.e. the line is still one line of text, but Vim displays it on multiple lines.
Use
:set nowrap
To display long lines as just one line (i.e. you have to scroll horizontally to see the entire line).
Handlebars can use an array as the context. You can use .
as the root of the data. So you can loop through your array data with {{#each .}}
.
var data = [_x000D_
{_x000D_
Category: "General",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - General",_x000D_
DocumentLocation: "Document Location 1 - General"_x000D_
},_x000D_
{_x000D_
DocumentName: "Document Name 2 - General",_x000D_
DocumentLocation: "Document Location 2 - General"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Unit Documents",_x000D_
DocumentList: [_x000D_
{_x000D_
DocumentName: "Document Name 1 - Unit Documents",_x000D_
DocumentList: "Document Location 1 - Unit Documents"_x000D_
}_x000D_
]_x000D_
},_x000D_
{_x000D_
Category: "Minutes"_x000D_
}_x000D_
];_x000D_
_x000D_
$(function() {_x000D_
var source = $("#document-template").html();_x000D_
var template = Handlebars.compile(source);_x000D_
var html = template(data);_x000D_
$('#DocumentResults').html(html);_x000D_
});
_x000D_
.row {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="DocumentResults">pos</div>_x000D_
<script id="document-template" type="text/x-handlebars-template">_x000D_
<div>_x000D_
{{#each .}}_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<h2>{{Category}}</h2>_x000D_
{{#DocumentList}}_x000D_
<p>{{DocumentName}} at {{DocumentLocation}}</p>_x000D_
{{/DocumentList}}_x000D_
</div>_x000D_
</div>_x000D_
{{/each}}_x000D_
</div>_x000D_
</script>
_x000D_
You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :
df[df['a']==1]['b'].sum()
or you can also try :
sum(df[df['a']==1]['b'])
Another way could be to use the numpy library of python :
import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())
I like to run a "bare-bones" version of Python 2 to verify scripts that I create for other people without an advanced python setup. But Anaconda and Python 3 have a lot of nice features. To enjoy both things on the same computer I do this on my Windows computer which allows me to easily switch.
C:\Users>python --version
Python 2.7.11
C:\Users>conda create --name p3 python=3
C:\Users>conda info --envs
Using Anaconda Cloud api site https://api.anaconda.org
# conda environments:
#
p3 C:\Anaconda3\envs\p3
root * C:\Anaconda3
C:\Users>activate p3
Deactivating environment "C:\Anaconda3"...
Activating environment "C:\Anaconda3\envs\p3"...
[p3] C:\Users>python --version
Python 3.5.1 :: Continuum Analytics, Inc.
For more info: http://conda.pydata.org/docs/test-drive.html
One more thing to check; for me it was Fusion logging.
I'd turned this on a very long time ago and more or less forgotten about it. Getting rid of the 5000+ directories and 1 GB of logged files worked wonders.
If you want to table do following steps:-
views.py:
def view_info(request):
objs=Model_name.objects.all()
............
return render(request,'template_name',{'objs':obj})
.html page
{% for item in objs %}
<tr>
<td>{{ item.field1 }}</td>
<td>{{ item.field2 }}</td>
<td>{{ item.field3 }}</td>
<td>{{ item.field4 }}</td>
</tr>
{% endfor %}
Don't cast unless you must. There's nothign wrong with calling toString().
Change the file content of c:\wamp\alias\phpmyadmin.conf
to the following.
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
</Directory>
Here my WAMP installation is in the c:\wamp folder. Change it according to your installation.
Previously, it was like this:
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
Restart your Apache server after making these changes.
Use the STR
function:
SELECT STR(field_name) FROM table_name
float_expression
Is an expression of approximate numeric (float) data type with a decimal point.
length
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.
source: https://msdn.microsoft.com/en-us/library/ms189527.aspx
Along the lines of Tim Down's answer but leveraging jQuery
(mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:
In the iframe:
<script>
$(function() {
var w = window;
if (w.frameElement != null
&& w.frameElement.nodeName === "IFRAME"
&& w.parent.jQuery) {
w.parent.jQuery(w.parent.document).trigger('iframeready');
}
});
</script>
In the containing page:
<script>
function myHandler() {
alert('iframe (almost) loaded');
}
$(document).on('iframeready', myHandler);
</script>
The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.
This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.
Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:
$(window).on('load', function() { ... });
printf
printf("control string ", argument );
fprintf
fprintf (filename, "control string ", argument );
Using Stateless Functional Component We will not be using this.state. Like this
{data1.map((item,key)=>
{ return
<tr key={key}>
<td>{item.heading}</td>
<td>{item.date}</td>
<td>{item.status}</td>
</tr>
})}
Why not use PHP! It's all server side:
<?php print file_get_contents("http://foo.com")?>
If you own both sites, you may need to ok this transaction with full declaration of headers at the server end. Works beautifully.
var express = require('express')
app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);
var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')
aws.config.update({
secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
region: 'us-east-1'
});
s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
dirname: "uploads",
bucket: "Your bucket name",
key: function (req, file, cb) {
console.log(file);
cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use
Date.now() for unique file keys
}
})
});
app.post('/upload', upload.single('photos'), function(req, res, next) {
console.log('Successfully uploaded ', req.file)
res.send('Successfully uploaded ' + req.file.length + ' files!')
})
Instead of the *
selector you can use the :not(selector)
with the >
selector and set something that definitely wont be a child.
Edit: I thought it would be faster but it turns out I was wrong. Disregard.
Example:
.container > :not(marquee){
color:red;
}
<div class="container">
<p></p>
<span></span>
<div>
The response provided by Ranveer (second answer above) absolutely does NOT work.
He says to use col-xx-offset-#
, but that is not how offsets are used.
If you wasted your time trying to use col-xx-offset-#
, as I did based on his answer, the solution is to use offset-xx-#
.
if you are using target sdk as 23 add below code in your build.gradle
android{
useLibrary 'org.apache.http.legacy'
}
additional note here: dont try using the gradle versions of those files. they are broken (28.08.15). I tried over 5 hours to get it to work. it just doesnt. not working:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
another thing dont use:
'org.apache.httpcomponents:httpclient-android:4.3.5.1'
its referring 21 api level.
The class attribute can contain multiple styles, so you could specify it as
<tr class="row-even highlight">
and do string manipulation to remove 'highlight' from element.className
element.className=element.className.replace('hightlight','');
Using jQuery would make this simpler as you have the methods
$("#id").addClass("highlight");
$("#id").removeClass("hightlight");
that would enable you to toggle highlighting easily
You must set your query base to the DN of the user in question, then set your filter to the DN of the group you're wondering if they're a member of. To see if jdoe is a member of the office group then your query will look something like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host '(memberof=cn=officegroup,dc=example,dc=local)'
If you want to see ALL the groups he's a member of, just request only the 'memberof' attribute in your search, like this:
ldapsearch -x -D "ldap_user" -w "user_passwd" -b "cn=jdoe,dc=example,dc=local" -h ldap_host **memberof**
Dont forget that you can sometimes just fall off the end of the block to get to the next iteration:
$(".row").each( function() {
if ( ! leaveTheLoop ) {
... do stuff here ...
}
});
Rather than actually returning like this:
$(".row").each( function() {
if ( leaveTheLoop )
return; //go to next iteration in .each()
... do stuff here ...
});
A viable option, and one that I have personally used, would be to add your own header to the first line of the file. I did this for a custom model format for my game. Basically, I have a tool that optimizes my .obj files, getting rid of the crap I don't need, converts them to a better layout, and then writes the total number of lines, faces, normals, vertices, and texture UVs on the very first line. That data is then used by various array buffers when the model is loaded.
This is also useful because you only need to loop through the file once to load it in, instead of once to count the lines, and again to read the data into your created buffers.
span
is an inline element that doesn't support vertical margins. Put the margin on the outer div
instead.
I want change default directory dumpfile.
You could create a new directory and give it required privileges, for example:
SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.
SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.
To use the newly created directory, you could just add it as a parameter:
DIRECTORY=dmpdir
Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:
SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';
DIRECTORY_NAME DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR C:\app\Lalit/admin/orcl/dpdump/
SQL>
Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
This is how you can open EditText label assigned number on dialer directly.
I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:
sudo apt-get install debian-keyring debian-archive-keyring
Make /etc/apt/sources.list.d/debian-jessie-backports.list
:
deb http://httpredir.debian.org/debian/ jessie-backports main
Make /etc/apt/preferences.d/debian-jessie-backports
:
Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200
Then finally do the install:
sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk
in kotlin :
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))
If you are using auto-layout than best approach is to use UITableViewController with static cells in storyboard.
I have also once faced the problem with a view that require much more scrolling so change the UIScrollView with above mentioned technique.
I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint
.
Even though gsprint
is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.
I convert the web page to PDF using Puppeteer, Chrome's headless browser. But you need to pass in the session cookie to maintain credentials.
using (MemoryStream mem = new MemoryStream())
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Add a row to the cell table.
Row row;
row = new Row() { RowIndex = 1 };
sheetData.Append(row);
// In the new row, find the column location to insert a cell in A1.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
{
refCell = cell;
break;
}
}
// Add the cell to the cell table at A1.
Cell newCell = new Cell() { CellReference = "A1" };
row.InsertBefore(newCell, refCell);
// Set the cell value to be a numeric value of 100.
newCell.CellValue = new CellValue("100");
newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
}
Best way would be to declare Boolean
variable within the code block and return
it at end of code, like this:
public boolean Test(){
boolean booleanFlag= true;
if (A>B)
{booleanFlag= true;}
else
{booleanFlag = false;}
return booleanFlag;
}
I find this the best way.
According to ISO 8601:1988 that is used in Sweden the first week of the year is the first week that has at least four days within the new year.
So if your week starts on a Monday the first Thursday any year is within the first week. You can DateAdd or DateDiff from that.
I just had the same issue on visual studio 2012. For a internet application project. How to resolve “Server Error in '/' Application” error?
Searching for answer I came across this post, but none of these answer help me. Than I found another post here on stackoverflow that has the answer for resolving this issue. Specified argument was out of the range of valid values. Parameter name: site
SIMPLEST ANSWER
just spread the set inside []
let mySet = new Set()
mySet.add(1)
mySet.add(5)
mySet.add(5)
let arr = [...mySet ]
Result: [1,5]
There isn't a "first" property. Object keys are unordered.
If you loop over them with for (var foo in bar)
you will get them in some order, but it may change in future (especially if you add or remove other keys).
stringWithFileSystemRepresentation doesn't appear to be available in iOS.
class HashMap:
def __init__(self):
self.size = 64
self.map = [None] * self.size
def _get_hash(self, key):
hash = 0
for char in str(key):
hash += ord(char)
return hash % self.size
def add(self, key, value):
key_hash = self._get_hash(key)
key_value = [key, value]
if self.map[key_hash] is None:
self.map[key_hash] = list([key_value])
return True
else:
for pair in self.map[key_hash]:
if pair[0] == key:
pair[1] = value
return True
else:
self.map[key_hash].append(list([key_value]))
return True
def get(self, key):
key_hash = self._get_hash(key)
if self.map[key_hash] is not None:
for pair in self.map[key_hash]:
if pair[0] == key:
return pair[1]
return None
def delete(self, key):
key_hash = self._get_hash(key)
if self.map[key_hash] is None :
return False
for i in range(0, len(self.map[key_hash])):
if self.map[key_hash][i][0] == key:
self.map[key_hash].pop(i)
return True
def print(self):
print('---Phonebook---')
for item in self.map:
if item is not None:
print(str(item))
h = HashMap()
If you have anything in particular you want to hide (like a proprietary algorithm), put that on the server, or put it in a Flash movie and call it with JavaScript. Writing ActionScript is very similar to writing JavaScript, and you can communicate between JavaScript and ActionScript. You can do the same with Silverlight, but Silverlight doesn't have the penetration Flash does.
However, remember that any mobile phones can run your JavaScript, but not Silverlight or Flash, so you're crippling your mobile users if you go with Flash or Silverlight.
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
Use the CSS3 filter property:
img {
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-o-filter: grayscale(100%);
-ms-filter: grayscale(100%);
filter: grayscale(100%);
}
The browser support is a little bad but it's 100% CSS. A nice article about the CSS3 filter property you can find here: http://blog.nmsdvid.com/css-filter-property/
There are many ways to create a train/test and even validation samples.
Case 1: classic way train_test_split
without any options:
from sklearn.model_selection import train_test_split
train, test = train_test_split(df, test_size=0.3)
Case 2: case of a very small datasets (<500 rows): in order to get results for all your lines with this cross-validation. At the end, you will have one prediction for each line of your available training set.
from sklearn.model_selection import KFold
kf = KFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
reg = RandomForestRegressor(n_estimators=50, random_state=0)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf = reg.fit(X_train, y_train)
y_hat = clf.predict(X_test)
y_hat_all.append(y_hat)
Case 3a: Unbalanced datasets for classification purpose. Following the case 1, here is the equivalent solution:
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3)
Case 3b: Unbalanced datasets for classification purpose. Following the case 2, here is the equivalent solution:
from sklearn.model_selection import StratifiedKFold
kf = StratifiedKFold(n_splits=10, random_state=0)
y_hat_all = []
for train_index, test_index in kf.split(X, y):
reg = RandomForestRegressor(n_estimators=50, random_state=0)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
clf = reg.fit(X_train, y_train)
y_hat = clf.predict(X_test)
y_hat_all.append(y_hat)
Case 4: you need to create a train/test/validation sets on big data to tune hyperparameters (60% train, 20% test and 20% val).
from sklearn.model_selection import train_test_split
X_train, X_test_val, y_train, y_test_val = train_test_split(X, y, test_size=0.6)
X_test, X_val, y_test, y_val = train_test_split(X_test_val, y_test_val, stratify=y, test_size=0.5)
This can be accomplished using the brand new CSS display: grid
(browser support)
HTML:
<div class='container'>
<label for="dummy1">title for dummy1:</label>
<input id="dummy1" name="dummy1" value="dummy1">
<label for="dummy2">longer title for dummy2:</label>
<input id="dummy2" name="dummy2" value="dummy2">
<label for="dummy3">even longer title for dummy3:</label>
<input id="dummy3" name="dummy3" value="dummy3">
</div>
CSS:
.container {
display: grid;
grid-template-columns: 1fr 3fr;
}
When using css grid, by default elements are laid out column by column then row by row. The grid-template-columns
rule creates two grid columns, one which takes up 1/4 of the total horizontal space and the other which takes up 3/4 of the horizontal space. This creates the desired effect.
Xcode 10.2.1 was not recognizing my ipad mini. I unplugged and rebooted the mini and it became visible.
Since you're using asp.net code-behind, add an id to the element and runat=server.
You can then reference the objects in the code behind.
The other answers will work for most strings, but you can end up unescaping an already escaped double quote, which is probably not what you want.
To work correctly, you are going to need to escape all backslashes and then escape all double quotes, like this:
var test_str = '"first \\" middle \\" last "';
var result = test_str.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');
depending on how you need to use the string, and the other escaped charaters involved, this may still have some issues, but I think it will probably work in most cases.
In both languages (Java and C#) int
is 4-byte signed integer.
Unlike Java, C# Provides both signed and unsigned integer values. As Java and C# are object object-oriented, some operations in these languages do not map directly onto instructions provided by the run time and so needs to be defined as part of an object of some type.
C# provides System.Int32
which is a value type using a part of memory that belongs to the reference type on the heap.
java provides java.lang.Integer
which is a reference type operating on int
. The methods in Integer
can't be compiled directly to run time instructions.So we box an int value to convert it into an instance of Integer and use the methods which expects instance of some type (like toString()
, parseInt()
, valueOf()
etc).
In C# variable int refers to System.Int32.Any
4-byte value in memory can be interpreted as a primitive int, that can be manipulated by instance of System.Int32.So int is an alias for System.Int32.When
using integer-related methods like int.Parse()
, int.ToString()
etc. Integer is compiled into the FCL System.Int32
struct calling the respective methods like Int32.Parse()
, Int32.ToString()
.
I would suggest you to use Origami. Its a great plugin for splitting the screen. For better information on keyboard short cuts install it and after restarting Sublime text open Preferences->
Package Settings ->
Origami ->
Key Bindings - Default
For specific to your question I would suggest you to see the short cuts related to cloning of files in the above mentioned file.
The answer:
int* pArray = new int[5];
int size = *(pArray-1);
Posted above is not correct and produces invalid value. The "-1"counts elements On 64 bit Windows OS the correct buffer size resides in Ptr - 4 bytes address
Use the following to jump to previous folder:
os.chdir(os.pardir)
If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.
For windows, you can use my PowerShell script to show messages for your app only: https://github.com/AlShevelev/power_shell_logcat
From other member and my problem:
Camera Rotation issue depend on different Devices and certain Version.
Version 1.6: to fix the Rotation Issue, and it is good for most of devices
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation",90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Version 2.2: not for all devices
camera.setDisplayOrientation(90);
To build on Louis's helpful answer...
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
...
caps = DesiredCapabilities.PHANTOMJS
caps["phantomjs.page.settings.userAgent"] = "whatever you want"
driver = webdriver.PhantomJS(desired_capabilities=caps)
The only minor issue is that, unlike for Firefox and Chrome, this does not return your custom setting:
driver.execute_script("return navigator.userAgent")
So, if anyone figures out how to do that in PhantomJS, please edit my answer or add a comment below! Cheers.
Using regex:
str = 'string'
n = 1 #to remove first n characters
str[/.{#{str.size-n}}\z/] #=> "tring"
For those using a Windows OS, I was able to import a large mysqldump file into my local XAMPP installation using this command in cmd.exe
:
C:\xampp\mysql\bin>mysql -u {DB_USER} -p {DB_NAME} < path/to/file/ab.sql
Also, I just wrote a more detailed answer to another question on MySQL imports, if this is what you're after.
Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
This helped me ..
@Override
public void onBackPressed() {
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
OR????? even you can use this for drawer toggle also
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
startActivity(new Intent(currentActivity.this, LastActivity.class));
finish();
}
I hope this would help you.. :)
Correct way (if you are not trying to reset the value of the hidden_field input) is:
f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form
Where :method
is the method that when called on the object results in the value you want
So following the example above:
= simple_form_for @movie do |f|
= f.hidden :title, "some value"
= f.button :submit
The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:
= simple_form_for @movie do |f|
= f.hidden :title, :value => params[:movie][:title]
= f.button :submit
Again only use my answer is you do not want to reset the value submitted by the user.
I hope this makes sense.
You must create them under strings.xml
<string name="close">Close</string>
You must replace and reference like this
android:text="@string/close"/>
Do not use @strings even though the XML file says strings.xml or else it will not work.
Following are eight ways to find the Uptime in Windows OS.
In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.
The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.
The systeminfo
command line utility checks and displays various system statistics such as installation date, installed hotfixes and more.
Open a Command Prompt and type the following command:
systeminfo
You can also narrow down the results to just the line you need:
systeminfo | find "System Boot Time:"
Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.
Read the following KB for more info and for the download links:
To use it, follow these steps:
uptime.exe
utility. You can add a /? to the command in order
to get more options.
It does not offer many command line parameters:
C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
-V display version
C:\uptimefromcodeplex\> uptime -V
version 1.1.0
There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)
Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)
C:\uptimev100download>uptime.exe /?
UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation
Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
server Name or IP address of remote server to process.
/s Display key system events and statistics.
/a Display application failure events (assumes /s).
/d: Only calculate for events after mm/dd/yyyy.
/p: Only calculate for events in the previous n days.
/heartbeat Turn on/off the system's heartbeat
/? Basic usage.
/help Additional usage information.
Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:
net statistics workstation
The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.
Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.
Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.
Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.
Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}
GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.
wmic os get lastbootuptime
Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h
command-line parameter).
Additionally, this version of uptime.exe
will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:
and when executed as uptime -h
: