and what about LibGDX from BadLogicGames?
You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.
The only way to have as large a limit as possible is to do memory intensive tasks via the NDK, as the NDK does not impose memory limits like the SDK.
Alternatively, you could only load the part of the model that is currently in view, and load the rest as you need it, while removing the unused parts from memory. However, this may not be possible, depending on your app.
Good list. The Angry Ninjas Starter Kit will have a Cocos2d-X update soon.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
///*
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){
uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(prjection[0]);
ImagePath = cursor.getString(columnIndex);
cursor.close();
FixBitmap = BitmapFactory.decodeFile(ImagePath);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
// FixBitmap = new BitmapDrawable(ImagePath);
int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);
// ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
This code is work
In version r82 of Three.js TextureLoader is the object to use for loading a texture.
Extract (test.js):
var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
0.1, 50);
var renderer = ...
[...]
/**
* Will be called when load completes.
* The argument will be the loaded texture.
*/
var onLoad = function (texture) {
var objGeometry = new THREE.BoxGeometry(20, 20, 20);
var objMaterial = new THREE.MeshPhongMaterial({
map: texture,
shading: THREE.FlatShading
});
var mesh = new THREE.Mesh(objGeometry, objMaterial);
scene.add(mesh);
var render = function () {
requestAnimationFrame(render);
mesh.rotation.x += 0.010;
mesh.rotation.y += 0.010;
renderer.render(scene, camera);
};
render();
}
// Function called when download progresses
var onProgress = function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};
// Function called when download errors
var onError = function (xhr) {
console.log('An error happened');
};
var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);
In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.
Extract (Globe.js):
Create a new container using Object3D
for having two meshes in the same container:
var Globe = function (radius, segments) {
THREE.Object3D.call(this);
this.name = "Globe";
var that = this;
// instantiate a loader
var loader = new THREE.TextureLoader();
A map called textures
where every object contains the url
of a texture file and val
for storing the value of a Three.js texture object.
// earth textures
var textures = {
'map': {
url: 'relief.jpg',
val: undefined
},
'bumpMap': {
url: 'elev_bump_4k.jpg',
val: undefined
},
'specularMap': {
url: 'wateretopo.png',
val: undefined
}
};
The array of promises, for each object in the map called textures
push a new Promise in the array texturePromises
, every Promise will call loader.load
. If the value of entry.val
is a valid THREE.Texture
object, then resolve the promise.
var texturePromises = [], path = './';
for (var key in textures) {
texturePromises.push(new Promise((resolve, reject) => {
var entry = textures[key]
var url = path + entry.url
loader.load(url,
texture => {
entry.val = texture;
if (entry.val instanceof THREE.Texture) resolve(entry);
},
xhr => {
console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
'% loaded');
},
xhr => {
reject(new Error(xhr +
'An error occurred loading while loading: ' +
entry.url));
}
);
}));
}
Promise.all
takes the promise array texturePromises
as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.
// load the geometry and the textures
Promise.all(texturePromises).then(loadedTextures => {
var geometry = new THREE.SphereGeometry(radius, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: textures.map.val,
bumpMap: textures.bumpMap.val,
bumpScale: 0.005,
specularMap: textures.specularMap.val,
specular: new THREE.Color('grey')
});
var earth = that.earth = new THREE.Mesh(geometry, material);
that.add(earth);
});
For the cloud sphere only one texture is necessary:
// clouds
loader.load('n_amer_clouds.png', map => {
var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
var material = new THREE.MeshPhongMaterial({
map: map,
transparent: true
});
var clouds = that.clouds = new THREE.Mesh(geometry, material);
that.add(clouds);
});
}
Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
Use the hasClass
method:
jQueryCollection.hasClass(className);
or
$(selector).hasClass(className);
The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).
Note: If you pass a className
argument that contains whitespace, it will be matched literally against the collection's elements' className
string. So if, for instance, you have an element,
<span class="foo bar" />
then this will return true
:
$('span').hasClass('foo bar')
and these will return false
:
$('span').hasClass('bar foo')
$('span').hasClass('foo bar')
Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd
for the search term.
(source: winaero.com)
It dipends on which distribution you are in general but... You have to install the php-curl module and then enable it on php.ini like you did in windows. Once you are done remember to restart apache demon!
As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.
The solution:
From github issue:
This bug only occurs if pkg-config is not installed;
a simple
sudo apt-get install pkg-config
will shore up the include paths for now.
After this installation proceeds smoothly.
Here is part of a line in my code that brought the warning up in NetBeans:
$page = (!empty($_GET['p']))
After much research and seeing how there are about a bazillion ways to filter this array, I found one that was simple. And my code works and NetBeans is happy:
$p = filter_input(INPUT_GET, 'p');
$page = (!empty($p))
This is a good way to do it:
<?php
if (!(isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' ||
$_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
If you need weighted edges and multigraphs, you might want to add another class Edge.
I would also recommend using generics to allow specifying which sub-class of Vertex and Edge are currently used. For example:
public class Graph<V extends Vertex> {
List<V> vertices;
...
}
When it comes to implementing graph algorithms, you could also define interfaces for your graph classes on which the algorithms can operate, so that you can play around with different implementations of the actual graph representation. For example, simple graphs that are well-connected might be better implemented by an adjacency matrix, sparser graphs might be represented by adjacency lists - it all depends...
BTW Building such structures efficiently can be quite challenging, so maybe you could give us some more details on what kind of job you would want to use them for? For more complex tasks I would suggest you have a look at the various Java graph libraries, to get some inspiration.
rt.jar
contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.
For MacOS it is called classes.jar
and located under /System/Library/Frameworks/<java_version>/Classes
. Same not messing with it rule applies there as well :).
http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html
I had the same problem where there's no files under Generated Java files, BuildConfig and R.java were missing. The automatic build option is not generating.
In Eclipse under Project, uncheck Build Automatically. Then under Project select Build Project. You may need to fix the projec
The only way would be to convert your text field into an nvarchar field.
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
Otherwise, I suggest doing the concatenation in your application.
I would use the following. It should work just fine, and doesn't seem ugly, at least to me:
singleString <- paste(readLines("foo.txt"), collapse=" ")
In Go and the mgo driver:
Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)
where result is the struct instance of the sought after type
Passing by reference in the above case is just an alias
for the actual object.
You'll be referring to the actual object just with a different name.
There are many advantages which references
offer compared to pointer references
.
This should about cut it (i'll leave the error handling to you):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime
. You can only convert it to a LocalDate
, because the string only represent the year,month and date components it would be the correct thing to do.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06
Anyway you can convert this to LocalDateTime
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
Simply :first
works for me, why isn't this mentioned yet?
I prefer to turn the tibble to data.frame. It shows everything and you're done
df %>% data.frame
If you would like to dynamically access USB devices which can be plugged in while the docker container is already running, for example access a just attached usb webcam at /dev/video0, you can add a cgroup rule when starting the container. This option does not need a --privileged container and only allows access to specific types of hardware.
Check the device major number of the type of device you would like to add. You can look it up in the linux kernel documentation. Or you can check it for your device. For example to check the device major number for a webcam connected to /dev/video0, you can do a ls -la /dev/video0
. This results in something like:
crw-rw----+ 1 root video 81, 0 Jul 6 10:22 /dev/video0
Where the first number (81) is the device major number. Some common device major numbers:
Add rules when you start the docker container:
--device-cgroup-rule='c major_number:* rmw'
rule for every type of device you want access to-v /run/udev:/run/udev:ro
-v /dev:/dev
So to add all usb webcams and serial2usb devices to your docker container, do:
docker run -it -v /dev:/dev --device-cgroup-rule='c 188:* rmw' --device-cgroup-rule='c 81:* rmw' ubuntu bash
It is just a convention as we can see here:
The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. By default, the first non-option argument is the name of the class to be invoked. A fully-qualified class name should be used. If the -jar option is specified, the first non-option argument is the name of a JAR archive containing class and resource files for the application, with the startup class indicated by the Main-Class manifest header.
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html#description
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter
with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
You need to use <> operator:
while (<>) {
print $_; # or simply "print;"
}
Which can be compacted to:
print while (<>);
Arbitrary file:
open F, "<file.txt" or die $!;
while (<F>) {
print $_;
}
close F;
I'm just taking the popular answer a bit further and making it more robust. This lets you specify any start point, so 0 or 1 for example. It also uses python's range feature where the end is one less so it can be used directly with list lengths for example.
@register.filter(name='range')
def filter_range(start, end):
return range(start, end)
Then in your template just include the above template tag file and use the following:
{% for c in 1|range:6 %}
{{ c }}
{% endfor %}
Now you can do 1-6 instead of just 0-6 or hard coding it. Adding a step would require a template tag, this should cover more uses cases so it's a step forward.
This is a fairly simple response changes the background of the site with a list of items
function randomToN(maxVal) {
var randVal = Math.random() * maxVal;
return typeof 0 == 'undefined' ? Math.round(randVal) : randVal.toFixed(0);
};
var list = [ "IMG0.EXT", "IMG2.EXT","IMG3.EXT" ], // Images
ram = list[parseFloat(randomToN(list.length))], // Random 1 to n
img = ram == undefined || ram == null ? list[0] : ram; // Detect null
$("div#ID").css("backgroundImage", "url(" + img + ")"); // push de background
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
The disabled
attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.
The given answers work if you're in a context where conda is in your PATH environment variable, e.g. if you set it up that way during installation, or if you're running the "Anaconda Prompt".
If that's not the case, e.g. if you're trying to locate conda for use in a script, you should be able to pick up its installation location by probing HKCU\Software\Python
for available Python installations. For example:
>for /F "tokens=2,*" %a in ('reg query HKCU\Software\Python /f InstallPath /s /k /ve ^| findstr Default') do @echo %b
C:\Users\<username>\Miniconda3
C:\Users\<username>\Miniconda3
Javascript always passes by value. However, if you pass an object to a function, the "value" is really a reference to that object, so the function can modify that object's properties but not cause the variable outside the function to point to some other object.
An example:
function changeParam(x, y, z) {
x = 3;
y = "new string";
z["key2"] = "new";
z["key3"] = "newer";
z = {"new" : "object"};
}
var a = 1,
b = "something",
c = {"key1" : "whatever", "key2" : "original value"};
changeParam(a, b, c);
// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...
I think you've actually got a wider confusion here.
The initial error is that you're trying to call split
on the whole list of lines, and you can't split
a list of strings, only a string. So, you need to split
each line, not the whole thing.
And then you're doing for points in Type
, and expecting each such points
to give you a new x
and y
. But that isn't going to happen. Types
is just two values, x
and y
, so first points
will be x
, and then points will be y
, and then you'll be done. So, again, you need to loop over each line and get the x
and y
values from each line, not loop over a single Types
from a single line.
So, everything has to go inside a loop over every line in the file, and do the split
into x
and y
once for each line. Like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getQuakeData()
As a side note, you really should close
the file, ideally with a with
statement, but I'll get to that at the end.
Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getQuakeData()
Or, a better way to write that might be:
def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getQuakeData()
Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.
sudo chown -R yourname:www-data cake
then
sudo chmod -R g+s cake
First command changes owner and group.
Second command adds s attribute which will keep new files and directories within cake having the same group permissions.
I have provided two solutions. Pick up which one best suits for you.
Solution#1:
<html>_x000D_
<style>_x000D_
#container {_x000D_
width: 50%;_x000D_
margin: auto;_x000D_
text-align: center;_x000D_
}_x000D_
#first {_x000D_
width:48%;_x000D_
float: left;_x000D_
height: 200px;_x000D_
background-color: blue;_x000D_
}_x000D_
#second {_x000D_
width: 48%;_x000D_
float: left;_x000D_
height: 200px;_x000D_
background-color: green;_x000D_
}_x000D_
#clear {_x000D_
clear: both;_x000D_
}_x000D_
#space{_x000D_
width: 4%;_x000D_
float: left;_x000D_
height: 200px;_x000D_
}_x000D_
table{_x000D_
border: 1px solid black;_x000D_
margin: 0 auto;_x000D_
table-layout:fixed;_x000D_
width:100%;_x000D_
text-align:center;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
_x000D_
<div id = "container" >_x000D_
<div id="first">_x000D_
<table>_x000D_
<tr>_x000D_
<th>Column1</th>_x000D_
<th>Column2</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Value1</td>_x000D_
<td>Value2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div id = "space" >_x000D_
</div>_x000D_
<div id = "second" >_x000D_
<table>_x000D_
<tr>_x000D_
<th>Column1</th>_x000D_
<th>Column2</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Value1</td>_x000D_
<td>Value2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div id = "clear" ></div>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Solution#2:
<html>_x000D_
<style>_x000D_
#container {_x000D_
margin:0 auto;_x000D_
text-align: center;_x000D_
}_x000D_
#first {_x000D_
float: left;_x000D_
}_x000D_
#second {_x000D_
float: left;_x000D_
}_x000D_
#clear {_x000D_
clear: both;_x000D_
}_x000D_
#space{_x000D_
width:20px;_x000D_
height:20px;_x000D_
float: left;_x000D_
}_x000D_
.table, .table th, .table td{_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
_x000D_
<table id = "container" >_x000D_
<td>_x000D_
<div id="first">_x000D_
<table class="table">_x000D_
<tr>_x000D_
<th>Column1</th>_x000D_
<th>Column2</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Value1</td>_x000D_
<td>Value2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div id = "space" >_x000D_
</div>_x000D_
<div id = "second" >_x000D_
<table class="table">_x000D_
<tr>_x000D_
<th>Column1</th>_x000D_
<th>Column2</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Value1</td>_x000D_
<td>Value2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
<div id = "clear" ></div>_x000D_
</div>_x000D_
</td>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Note: Change the width percentage as per your need in 1st solution.
Two problems here:
seven_date
is a number, not a date. 29 + 7 = 36
getMonth
returns a zero based index of the month. So adding one just gets you the current month number. Just found base64-arraybuffer, a small npm package with incredibly high usage, 5M downloads last month (2017-08).
https://www.npmjs.com/package/base64-arraybuffer
For anyone looking for something of a best standard solution, this may be it.
You can use node package, if you often need to restore databases in development process.
Install:
npm install -g sql-bak-restore
Usage:
sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>
Arguments:
!! sqlcmd command line utility should be in your PATH variable.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
GO is not a SQL keyword.
It's a batch separator used by client tools (like SSMS) to break the entire script up into batches
Answered before several times... example 1
On Mac, Linux and Windows i.e. on all 3 of the major platforms, Gradle stores dependencies at:
~/.gradle/caches/modules-2/files-2.1
//create TreeMap instance
TreeMap treeMap = new TreeMap();
//add key value pairs to TreeMap
treeMap.put("1","One");
treeMap.put("2","Two");
treeMap.put("3","Three");
/*
get Collection of values contained in TreeMap using
Collection values()
*/
Collection c = treeMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through TreeMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
or:
for (Map.Entry<K,V> entry : treeMap.entrySet()) {
V value = entry.getValue();
K key = entry.getKey();
}
or:
// Use iterator to display the keys and associated values
System.out.println("Map Values Before: ");
Set keys = map.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
Integer key = (Integer) i.next();
String value = (String) map.get(key);
System.out.println(key + " = " + value);
}
Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx
Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\
In the folder path F:\Temp\
, create an Excel 2007 spreadsheet file named States_1.xlsx
with two worksheets.
Sheet 1
of States_1.xlsx contained the following data
Sheet 2
of States_1.xlsx contained the following data
In the folder path F:\Temp\
, create another Excel 2007 spreadsheet file named States_2.xlsx
with two worksheets.
Sheet 1
of States_2.xlsx contained the following data
Sheet 2
of States_2.xlsx contained the following data
Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.
CREATE TABLE [dbo].[Destination](
[Id] [int] IDENTITY(1,1) NOT NULL,
[State] [nvarchar](255) NULL,
[Country] [nvarchar](255) NULL,
[FilePath] [nvarchar](255) NULL,
[SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO
The table is currently empty.
Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx
. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx
of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$
to avoid design time error.
In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.
Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider
under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx
Click on the All
section on the left side and set the property Extended Properties to Excel 12.0
to denote the version of Excel. Here in this case 12.0 denotes Excel 2007
. Click on the Test Connection to make sure that the connection succeeds.
Create an Excel connection manager named Excel as shown below.
Create an OLE DB Connection SQL Server named SQLServer
. So, we should have three connections on the package as shown below.
We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.
On the connection ExcelSchema, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
Similarly on the connection Excel, configure the expression ServerName
to use the variable FilePath
. Click on the ellipsis button to configure the expression.
On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container
named Loop files will loop through the files. The second Foreach Loop container
will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL
Configure the first Foreach loop container named Loop files as shown below:
Configure the first Foreach loop container named Loop sheets as shown below:
Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:
Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.
Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.
Configure the OLE DB destination to insert the data into the SQL table.
Below screenshot shows successful execution of the package.
Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.
Hope that helps.
Basically if you follow the issues in this link for 0.2 you'll likely get yourself fixed, I had the same problems with 0.2
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Here's what the JDK API says about AbstractMethodError:
Thrown when an application tries to call an abstract method. Normally, this error is caught by the compiler; this error can only occur at run time if the definition of some class has incompatibly changed since the currently executing method was last compiled.
Bug in the oracle driver, maybe?
Use the below css
input[type="submit"] {_x000D_
font-size: 20px;_x000D_
background: pink;_x000D_
border: none;_x000D_
padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
margin: 25px 0 10px;_x000D_
font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
That also happened to me on a recreated directory, the directory is the same but to make it work again just run:
cd .
I faced the same problem and was frustrated to see as to all options i tried and none of them work,
Turns out once you have configured everything correctly including settings.xml
just clear your local repository folder and try mvn commands. That greatly helped me
Hope this helps others
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
There should be a script named mvim in the root of the .bz2 file. Copy this somewhere into your $PATH ( /usr/local/bin would be good ) and you should be sorted.
In iOS 8 you need to do two extra things to get location working: Add a key to your Info.plist and request authorization from the location manager asking it to start
info.plist:
<key>NSLocationUsageDescription</key>
<string>I need location</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>I need location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>I need location</string>
Add this to your code
if (IS_OS_8_OR_LATER)
{
[locationmanager requestWhenInUseAuthorization];
[locationmanager requestAlwaysAuthorization];
}
I found this will have git ignore temporary files created by vim:
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~
It can also be viewed here.
Update for Java 8 or plus. In Java 8, PermGen (Permanent Generation) space is removed and replaced by Meta Space. The String pool memory is moved to the heap of JVM.
Compared with Java 7, the String pool size is increased in the heap. Therefore, you have more space for internalized Strings, but you have less memory for the whole application.
One more thing, you have already known that when comparing 2 (referrences of) objects in Java, '==
' is used for comparing the reference of object, 'equals
' is used for comparing the contents of object.
Let's check this code:
String value1 = "70";
String value2 = "70";
String value3 = new Integer(70).toString();
Result:
value1 == value2
---> true
value1 == value3
---> false
value1.equals(value3)
---> true
value1 == value3.intern()
---> true
That's why you should use 'equals
' to compare 2 String objects. And that's is how intern()
is useful.
You can use while(in.available() != 0)
instead of while(true)
.
You use the sql%rowcount
variable.
You need to call it straight after the statement which you need to find the affected row count for.
For example:
set serveroutput ON;
DECLARE
i NUMBER;
BEGIN
UPDATE employees
SET status = 'fired'
WHERE name LIKE '%Bloggs';
i := SQL%rowcount;
--note that assignment has to precede COMMIT
COMMIT;
dbms_output.Put_line(i);
END;
fflush()
only flushes the buffering added by the stdio fopen()
layer, as managed by the FILE *
object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE *
layer, using fileno()
and a raw write()
, are also not buffered in a way that fflush()
would flush.
As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl()
, then open()
the file yourself directly, without using fopen<()
and friends from stdio.
EDIT
As pointed out by @Kwame , the below code does validate the url even if the
.com
or.co
etc are not present.also pointed out by @Blaise, URLs like https://www.google is a valid URL and you need to do a DNS check for checking if it resolves or not, separately.
This is simple and works:
So min_attr
contains the basic set of strings that needs to be present to define the validity of a URL,
i.e http://
part and google.com
part.
urlparse.scheme
stores http://
and
urlparse.netloc
store the domain name google.com
from urlparse import urlparse
def url_check(url):
min_attr = ('scheme' , 'netloc')
try:
result = urlparse(url)
if all([result.scheme, result.netloc]):
return True
else:
return False
except:
return False
all()
returns true if all the variables inside it return true.
So if result.scheme
and result.netloc
is present i.e. has some value then the URL is valid and hence returns True
.
Shouldn't that be:
<xsl:value-of select="/root/Image/img/@src"/>
? It looks like you are trying to copy the entire Image/img node to the attribute @src
An incomplete type
error is when the compiler encounters the use of an identifier that it knows is a type, for instance because it has seen a forward-declaration of it (e.g. class stringstream;
), but it hasn't seen a full definition for it (class stringstream { ... };
).
This could happen for a type that you haven't used in your own code but is only present through included header files -- when you've included header files that use the type, but not the header file where the type is defined. It's unusual for a header to not itself include all the headers it needs, but not impossible.
For things from the standard library, such as the stringstream
class, use the language standard or other reference documentation for the class or the individual functions (e.g. Unix man
pages, MSDN library, etc.) to figure out what you need to #include
to use it and what namespace to find it in if any. You may need to search for pages where the class name appears (e.g. man -k stringstream
).
Android Studio 3
The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:
repositories {
google()
jcenter()
}
So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.
dependencies {
// ...
implementation 'com.squareup.picasso:picasso:2.5.2'
}
binary tree :
No need to consider values, we need to look at the structrue.
Given by (2 power n) - n
Eg: for three nodes it is (2 power 3) -3 = 8-3 = 5 different structrues
binary search tree:
We need to consider even the node values. We call it as Catalan Number
Given by 2n C n / n+1
Two options save vijay.sql
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as
declare
begin
execute immediate
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
sel.tactical_select_executive_flag,
sel.agent_name,
res.DMS_RESIGN_CAMPAIGN_CODE,
pclub.tactical_select_flag
FROM spineowner.pop_wkly_refresh_20100201 wk,
dms_bb_coverage_102009 bbc,
dms_select_executive_group sel,
DMS_RESIGN_CAMPAIGN_26052009 res,
DMS_PRIORITY_CLUB pclub
WHERE wk.mpn = bbc.mpn(+)
AND wk.mpn = sel.mpn (+)
AND wk.mpn = res.mpn (+)
AND wk.mpn = pclub.mpn (+)'
end;
/
and then run as sqlplus -s username/password @vijay.sql '20100101'
Add display: block;
or display: inline-block;
to your #User_Apps_Content .DLD_App a
Yes, the error you are getting means that there is not a private key on your Mac associated with the distribution certificate you are trying to use to sign the app.
There are two possible solutions, depending on whether the computer who requested the distribution certificate is available or not.
If the computer who requested the distribution certificate is available (or there is a backup of the distribution assets somewhere)
If the computer where the distribution profile was created is not accessible anymore (and there is not a backup)
You have to revoke the certificate and create a new one.
You may need to ask your team admin or agent to give you some privileges in order to generate distribution certificates. Once you have enough privileges, follow these steps (accurate as of 15-May-2013):
Reopen Xcode and check your project configuration to see if you can now select an "iPhone Distribution" certificate (i.e. it's not grayed out).
If you're not concerned about the exact formatting however you do want something simple but without the line breaks of print_r
you can also use json_encode($value)
for a quick and simple formatted output. (note it works well on other data types too)
$str = json_encode($arr);
//output...
[{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]
I tried using the solution By @davy-c but had an Exception "System.FormatException: 'Input string was not in a correct format.'", this was due to there still being text past the line number, I modified the code he posted and came up with:
int line = Convert.ToInt32(objErr.ToString().Substring(objErr.ToString().IndexOf("line")).Substring(0, objErr.ToString().Substring(objErr.ToString().IndexOf("line")).ToString().IndexOf("\r\n")).Replace("line ", ""));
This works for me in VS2017 C#.
If anyone is interested, here are some one-liners (and a note on loss of type information in CSV):
require 'csv'
rows = [[1,2,3],[4,5]] # [[1, 2, 3], [4, 5]]
# To CSV string
csv = rows.map(&:to_csv).join # "1,2,3\n4,5\n"
# ... and back, as String[][]
rows2 = csv.split("\n").map(&:parse_csv) # [["1", "2", "3"], ["4", "5"]]
# File I/O:
filename = '/tmp/vsc.csv'
# Save to file -- answer to your question
IO.write(filename, rows.map(&:to_csv).join)
# Read from file
# rows3 = IO.read(filename).split("\n").map(&:parse_csv)
rows3 = CSV.read(filename)
rows3 == rows2 # true
rows3 == rows # false
Note: CSV loses all type information, you can use JSON to preserve basic type information, or go to verbose (but more easily human-editable) YAML to preserve all type information -- for example, if you need date type, which would become strings in CSV & JSON.
A struct (without a typedef) often needs to (or should) be with the keyword struct when used.
struct A; // forward declaration
void function( struct A *a ); // using the 'incomplete' type only as pointer
If you typedef your struct you can leave out the struct keyword.
typedef struct A A; // forward declaration *and* typedef
void function( A *a );
Note that it is legal to reuse the struct name
Try changing the forward declaration to this in your code:
typedef struct context context;
It might be more readable to do add a suffix to indicate struct name and type name:
typedef struct context_s context_t;
HTML 4 does not make it explicit. The current HTML5 working draft specifies that the first submit button must be the default:
A
form
element's default button is the first submit button in tree order whose form owner is thatform
element.If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
I am using docker-compose to build the Kafka container using wurstmeister/kafka
image. Adding KAFKA_ADVERTISED_PORT: 9092
property to my docker-compose
file solved this error for me.
The reason must be somewhere else. Using only Spring Boot 1.2.2 out of the box with no configuration, it Just Works. Have a look at this repo - can you get it to break?
https://github.com/konrad-garus/so-yaml
Are you sure the YAML file looks exactly the way you pasted? No extra whitespace, characters, special characters, mis-indentation or something of that sort? Is it possible you have another file elsewhere in the search path that is used instead of the one you're expecting?
If you do not have privilege for "Show Status" then, The best option is to, create two triggers and a new table which keeps the row count of your billion records table.
Example:
TableA >> Billion Records
TableB >> 1 Column and 1 Row
Whenever there is insert query on TableA(InsertTrigger), Increment the row value by 1 TableB
Whenever there is delete query on TableA(DeleteTrigger), Decrement the row value by 1 in TableB
I think you are creating a project in the wrong way,I am going to post here in step by step
Step 1: File>>New>>Project>>Web>>Dynamic Web Project
Step 2: Enter Project Name>>Next>>Next>>
Step 3: Check the checkbox for Generate web.xml deployment descriptor
Step 4: Finish
Please follow this way you will get you web.xml file under WEB-INF folder
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"]
would be looking in the AppSettings
for something named ConnectionString
, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized
, because it is looking for an initialized property of AppSettings
named ConnectionString
.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString
instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
Please see my answer here:
https://stackoverflow.com/a/24844618/2293304
It's a long and ugly, but reliable and efficient solution.
It resolves a few problems which are not addressed by the other answerers:
shutil.rmtree()
on a symbolic link (which will pass the os.path.isdir()
test if it links to a directory).Tell it where to look for you class: it's in ".", which is the current directory:
java -classpath . HelloWorld
No need to set JAVA_HOME
or CLASSPATH
in this case
The problem is that Visual Studio is getting 'confused' over the dotnet core versions on the machine. When I went to control panel -> uninstall programs I had 8 different dotnet core SDK's and Runtimes installed. This was somehow causing VS to silently have an error when trying to find tests.
You can validate the issue by going to the command line and getting the version of dotnet your on $ dotnet --version
. If you see anything except the latest version you have installed then your machine has some mismatch and is not using the correct version. Example...If you have dotnet core 1.0.1
installed but when you get the version at command prompt and it says 1.0.0
thats a problem.
Delete all the old stuff. I started with only what I though I needed to remove (the oldest dotnet rc versions) but it still gave the wrong version when testing the issue. Eventually I conceded to do a full clean. I...
After my machine was completely empty of all VS and donet I installed only VS2017 (it comes packaged with latest dotnet). I created a xUnit test project and the test explorer found the test immediately SOLVED
This may seem like overkill but I spent two weeks trying to fix this in other ways. If your having the issue just do it, even though it may take you hours to uninstall/reinstall items it will probably save you time.
The cleaner way in my opinion is to first export to .py as aforementioned:
pyuic4 foo.ui > foo.py
And then use it inside your code (e.g main.py
), like:
from foo import Ui_MyWindow
class MyWindow(QtGui.QDialog):
def __init__(self):
super(MyWindow, self).__init__()
self.ui = Ui_MyWindow()
self.ui.setupUi(self)
# go on setting up your handlers like:
# self.ui.okButton.clicked.connect(function_name)
# etc...
def main():
app = QtGui.QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
This way gives the ability to other people who don't use qt-designer to read the code, and also keeps your functionality code outside foo.py
that could be overwritten by designer. You just reference ui
through MyWindow
class as seen above.
Answer without the need for a exterior array or additional function
function permutator (arr) {
var permutations = [];
if (arr.length === 1) {
return [ arr ];
}
for (var i = 0; i < arr.length; i++) {
var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1)));
for (var j = 0; j < subPerms.length; j++) {
subPerms[j].unshift(arr[i]);
permutations.push(subPerms[j]);
}
}
return permutations;
}
I was working with a embedded device which had neither perl, awk or python and did it with sed instead. It supports multiple spaces before the first word (which the cut
and bash
solutions did not handle).
VARIABLE=" first_word_with_spaces_before_and_after another_word "
echo $VARIABLE | sed 's/ *\([^ ]*\).*/\1/'
This was very useful when grepping ps
for process IDs since the other solutions here using only bash was not able to remove the first spaces which ps
uses to align.
Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:
For satisfying multiple (all) conditions:
select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] # 1 < x <5
For satisfying multiple (or) conditions:
select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5
If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.
Run these:
$ cd /usr/local/mysql/bin
$ ./mysqladmin -u root password 'password'
Then run
./mysql -u root
It should log in. Now run FLUSH privileges;
Then exit the MySQL console and try logging in. If that doesn't work run these:
$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET authentication_string=PASSWORD("XXXXXXX") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit
Change xxxxxx to ur new password. Then try logging in again.
Update. See this http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html
It should solve your problem.
If you are on oracle try this
ALTER USER username IDENTIFIED BY password
Find below some characteristics of clustered and non-clustered indexes:
create Index index_name(col1, col2, col.....)
.Suppose we have a collection like below:
{
"_id":"1234"
"open":"Yes"
"things":{
"paper":1234
"bottle":"Available"
"bottle_count":40
}
}
We want to know if the bottle field is present or not?
Ans:
db.products.find({"things.bottle":{"$exists":true}})
If INSERTS
are rare, I would avoid doing a NOT EXISTS (...)
since it emits a SELECT
on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql
CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$
DECLARE
BEGIN
UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2;
IF NOT FOUND THEN
INSERT INTO tableName values (value, arg1, arg2);
END IF;
END;
$$ LANGUAGE 'plpgsql';
This way Postgres will initially try to do a UPDATE
. If no rows was affected, it will fall back to emitting an INSERT
.
Use t
function:
t(colnames(df))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] "var1" "var2" "var3" "var4" "var5" "var6"
Similar question as: pandas: How do I split text in a column into multiple rows?
You could do:
>> a=pd.DataFrame({"var1":"a,b,c d,e,f".split(),"var2":[1,2]})
>> s = a.var1.str.split(",").apply(pd.Series, 1).stack()
>> s.index = s.index.droplevel(-1)
>> del a['var1']
>> a.join(s)
var2 var1
0 1 a
0 1 b
0 1 c
1 2 d
1 2 e
1 2 f
Because $xml->xpath
always return an array, and strlen
expects a string.
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
One of the good things about handle.exe
is that you can run it as a subprocess and parse the output.
We do this in our deployment script - works like a charm.
great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..
if (model is ViewDataDictionary)
{
controller.ViewData = model as ViewDataDictionary;
} else {
controller.ViewData.Model = model;
}
You can use a 1 pixel per 1 pixel Java applet embedded in the page and use that for compression.
It's not JavaScript and the clients will need a Java runtime but it will do what you need.
You have two possibilities (for an IPv4 address) :
varchar(15)
, if your want to store the IP address as a string
192.128.0.15
for instanceinteger
(4 bytes), if you convert the IP address to an integer
3229614095
for the IP I used before
The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
About those manipulations, see the ip2long()
and long2ip()
functions, on the PHP-side, or inet_aton()
and inet_ntoa()
on the MySQL-side.
If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.
Use parameter expansion, if the value is already stored in a variable.
$ str="GenFiltEff=7.092200e-01"
$ value=${str#*=}
Or use read
$ IFS="=" read name value <<< "GenFiltEff=7.092200e-01"
Either way,
$ echo $value
7.092200e-01
For Kotlin, You can use something like this :
object FileUtils {
fun Context.getFileName(uri: Uri): String?
= when (uri.scheme) {
ContentResolver.SCHEME_FILE -> File(uri.path).name
ContentResolver.SCHEME_CONTENT -> getCursorContent(uri)
else -> null
}
private fun Context.getCursorContent(uri: Uri): String?
= try {
contentResolver.query(uri, null, null, null, null)?.let { cursor ->
cursor.run {
if (moveToFirst()) getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
else null
}.also { cursor.close() }
}
} catch (e : Exception) { null }
This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.
import datetime
__author__ = 'Daniel Margarido'
# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]
# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
if month in THIRTY_DAYS_MONTHS: # April, June, September, November
return 30
elif month in THIRTYONE_DAYS_MONTHS: # January, March, May, July, August, October, December
return 31
else: # February
if is_leap_year(year):
return 29
else:
return 28
# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
current_month_days = get_month_days(date.month, date.year)
next_month_days = get_month_days(date.month + 1, date.year)
delta = datetime.timedelta(days=current_month_days)
if date.day > next_month_days:
delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)
return date + delta
def add_year(date):
if is_leap_year(date.year):
delta = datetime.timedelta(days=366)
else:
delta = datetime.timedelta(days=365)
return date + delta
# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
if expected_value == value:
print "Test Passed"
return True
print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
return False
# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))
# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))
# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
Here is the code for it, enjoy!, I picked that up from the dotNetReference type the "using" statement inside the namespace line 106 http://referencesource.microsoft.com/#mscorlib/microsoft/win32/win32native.cs
using System;
using System.Collections.Generic;
namespace UsingStatement
{
using Typedeffed = System.Int32;
using TypeDeffed2 = List<string>;
class Program
{
static void Main(string[] args)
{
Typedeffed numericVal = 5;
Console.WriteLine(numericVal++);
TypeDeffed2 things = new TypeDeffed2 { "whatever"};
}
}
}
I haven't played with these settings myself so this is just speculation but if we think about this issue as normal cores and threads in a distributed system then in your cluster you can use up to 12 cores (4 * 3 machines) and 24 threads (8 * 3 machines). In your first two examples you are giving your job a fair number of cores (potential computation space) but the number of threads (jobs) to run on those cores is so limited that you aren't able to use much of the processing power allocated and thus the job is slower even though there is more computation resources allocated.
you mention that your concern was in the shuffle step - while it is nice to limit the overhead in the shuffle step it is generally much more important to utilize the parallelization of the cluster. Think about the extreme case - a single threaded program with zero shuffle.
Since Java 7 you can use java.util.Objects.equals(Object a, Object b):
These utilities include null-safe or null-tolerant methods
Long id1 = null;
Long id2 = 0l;
Objects.equals(id1, id2));
When you install git-scm found in "https://git-scm.com/downloads" uncheck the "Only show new options" located at the very bottom of the installation window
Make sure you check
Click Next and you're good to go!
range(x)
returns a list of numbers from 0 to x - 1.
>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]
for i in range(x):
executes the body (which is print i
in your first example) once for each element in the list returned by range()
.
i
is used inside the body to refer to the “current” item of the list.
In that case, i
refers to an integer, but it could be of any type, depending on the objet on which you loop.
Adding line height helps too.
text-align: center;
line-height: 18px; /* for example. */
Ahhh, the stupid linesize ... Here is what I do in my profile.sql - works only on unixes:
echo SET LINES $(tput cols) > $HOME/.login_tmp.sql
@$HOME/.login_tmp.sql
if you find an equivalent for tput on Windows, it might work there as well
Hint for adding an element at the beginning of an array:
$a = array('first', 'second');
$a[-1] = 'i am the new first element';
then:
foreach($a as $aelem)
echo $a . ' ';
//returns first, second, i am...
but:
for ($i = -1; $i < count($a)-1; $i++)
echo $a . ' ';
//returns i am as 1st element
Based on what you provided, it is pretty simple for what you need to do and you even have a number of ways to go about doing it. You'll need something that'll let you post a body with your request. Almost any programming language can do this as well as command line tools like cURL.
One you have your tool decided, you'll need to create your JSON body and submit it to the server.
An example using cURL would be (all in one line, minus the \
at the end of the first line):
curl -v -H "Content-Type: application/json" -X POST \
-d '{"name":"your name","phonenumber":"111-111"}' http://www.abc.com/details
The above command will create a request that should look like the following:
POST /details HTTP/1.1
Host: www.abc.com
Content-Type: application/json
Content-Length: 44
{"name":"your name","phonenumber":"111-111"}
I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well. Even though the question/answer is about downloading the code of an earlier commit, I thought I'd just add an answer for browsing the code also.
When you're browsing your code the URL is something like:
https://bitbucket.org/user/repo/src/
and by adding a commit hash at the end like this:
https://bitbucket.org/user/repo/src/a0328cb
You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.
The string you have here contains a floating point number with a unit. I'd recommend splitting that string into a number and unit part with QString::split()
.
Then use toDouble()
to get a floating point number and round as you want.
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
Given returned json from your://site.com:
[{text:"Text1", val:"Value1"},
{text:"Text2", val:"Value2"},
{text:"Text3", val:"Value3"}]
Use this:
$.getJSON("your://site.com", function(json){
$('#select').empty();
$('#select').append($('<option>').text("Select"));
$.each(json, function(i, obj){
$('#select').append($('<option>').text(obj.text).attr('value', obj.val));
});
});
Instead of style changes, just put these two lines of code to your activity.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowleft);
Executing PHP functions by the onclick event is a cumbersome task and near impossible.
Instead you can redirect to another PHP page.
Say you are currently on a page one.php and you want to fetch some data from this php script process the data and show it in another page i.e. two.php you can do it by writing the following code
<button onclick="window.location.href='two.php'">Click me</button>
For an specific cluster use: getMarkers() Gets the array of markers in the clusterer.
For all the markers in the map use: getTotalMarkers() Gets the array of markers in the clusterer.
The difference is not Java-specific, but platform specific.
Historically UNIX-like OSes have used \n
as newline character, some other deprecated OSes have used \r
and Windows OSes have employed \r\n
.
"%.2f"
does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:
['0.30', '0.50', '0.20']
Also, don't call your variable list
. This is a reserved word for list creation. Use some other name, for example my_list
.
If you want to obtain [0.30, 0.5, 0.20]
(or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:
[0.29999999999999999, 0.5, 0.20000000000000001]
If you've been working on a branch on-and-off, or lots has happened in other branches while you've been working on something, it's best to rebase your branch onto master. This keeps the history tidy and makes things a lot easier to follow.
git checkout master
git pull
git checkout local_branch_name
git rebase master
git push --force # force required if you've already pushed
Notes:
There's a chapter on rebasing at http://git-scm.com/book/ch3-6.html, and loads of other resources out there on the web.
public static final String YOUR_STRING_CONSTANT = "";
For different types of arguments, there is 3-dots :
public void foo(Object... x) {
String myVar1 = x.length > 0 ? (String)x[0] : "Hello";
int myVar2 = x.length > 1 ? Integer.parseInt((String) x[1]) : 888;
}
Then call it
foo("Hii");
foo("Hii", 146);
for security, use like this:
if (!(x[0] instanceof String)) { throw new IllegalArgumentException("..."); }
The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Please, see more variations .
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
I had the similar issue showing the error
For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.
Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.
2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.
The first argument should be the path to the executable program. So
gdb progname 12271
Applications using JDBC 10.1 has got a bug (Doc ID 370438.1) and can throw the same ORA-01461 exception while working with UTF8 character set database even though inserted characters are less than the maximum size of the column.
Recommended Solution: - Use 10gR2 JDBC drivers or higher in such case.
HTH
Take a look at the Boost documentation as well, regarding how you are using the macro:
In reference to BOOST_VERSION
, from http://www.boost.org/doc/libs/1_37_0/libs/config/doc/html/boost_config/boost_macro_reference.html#boost_config.boost_macro_reference.boost_helper_macros:
Describes the boost version number in XXYYZZ format such that:
(BOOST_VERSION % 100)
is the sub-minor version,((BOOST_VERSION / 100) %
1000)
is the minor version, and(BOOST_VERSION / 100000)
is the major version.
Example I have a class Test:
Then. Go to config to run class Test:
Step 1: Add Application
Step 2:
You can input arguments in the Program Arguments textbox.
You can use
substr(string $string, int $start, int[optional] $length=null);
See substr in the PHP documentation. It returns part of a string.
An alternative if you sometimes do not have spaces do not want to use the CASE statement
select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))
This works in SQL Server, and according to my searching MySQL has the same functions
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
Based on https://github.com/antonyt/InfiniteViewPager I wrote up this which works nicely:
class InfiniteViewPager @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
// Allow for 100 back cycles from the beginning.
// This should be enough to create an illusion of infinity.
// Warning: scrolling to very high values (1,000,000+) results in strange drawing behaviour.
private val offsetAmount get() = if (adapter?.count == 0) 0 else (adapter as InfinitePagerAdapter).realCount * 100
override fun setAdapter(adapter: PagerAdapter?) {
super.setAdapter(if (adapter == null) null else InfinitePagerAdapter(adapter))
currentItem = 0
}
override fun setCurrentItem(item: Int) = setCurrentItem(item, false)
override fun setCurrentItem(item: Int, smoothScroll: Boolean) {
val adapterCount = adapter?.count
if (adapterCount == null || adapterCount == 0) {
super.setCurrentItem(item, smoothScroll)
} else {
super.setCurrentItem(offsetAmount + item % adapterCount, smoothScroll)
}
}
override fun getCurrentItem(): Int {
val adapterCount = adapter?.count
return if (adapterCount == null || adapterCount == 0) {
super.getCurrentItem()
} else {
val position = super.getCurrentItem()
position % (adapter as InfinitePagerAdapter).realCount
}
}
fun animateForward() {
super.setCurrentItem(super.getCurrentItem() + 1, true)
}
fun animateBackwards() {
super.setCurrentItem(super.getCurrentItem() - 1, true)
}
internal class InfinitePagerAdapter(private val adapter: PagerAdapter) : PagerAdapter() {
internal val realCount: Int get() = adapter.count
override fun getCount() = if (realCount == 0) 0 else Integer.MAX_VALUE
override fun instantiateItem(container: ViewGroup, position: Int) = adapter.instantiateItem(container, position % realCount)
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) = adapter.destroyItem(container, position % realCount, `object`)
override fun finishUpdate(container: ViewGroup) = adapter.finishUpdate(container)
override fun isViewFromObject(view: View, `object`: Any) = adapter.isViewFromObject(view, `object`)
override fun restoreState(bundle: Parcelable?, classLoader: ClassLoader?) = adapter.restoreState(bundle, classLoader)
override fun saveState(): Parcelable? = adapter.saveState()
override fun startUpdate(container: ViewGroup) = adapter.startUpdate(container)
override fun getPageTitle(position: Int) = adapter.getPageTitle(position % realCount)
override fun getPageWidth(position: Int) = adapter.getPageWidth(position)
override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) = adapter.setPrimaryItem(container, position, `object`)
override fun unregisterDataSetObserver(observer: DataSetObserver) = adapter.unregisterDataSetObserver(observer)
override fun registerDataSetObserver(observer: DataSetObserver) = adapter.registerDataSetObserver(observer)
override fun notifyDataSetChanged() = adapter.notifyDataSetChanged()
override fun getItemPosition(`object`: Any) = adapter.getItemPosition(`object`)
}
}
For consuming it simply change your ViewPager to InfiniteViewPager and that's all you need to change.
Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data
. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):
POST
to /users
to create the user entity.POST
the image to /images
, making sure to return a Location
header to where the image can be retrieved per the HTTP spec.PATCH
to /users/carPhoto
and assign it the ID of the photo given in the Location
header of step 2.I had some troubles with provisioning when trying to login as root, even with PermitRootLogin yes
. I made it so only the vagrant ssh
command is affected:
# Login as root when doing vagrant ssh
if ARGV[0]=='ssh'
config.ssh.username = 'root'
end
A single line method within bash works like this.
[some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver
will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working.
find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver
Of course
cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver
or even simpler
ls > $(date "+%Y.%m.%d-%H.%M.%S").ver
Don't use firefox profile and try below code:
driver.get("http://UserName:[email protected]");
If you're implementing it in IE browser, there are certain things which you need to do.
In case your authentication server requires username with domain like "domainuser" you need to add double slash /
to the url:
//localdomain\user:[email protected]
You can use unicode for this in CSS. If you are using font awesome 5, this is the syntax;
.login::before {
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f007";
}
You can see their documentation here.
You could store this into a temporary table.
So instead of doing the CTE/sub query you would use a temp table.
Good article on these here http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:
let currentYear = new Date().getFullYear;
The currentYear variable will hold the value you are looking out for.
__init__
is basically a function which will "initialize"/"activate" the properties of the class for a specific object, once created and matched to the corresponding class..self
represents that object which will inherit those properties.An idempotent operation over a set leaves its members unchanged when applied one or more times.
It can be a unary operation like absolute(x) where x belongs to a set of positive integers. Here absolute(absolute(x)) = x.
It can be a binary operation like union of a set with itself would always return the same set.
cheers
pass $connect
as your first parameter in mysqli_real_escape_string
for this first make connection then do rest.read here http://php.net/manual/en/mysqli.real-escape-string.php
To get the maximum value of a column across a set of rows:
SELECT MAX(column1) FROM table; -- expect one result
To get the maximum value of a set of columns, literals, or variables for each row:
SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results
You could use pandas.
Here is an example with a list:
In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out:
0 3.45
1 2.12
2 6.23
3 6.34
4 9.34
dtype: float64
If you have a dict d, and you want its keys as rows:
In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}
In: P.DataFrame(index=d.keys(), data=d.values())
Out:
0
1 0.45
2 2.35
3 3.42
4 4.13
And another way of giving dict to a DataFrame:
P.DataFrame.from_dict(d, orient='index')
IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4
Have Fun!
The ss.str()
temporary is destroyed after initialization of cstr2
is complete. So when you print it with cout
, the c-string that was associated with that std::string
temporary has long been destoryed, and thus you will be lucky if it crashes and asserts, and not lucky if it prints garbage or does appear to work.
const char* cstr2 = ss.str().c_str();
The C-string where cstr1
points to, however, is associated with a string that still exists at the time you do the cout
- so it correctly prints the result.
In the following code, the first cstr
is correct (i assume it is cstr1
in the real code?). The second prints the c-string associated with the temporary string object ss.str()
. The object is destroyed at the end of evaluating the full-expression in which it appears. The full-expression is the entire cout << ...
expression - so while the c-string is output, the associated string object still exists. For cstr2
- it is pure badness that it succeeds. It most possibly internally chooses the same storage location for the new temporary which it already chose for the temporary used to initialize cstr2
. It could aswell crash.
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
The return of c_str()
will usually just point to the internal string buffer - but that's not a requirement. The string could make up a buffer if its internal implementation is not contiguous for example (that's well possible - but in the next C++ Standard, strings need to be contiguously stored).
In GCC, strings use reference counting and copy-on-write. Thus, you will find that the following holds true (it does, at least on my GCC version)
string a = "hello";
string b(a);
assert(a.c_str() == b.c_str());
The two strings share the same buffer here. At the time you change one of them, the buffer will be copied and each will hold its separate copy. Other string implementations do things different, though.
You can always cancel()
the Notification
from whatever is being invoked by the action (e.g., in onCreate()
of the activity tied to the PendingIntent
you supply to addAction()
).
In Spring MVC you get the HtppServletResponce object by default .
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception{
//Do service call passing the response
return new ModelAndView("CustomerAddView");
}
//Service code
Cookie myCookie =
new Cookie("name", "val");
response.addCookie(myCookie);
You can use python within the bash script too. I didn't have much success with some of the top answers here, and found this to work without the need for loops:
#!/bin/bash
python
filetosearch = '/home/ubuntu/ip_table.txt'
texttoreplace = 'tcp443'
texttoinsert = 'udp1194'
s = open(filetosearch).read()
s = s.replace(texttoreplace, texttoinsert)
f = open(filetosearch, 'w')
f.write(s)
f.close()
quit()
Use http://www.proxomitron.info and set up the header you want, etc.
"Pop Catalin" got it right. Controlling the definition based on the type of build provides a great deal of flexibility. For example, you can have a "DEBUG", "DEMO", and "RELEASE" configuration all in the same solution. That prevents the need for duplicate programming with two different solutions.
So yes #if RELEASE
or #if (RELEASE)
works the same as #if DEBUG
when the RELEASE Conditional compilation symbol is defined.
The following is taken from "Pop Catalin" post: If you want to define a RELEASE constant for the release configuration go to: * Project Properties -> Build * Select Release Mode * in the Conditional compilation symbols textbox enter: RELEASE
For many purposes simply calling sorted will suffice. For example
>>> s = set([0, 1, 2, 99, 4, 40, 3, 20, 24, 100, 60])
>>> sorted(s)
[0, 1, 2, 3, 4, 20, 24, 40, 60, 99, 100]
If you are going to use this repeatedly, there will be overhead incurred by calling the sorted function so you might want to save the resulting list, as long as you're done changing the set. If you need to maintain unique elements and sorted, I agree with the suggestion of using OrderedDict from collections with an arbitrary value such as None.
$search_string = 4;
$original_array = [1,2,1,3,2,4,4,4,4,4,10];
$step1 = implode(",", $original_array); // convert original_array to string
$step2 = explode($search_string, $step1); // break step1 string into a new array using the search string as delimiter
$result = count($step2)-1; // count the number of elements in the resulting array, minus the first empty element
print_r($result); // result is 5
Using the first for
-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.
The latter syntax is added in Java 5 and enumerates an array by using an Iterator
instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.
It's convenient when you just want to perform some actions on all objects in an array.
Remove all spaces in string
// Remove only spaces
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/ /g,'');
"
Textwithspaces1111
andsome
breaklines
"
// Remove spaces and breaklines
`
Text with spaces 1 1 1 1
and some
breaklines
`.replace(/\s/g,'');
"Textwithspaces1111andsomebreaklines"
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
The modulo operator tells you the remainder of a division of two numbers.
Getting python to read a single character from the terminal in an unbuffered manner is a little bit tricky, but here's a recipe that'll do it:
You forgot to close the Class
bracket.
class AddAddressComponent extends React.Component {_x000D_
render() {_x000D_
let {provinceList,cityList} = this.props_x000D_
if(cityList === undefined || provinceList === undefined){_x000D_
console.log('undefined props')_x000D_
} else {_x000D_
console.log('defined props')_x000D_
}_x000D_
_x000D_
return (_x000D_
<div>rendered</div>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
AddAddressComponent.contextTypes = {_x000D_
router: React.PropTypes.object.isRequired_x000D_
};_x000D_
_x000D_
AddAddressComponent.defaultProps = {_x000D_
cityList: [],_x000D_
provinceList: [],_x000D_
};_x000D_
_x000D_
AddAddressComponent.propTypes = {_x000D_
userInfo: React.PropTypes.object,_x000D_
cityList: React.PropTypes.array.isRequired,_x000D_
provinceList: React.PropTypes.array.isRequired,_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<AddAddressComponent />,_x000D_
document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app" />
_x000D_
The solution below incorporates all of the suggestions here. It starts with what was originally posted by Dunni. It uses a binary search like gjpc's, but it is a bit more readable. It also include's gregm's bug fixes and a bug-fix of my own.
import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialise();
}
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialise();
}
private void initialise() {
mTestPaint = new Paint();
mTestPaint.set(this.getPaint());
//max size defaults to the initially specified text size unless it is too small
}
/* Re size the font so the specified text fits in the text box
* assuming the text box is the specified width.
*/
private void refitText(String text, int textWidth)
{
if (textWidth <= 0)
return;
int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
float hi = 100;
float lo = 2;
final float threshold = 0.5f; // How close we have to be
mTestPaint.set(this.getPaint());
while((hi - lo) > threshold) {
float size = (hi+lo)/2;
mTestPaint.setTextSize(size);
if(mTestPaint.measureText(text) >= targetWidth)
hi = size; // too big
else
lo = size; // too small
}
// Use lo so that we undershoot rather than overshoot
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int height = getMeasuredHeight();
refitText(this.getText().toString(), parentWidth);
this.setMeasuredDimension(parentWidth, height);
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}
//Attributes
private Paint mTestPaint;
}
Try it, learn it:
DECLARE @r INT = 5
DECLARE @i INT = 0
DECLARE @F varchar(max) = ''
WHILE @i < @r
BEGIN
DECLARE @j INT = 0
DECLARE @o varchar(max) = ''
WHILE @j < @r - @i - 1
BEGIN
SET @o = @o + ' '
SET @j += 1
END
DECLARE @k INT = 0
WHILE @k < @i + 1
BEGIN
SET @o = @o + ' *' -- '*'
SET @k += 1
END
SET @i += 1
SET @F = @F + @o + CHAR(13)
END
PRINT @F
With date:
DECLARE @d DATE = '2019-11-01'
WHILE @d < GETDATE()
BEGIN
PRINT @d
SET @d = DATEADD(DAY,1,@d)
END
PRINT 'n'
PRINT @d
Java ships in 2 versions: JRE & SDK (used to be called JDK)
The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)
When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.
This error can be caused by an unclosed set of brackets.
int main {
doSomething {}
doSomething else {
}
Not so easy to spot, even in this 4 line example.
This error, in a 150 line main function, caused the bewildering error: "static declaration of ‘savePair’ follows non-static declaration". There was nothing wrong with my definition of function savePair, it was that unclosed bracket.
try this. http://jsfiddle.net/fVpkm/
Html:-
<div class="row-fluid summary">
<div class="span11">
<h2>MyHeading</h2>
</div>
<div class="span1">
<button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
</div>
</div>
<div class="row-fluid summary">
<div id="intro" class="collapse">
Here comes the text...
</div>
</div>
JS:-
$('button').click(function(){ //you can give id or class name here for $('button')
$(this).text(function(i,old){
return old=='+' ? '-' : '+';
});
});
Update With pure Css, pseudo elements
button.btn.collapsed:before
{
content:'+' ;
display:block;
width:15px;
}
button.btn:before
{
content:'-' ;
display:block;
width:15px;
}
Update 2 With pure Javascript
function handleClick()
{
this.value = (this.value == '+' ? '-' : '+');
}
document.getElementById('collapsible').onclick=handleClick;
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
We could use tidyr::extract()
x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#> A B C D
#> <chr> <chr> <chr> <chr>
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Another option is to use unglue::unglue_data()
# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#> A B C D
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Created on 2019-09-14 by the reprex package (v0.3.0)
declare @sttime datetime
set @sttime=getdate()
print @sttime
Select * from ProductMaster
SELECT RTRIM(CAST(DATEDIFF(MS, @sttime, GETDATE()) AS CHAR(10))) AS 'TimeTaken'
Here the solution from http://forums.asp.net/t/928411.aspx/1 as mentioned by mamoo - just in case the website goes offline. Worked well for me.
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");
sbScript.Append(this.GetPostBackEventReference(this, "PBArg") + ";\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");
this.RegisterStartupScript("AutoPostBackScript", sbScript.ToString());
Simple try to remove name attribute from input element.
So it has to look like
<input type="checkbox" checked="" id="class_box_2" value="2">
You can add an event listener with 'ended' as the first param
Like this :
Convert a string to an integer with the parseInt
method of the Java Integer class. The parseInt
method is to convert the String to an int and throws a NumberFormatException
if the string cannot be converted to an int type.
Overlooking the exception it can throw, use this:
int i = Integer.parseInt(myString);
If the String signified by the variable myString
is a valid integer like “1234”, “200”, “1”,
and it will be converted to a Java int. If it fails for any reason, the change can throw a NumberFormatException
, so the code should be a little longer to account for this.
For example, Java String
to int
conversion method, control for a possible NumberFormatException
public class JavaStringToIntExample
{
public static void main (String[] args)
{
// String s = "test"; // Use this if you want to test the exception below
String s = "1234";
try
{
// The String to int conversion happens here
int i = Integer.parseInt(s.trim());
// Print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
If the change attempt fails – in this case, if you can try to convert the Java String test to an int — the Integer parseInt
process will throw a NumberFormatException
, which you must handle in a try/catch block.
Swift 3 & 4, iOS 10 & 11, Xcode 9 & 10
For me, this method doesn't work:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
when I used to each view controller, but this worked:
In file info.list, add row: View controller-based status bar appearance
and set to NO
Next in appdelegate:
UIApplication.shared.statusBarStyle = .lightContent
You mean the ASCII ordinal value? Try type casting like this one:
int x = 'a';
I have found the browser referer implementation to be really inconsistent.
For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.
<a href="http://foo.com/foo" download="bar">click to download</a>
Is broken in Chrome - no referer sent.
You can try to do json.loads()
, which will throw a ValueError
if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
It should be noted that not only will the caret (^) behave differently within the brackets, it will have the opposite result of placing it outside of the brackets. Placing the caret where you have it will search for all strings NOT beginning with the content you placed within the brackets. You also would want to place a period before the asterisk in between your brackets as with grep, it also acts as a "wildcard".
grep ^[.rwx].*[0-9]$
This should work for you, I noticed that some posters used a character class in their expressions which is an effective method as well, but you were not using any in your original expression so I am trying to get one as close to yours as possible explaining every minor change along the way so that it is better understood. How can we learn otherwise?
If you're required to show growth as a percentage it's customary to display [NaN]
or something similar in these cases. A growth rate, on the other hand, would be reported in this case as $/month. So in your example for April
the growth rate would be calculated as ((20-0)/1
.
In any event, determining the correct method for reporting this special case is a user decision. Is it covered in your user requirements?
I took sth's answer and modified it slightly to fit my needs of a nested dictionaries and lists:
def pretty(d, indent=0):
if isinstance(d, dict):
for key, value in d.iteritems():
print '\t' * indent + str(key)
if isinstance(value, dict) or isinstance(value, list):
pretty(value, indent+1)
else:
print '\t' * (indent+1) + str(value)
elif isinstance(d, list):
for item in d:
if isinstance(item, dict) or isinstance(item, list):
pretty(item, indent+1)
else:
print '\t' * (indent+1) + str(item)
else:
pass
Which then gives me output like:
>>>
xs:schema
@xmlns:xs
http://www.w3.org/2001/XMLSchema
xs:redefine
@schemaLocation
base.xsd
xs:complexType
@name
Extension
xs:complexContent
xs:restriction
@base
Extension
xs:sequence
xs:element
@name
Policy
@minOccurs
1
xs:complexType
xs:sequence
xs:element
...
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
The Python tutorial has an appendix called Floating Point Arithmetic: Issues and Limitations. Read it. It explains what is happening and why Python is doing its best. It has even an example that matches yours. Let me quote a bit:
>>> 0.1 0.10000000000000001
you may be tempted to use the
round()
function to chop it back to the single digit you expect. But that makes no difference:>>> round(0.1, 1) 0.10000000000000001
The problem is that the binary floating-point value stored for
“0.1”
was already the best possible binary approximation to1/10
, so trying to round it again can’t make it better: it was already as good as it gets.Another consequence is that since
0.1
is not exactly1/10
, summing ten values of0.1
may not yield exactly1.0
, either:>>> sum = 0.0 >>> for i in range(10): ... sum += 0.1 ... >>> sum 0.99999999999999989
One alternative and solution to your problems would be using the decimal
module.
Initialize instance:
private String imagePath;
private List<String> imagePathList;
In onActivityResult You have to write this, If-else 2 block. One for single image and another for multiple image.
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && data != null){
imagePathList = new ArrayList<>();
if(data.getClipData() != null){
int count = data.getClipData().getItemCount();
for (int i=0; i<count; i++){
Uri imageUri = data.getClipData().getItemAt(i).getUri();
getImageFilePath(imageUri);
}
}
else if(data.getData() != null){
Uri imgUri = data.getData();
getImageFilePath(imgUri);
}
}
Most important part, Get Image Path from uri:
public void getImageFilePath(Uri uri) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String image_id = filePath[filePath.length - 1];
Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
imagePathList.add(imagePath);
cursor.close();
}
}
Hope this can help you.
just set the width of the td/column you want to be fixed and the rest will expand.
<td width="200"></td>
It worked for me, but the exe4j can leave a signature when you double click the .exe application
In ngModule
you need to import FormsModule
, because ngModel
is coming from FormsModule
.
Please modify your app.module.ts like the below code I have shared
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
There is one rule that is set by font-awesome.css
, which you need to override.
You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline;
by default and which I've corrected here:
<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:
I've downsized the font-size of the icon above in this instance to 30px
, as it feels too big at 40px
for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:
<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
<span>Continue</span>
<i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>
Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:
Going further on Pekka's answer, I had a style "style1" on some of my textboxes. You can create a "style1[disabled]" so you style only the disabled textboxes using "style1" style:
.style1[disabled] { ... }
Worked ok on IE8.
You are looking for System.Environment.NewLine
.
On Windows, this is equivalent to \r\n
though it could be different under another .NET implementation, such as Mono on Linux, for example.
To see all keys of Jsonobject use this
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject obj = new JSONObject(JSON);
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
System.out.pritnln(key);
}
Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers.
There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile times since all code has to be processed every time it is included by the compiler.
Finally, it is often annoying to have circular object relationships (sometimes desired) when all the code is the headers.
Bottom line, you were right, he is wrong.
EDIT: I have been thinking about your question. There is one case where what he says is true. templates. Many newer "modern" libraries such as boost make heavy use of templates and often are "header only." However, this should only be done when dealing with templates as it is the only way to do it when dealing with them.
EDIT: Some people would like a little more clarification, here's some thoughts on the downsides to writing "header only" code:
If you search around, you will see quite a lot of people trying to find a way to reduce compile times when dealing with boost. For example: How to reduce compilation times with Boost Asio, which is seeing a 14s compile of a single 1K file with boost included. 14s may not seem to be "exploding", but it is certainly a lot longer than typical and can add up quite quickly. When dealing with a large project. Header only libraries do affect compile times in a quite measurable way. We just tolerate it because boost is so useful.
Additionally, there are many things which cannot be done in headers only (even boost has libraries you need to link to for certain parts such as threads, filesystem, etc). A Primary example is that you cannot have simple global objects in header only libs (unless you resort to the abomination that is a singleton) as you will run into multiple definition errors. NOTE: C++17's inline variables will make this particular example doable in the future.
As a final point, when using boost as an example of header only code, a huge detail often gets missed.
Boost is library, not user level code. so it doesn't change that often. In user code, if you put everything in headers, every little change will cause you to have to recompile the entire project. That's a monumental waste of time (and is not the case for libraries that don't change from compile to compile). When you split things between header/source and better yet, use forward declarations to reduce includes, you can save hours of recompiling when added up across a day.
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
I was just banging my head against a wall just trying to get S3 uploads to work with large files. Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied
Then I tried copying a smaller file and got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I could list objects fine but I couldn't do anything else even though I had s3:*
permissions in my Role policy. I ended up reworking the policy to this:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucketMultipartUploads",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::my-bucket",
"arn:aws:s3:::my-bucket/*"
]
},
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "*"
}
]
}
Now I'm able to upload any file. Replace my-bucket
with your bucket name. I hope this helps somebody else that's going thru this.
You aren't building your formula right.
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = "=SUM(H5:H" & var1a & ")"
This does the same as the following lines do:
Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"
which is what you are trying to do.
Also, you want to have the =
at the beginning of the formala.
An index is just a data structure that makes the searching faster for a specific column in a database. This structure is usually a b-tree or a hash table but it can be any other logic structure.
As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:
foreach (KeyValuePair<int, int> kvp in rankings)
{
.....
if((double)(similarModules/modules.Count)>0.6)
{
rankings[kvp.Key] = rankings[kvp.Key] + 4; // <--- This line is the problem
}
.....
What may not be obvious from the code above is where the Enumerator
comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach
loop gets expanded to by the compiler. The generated code will look something like:
{
IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
// is where the Enumerator
// comes from.
try
{
int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
while(e.MoveNext())
{
// loop code goes here
}
}
finally
{
if (e != null) ((IDisposable)e).Dispose();
}
}
If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator()
returns) you will see:
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.
A great resource is iosfonts.com, which says that the name for that font is HelveticaNeue-UltraLight
. So you'd use this code:
label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30)
If the system can't find the font, it defaults to a 'normal' font - I think it's something like 11-point Helvetica. This can be quite confusing, always check your font names.
This meta tag is used by all responsive web pages, that is those that are designed to layout well across device types - phone, tablet, and desktop. The attributes do what they say. However, as MDN's Using the viewport meta tag to control layout on mobile browsers indicates,
On high dpi screens, pages with
initial-scale=1
will effectively be zoomed by browsers.
I've found that the following ensures that the page displays with zero zoom by default.
<meta name="viewport" content="width=device-width, initial-scale=0.86, maximum-scale=3.0, minimum-scale=0.86">
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!