On a Mac, you need to use this command:
STATIC_DEPS=true sudo pip install lxml
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
To sum up, the quick linkedlist method:
List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
You can't modify a collection while you're iterating over it with foreach. You might try using a regular for() statement.
You may need to iterate backwards from the end of the collection to make sure you cover every item in the collection and don't accidentally overrun the end of the collection after removing an item (since the length would change). I can't remember if .NET accounts for that possibility or not.
What parts of Boost do you need? A lot of stuff is part of TR1 which is shipped with Visual Studio, so you could simply say, for example:
#include <tr1/memory>
using std::tr1::shared_ptr;
According to James, this should also work (in C++0x):
#include <memory>
using std::shared_ptr;
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
I'm going to give you 2 way's to call an action from the client side
first
If you just want to navigate to an action you should call just use the follow
window.location = "/Home/Index/" + youid
Notes: that you action need to handle a get type called
Second
If you need to render a View you could make the called by ajax
//this if you want get the html by get
public ActionResult Foo()
{
return View(); //this return the render html
}
And the client called like this "Assuming that you're using jquery"
$.get('your controller path', parameters to the controler , function callback)
or
$.ajax({
type: "GET",
url: "your controller path",
data: parameters to the controler
dataType: "html",
success: your function
});
or
$('your selector').load('your controller path')
Update
In your ajax called make this change to pass the data to the action
function onDropDownChange(e) {
var url = '/Home/Index'
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
//put your code here
}
});
}
UPDATE 2
You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div
in your view and do something like this
in the view where you are that have the combo in some place
<div id="theNewView"> </div> <---you're going to load the other view here
in the javascript client
$.ajax({
type: "GET",
url: url,
data: { id = e.value}, <--sending the values to the server
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
With this i think that you solve your problem
\dt information_schema.
from within psql, should be fine.
I update my Hibernate JPA to 2.1 and It works.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
This algorithm is the most effective one, it avoids of array passing and manipulation in recursive calls, works in Python 2, 3:
def permute(items):
length = len(items)
def inner(ix=[]):
do_yield = len(ix) == length - 1
for i in range(0, length):
if i in ix: #avoid duplicates
continue
if do_yield:
yield tuple([items[y] for y in ix + [i]])
else:
for p in inner(ix + [i]):
yield p
return inner()
Usage:
for p in permute((1,2,3)):
print(p)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
No need to use grep. ps
in Android can filter by COMM
value (last 15 characters of the package name in case of java app)
Let's say we want to check if com.android.phone
is running:
adb shell ps m.android.phone
USER PID PPID VSIZE RSS WCHAN PC NAME
radio 1389 277 515960 33964 ffffffff 4024c270 S com.android.phone
Filtering by COMM
value option has been removed from ps
in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof
command:
adb shell pidof com.android.phone
It returns the PID if such process was found or an empty string otherwise.
Most easy way..
//div[@class="Test"]
Assuming you want to find <div class="Test">
as described.
Its not recommended to overwrite bootstrap file, just in your local style.css use
body{background: your color !important;
here !important declaration overwrite bootstrap value.
in case you have a variable :
$your_var = 'declare your var';
echo 'i want to show my var here'.$your_var.'<br>';
I would use du
's --threshold
for this. Not sure if this option is available in all versions of du
but it is implemented in GNU's version.
Quoting from du(1)'s manual:
-t, --threshold=SIZE
exclude entries smaller than SIZE if positive, or entries greater
than SIZE if negative
Here's my solution, using du --threshold=
for OP's use case:
THRESHOLD=90k
if [[ -z "$(du --threshold=${THRESHOLD} file.txt)" ]]; then
mail -s "file.txt size is below ${THRESHOLD}, please fix. " [email protected] < /dev/null
mv -f /root/tmp/file.txt /var/www/file.txt
fi
The advantage of that, is that du
can accept an argument to that option in a known format - either human as in 10K
, 10MiB
or what ever you feel comfortable with - you don't need to manually convert between formats / units since du
handles that.
For reference, here's the explanation on this SIZE
argument from the man page:
The SIZE argument is an integer and optional unit (example: 10K is
10*1024). Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers
of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on.
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for(double a : data)
sum += a;
return sum/size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for(double a :data)
temp += (a-mean)*(a-mean);
return temp/(size-1);
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if (data.length % 2 == 0)
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
return data[data.length / 2];
}
}
Here is how to kill one or more process from a .bat file.
Step 1. Open a preferred text editor and create a new file.
step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:
taskkill /im examplename.exe
To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:
taskkill /f /im somecorporateprocess.exe
To kill more than one process you rinse and repeat the first part of step 2. Example:
taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe
or
taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe
step 3. Save your file to desired location with the .bat extension.
step 4. click newly created bat file to run it.
From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.
find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'
It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.
cp flags are:
Object objectToGet = ...
Map<Object, Object> map = new HashMap<Object, Object>(set.size());
for (Object o : set) {
map.put(o, o);
}
Object objectFromSet = map.get(objectToGet);
If you only do one get this will not be very performing because you will loop over all your elements but when performing multiple retrieves on a big set you will notice the difference.
The answer from @prgDevelop returns 0 on my Android Marsmallow. Must return 7200000. These changes make it work fine:
int offset = TimeZone.getTimeZone(Time.getCurrentTimezone()).getRawOffset() + TimeZone.getTimeZone(Time.getCurrentTimezone()).getDSTSavings();
This works for me I'm using Windows 10
git config --global credential.helper wincred
Import Linking the module from React Native
import { TouchableOpacity, Linking } from "react-native";
Try it:-
<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
<Text> Facebook </Text>
</TouchableOpacity>
I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:
/* Grid Definition */
table {
word-break: break-word;
}
For IE11 in edge mode, you need to set this to word-break:break-all
In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:
var ListView = React.createClass({
render: function() {
var items = this.props.data.map(function(item) {
return this.props.delegate({data:item});
}.bind(this));
return <ul>{items}</ul>;
}
});
var ItemDelegate = React.createClass({
render: function() {
return <li>{this.props.data}</li>
}
});
var Wrapper = React.createClass({
render: function() {
return <ListView delegate={ItemDelegate} data={someListOfData} />
}
});
Edit: added information about ngMessages (>= 1.3.X) below.
Since this is one of the top results if you Google "Angular Form Validation", currently, I want to add another answer to this for anyone coming in from there.
There's a method in FormController.$setValidity but that doesn't look like a public API so I rather not use it.
It's "public", no worries. Use it. That's what it's for. If it weren't meant to be used, the Angular devs would have privatized it in a closure.
To do custom validation, if you don't want to use Angular-UI as the other answer suggested, you can simply roll your own validation directive.
app.directive('blacklist', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
var blacklist = attr.blacklist.split(',');
//For DOM -> model validation
ngModel.$parsers.unshift(function(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function(value) {
ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
return value;
});
}
};
});
And here's some example usage:
<form name="myForm" ng-submit="doSomething()">
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
<span ng-show="myForm.fruitName.$error.blacklist">
The phrase "{{data.fruitName}}" is blacklisted</span>
<span ng-show="myForm.fruitName.$error.required">required</span>
<button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>
Note: in 1.2.X it's probably preferrable to substitute ng-if
for ng-show
above
Here is an obligatory plunker link
Also, I've written a few blog entries about just this subject that goes into a little more detail:
You can now use the ngMessages module instead of ngShow to show your error messages. It will actually work with anything, it doesn't have to be an error message, but here's the basics:
<script src="angular-messages.js"></script>
Reference ngMessages
in your module declaration:
var app = angular.module('myApp', ['ngMessages']);
Add the appropriate markup:
<form name="personForm">
<input type="email" name="email" ng-model="person.email" required/>
<div ng-messages="personForm.email.$error">
<div ng-message="required">required</div>
<div ng-message="email">invalid email</div>
</div>
</form>
In the above markup, ng-message="personForm.email.$error"
basically specifies a context for the ng-message
child directives. Then ng-message="required"
and ng-message="email"
specify properties on that context to watch. Most importantly, they also specify an order to check them in. The first one it finds in the list that is "truthy" wins, and it will show that message and none of the others.
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/
Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.
You can cast your iterable to a list then use .size() on it.
Lists.newArrayList(iterable).size();
For the sake of clarity, the above method will require the following import:
import com.google.common.collect.Lists;
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
Your second question
How many columns can be used together as a primary key in a given table?
is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)
If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.
As noted in previous responses, using "$MyInvocation" is subject to scoping issues and doesn't necessarily provide consistent data (return value vs. direct access value). I've found that the "cleanest" (most consistent) method for getting script info like script path, name, parms, command line, etc. regardless of scope (in main or subsequent/nested function calls) is to use "Get-Variable" on "MyInvocation"...
# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value
# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path
# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath
# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name
# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName
So, you can get the same info as $PSCommandPath, but a whole lot more in the deal. Not sure, but it looks like "Get-Variable" was not available until PS3 so not a lot of help for really old (not updated) systems.
There are also some interesting aspects when using "-Scope" as you can backtrack to get the names, etc. of the calling function(s). 0=current, 1=parent, etc.
Hope this is somewhat helpful.
Ref, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable
This is a combination of @paul-blair 's answer converted to Java which includes some cleanups pointed out by paul blair and some mistakes that seem to have been inside @pushy 's code which is made up of @Edward Campbell and anonymous.
I cannot emphasize how much this code should ONLY be used in testing and is extremely hacky. But for cases where you need the environment setup in tests it is exactly what I needed.
This also includes some minor touches of mine that allow the code to work on both Windows running on
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)
as well as Centos running on
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
The implementation:
/**
* Sets an environment variable FOR THE CURRENT RUN OF THE JVM
* Does not actually modify the system's environment variables,
* but rather only the copy of the variables that java has taken,
* and hence should only be used for testing purposes!
* @param key The Name of the variable to set
* @param value The value of the variable to set
*/
@SuppressWarnings("unchecked")
public static <K,V> void setenv(final String key, final String value) {
try {
/// we obtain the actual environment
final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
final boolean environmentAccessibility = theEnvironmentField.isAccessible();
theEnvironmentField.setAccessible(true);
final Map<K,V> env = (Map<K, V>) theEnvironmentField.get(null);
if (SystemUtils.IS_OS_WINDOWS) {
// This is all that is needed on windows running java jdk 1.8.0_92
if (value == null) {
env.remove(key);
} else {
env.put((K) key, (V) value);
}
} else {
// This is triggered to work on openjdk 1.8.0_91
// The ProcessEnvironment$Variable is the key of the map
final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
convertToVariable.setAccessible(true);
// The ProcessEnvironment$Value is the value fo the map
final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
final Method convertToValue = valueClass.getMethod("valueOf", String.class);
final boolean conversionValueAccessibility = convertToValue.isAccessible();
convertToValue.setAccessible(true);
if (value == null) {
env.remove(convertToVariable.invoke(null, key));
} else {
// we place the new value inside the map after conversion so as to
// avoid class cast exceptions when rerunning this code
env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));
// reset accessibility to what they were
convertToValue.setAccessible(conversionValueAccessibility);
convertToVariable.setAccessible(conversionVariableAccessibility);
}
}
// reset environment accessibility
theEnvironmentField.setAccessible(environmentAccessibility);
// we apply the same to the case insensitive environment
final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
theCaseInsensitiveEnvironmentField.setAccessible(true);
// Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
if (value == null) {
// remove if null
cienv.remove(key);
} else {
cienv.put(key, value);
}
theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">", e);
} catch (final NoSuchFieldException e) {
// we could not find theEnvironment
final Map<String, String> env = System.getenv();
Stream.of(Collections.class.getDeclaredClasses())
// obtain the declared classes of type $UnmodifiableMap
.filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName()))
.map(c1 -> {
try {
return c1.getDeclaredField("m");
} catch (final NoSuchFieldException e1) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+"> when locating in-class memory map of environment", e1);
}
})
.forEach(field -> {
try {
final boolean fieldAccessibility = field.isAccessible();
field.setAccessible(true);
// we obtain the environment
final Map<String, String> map = (Map<String, String>) field.get(env);
if (value == null) {
// remove if null
map.remove(key);
} else {
map.put(key, value);
}
// reset accessibility
field.setAccessible(fieldAccessibility);
} catch (final ConcurrentModificationException e1) {
// This may happen if we keep backups of the environment before calling this method
// as the map that we kept as a backup may be picked up inside this block.
// So we simply skip this attempt and continue adjusting the other maps
// To avoid this one should always keep individual keys/value backups not the entire map
LOGGER.info("Attempted to modify source map: "+field.getDeclaringClass()+"#"+field.getName(), e1);
} catch (final IllegalAccessException e1) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">. Unable to access field!", e1);
}
});
}
LOGGER.info("Set environment variable <"+key+"> to <"+value+">. Sanity Check: "+System.getenv(key));
}
Java Advanced Imaging is now open source, and provides the operations you need.
A basic while loop is often the fastest. jsperf.com is a great sandbox to test these types of concepts.
It is very important that AJAX requests retain session. The easiest example is when you try to do an AJAX request for the admin panel, let's say. Of course that you will protect the page that you make the request to, not to accessible by others who don't have the session you get after administrator login. Makes sense?
To install the OpenCV package with conda, run:
conda install -c menpo opencv3=3.1.0
It is as easy as this (it works for dynamic objects as well (type object)):
string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
This is what works on my first generation Droid X with Android version 2.3.4. I suspect that this will be universal. Steps:
root system and install su.
Install busybox
Install a terminal program.
to mount system rw first su then
busybox mount -o rw,remount system
To remount ro
busybox mount -o ro,remount system
Note that there are no slashes on "system".
git splits
. I created it as a git extension, based on jkeating's solution. Split the directories into a local branch
#change into your repo's directory
cd /path/to/repo
#checkout the branch
git checkout XYZ
#split multiple directories into new branch XYZ
git splits -b XYZ XY1 XY2
Create an empty repo somewhere. We'll assume we've created an empty repo called xyz
on GitHub that has path : [email protected]:simpliwp/xyz.git
Push to the new repo.
#add a new remote origin for the empty repo so we can push to the empty repo on GitHub
git remote add origin_xyz [email protected]:simpliwp/xyz.git
#push the branch to the empty repo's master branch
git push origin_xyz XYZ:master
Clone the newly created remote repo into a new local directory
#change current directory out of the old repo
cd /path/to/where/you/want/the/new/local/repo
#clone the remote repo you just pushed to
git clone [email protected]:simpliwp/xyz.git
Templates:
Pass function name and argument.
<a href="{{ url_for('get_blog_post',id = blog.id)}}">{{blog.title}}</a>
View,function
@app.route('/blog/post/<string:id>',methods=['GET'])
def get_blog_post(id):
return id
$('input').each(function() {
if ($(this).val() != '') {
console.log('all inputs filled');
}
else{
console.log('theres an empty input');
return false
}
});
you might want to wrap this in a keyup function
If u want to Selected text clear then using to this code i will make by my self ;)
If e.KeyCode = Keys.Delete Then
TextBox1.SelectedText = ""
End If
thats it
As an alternative to the PROGRA~2 method (which is not working for example in IntelliJ IDEA), you can create a symbolic link.
It can be named, for example, prg
to Program Files
(run mklink /?
from the command line to learn how to do it). Then run the emulator as C:\prg\Android\android-sdk\tools\emulator.exe
. Also change the path to SDK/emulator in your IDE.
I did some mock testing to record the difference between save()
and persist()
.
Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.
For the below example, take EmployeeVehicle as an Entity with PK as vehicleId
which is a generated value and vehicleName
as one of its properties.
Example 1 : Dealing with Transient Object
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = new EmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();
Result:
select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)
Note the result is same when you get an already persisted object and save it
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
entity.setVehicleName("Toyota");
session.save(entity); -------> **instead of session.update(entity);**
// session.persist(entity);
Repeat the same using persist(entity)
and will result the same with new Id ( say 37 , honda ) ;
Example 2 : Dealing with Detached Object
// Session 1
// Get the previously saved Vehicle Entity
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached object
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();
Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"
select nextval ('hibernate_sequence')
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)
Using persist to persist detached entity
// (ii) Using Persist() to persist a detached
// Session 1
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();
Result:
Exception being thrown : detached entity passed to persist
So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with Transient object .
Important Note : In the above example , the pk of vehicle entity is a generated value , so when using save() to persist a detached entity , hibernate generates a new id to persist . However if this pk is not a generated value than it is result in a exception stating key violated.
By combining all answers above I came with following function :
from datetime import datetime, tzinfo, timedelta
class simple_utc(tzinfo):
def tzname(self,**kwargs):
return "UTC"
def utcoffset(self, dt):
return timedelta(0)
def getdata(yy, mm, dd, h, m, s) :
d = datetime(yy, mm, dd, h, m, s)
d = d.replace(tzinfo=simple_utc()).isoformat()
d = str(d).replace('+00:00', 'Z')
return d
print getdata(2018, 02, 03, 15, 0, 14)
Updated one. it works for me.
function ClickConnect(){
console.log("Working");
document.querySelector("paper-icon-button").click()
}
Const myjob = setInterval(ClickConnect, 60000)
_x000D_
If isn't working you for you guys try clear it by running:
clearInterval(myjob)
_x000D_
As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema
namespace.
Try width:inherit
to make the image take the width of it's container <div>
. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>
, it will size to fit the image height.
img {
width:inherit;
}
.item {
border:1px solid pink;
width: 120px;
float: left;
margin: 3px;
padding: 3px;
}
The right answer is
Decoupled the build-specific components of the Android SDK from the platform-tools component, so that the build tools can be updated independently of the integrated development environment (IDE) components.
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
Maybe you could use this view, but i'm not sure.
select * from v$database;
But I think It will only show you info about the current db.
Other option, if the db is running in linux... whould be something like this:
SQL>!grep SID $TNS_ADMIN/tnsnames.ora | grep -v PLSExtProc
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
It's entirely possible in browser-side javascript.
The easy way:
The readAsDataURL() method might already encode it as base64 for you. You'll probably need to strip out the beginning stuff (up to the first ,
), but that's no biggie. This would take all the fun out though.
The hard way:
If you want to try it the hard way (or it doesn't work), look at readAsArrayBuffer()
. This will give you a Uint8Array and you can use the method specified. This is probably only useful if you want to mess with the data itself, such as manipulating image data or doing other voodoo magic before you upload.
There are two methods:
btoa
or similar
I recently implemented tar in the browser. As part of that process, I made my own direct Uint8Array->base64 implementation. I don't think you'll need that, but it's here if you want to take a look; it's pretty neat.
What I do now:
The code for converting to string from a Uint8Array is pretty simple (where buf is a Uint8Array):
function uint8ToString(buf) {
var i, length, out = '';
for (i = 0, length = buf.length; i < length; i += 1) {
out += String.fromCharCode(buf[i]);
}
return out;
}
From there, just do:
var base64 = btoa(uint8ToString(yourUint8Array));
Base64 will now be a base64-encoded string, and it should upload just peachy. Try this if you want to double check before pushing:
window.open("data:application/octet-stream;base64," + base64);
This will download it as a file.
Other info:
To get the data as a Uint8Array, look at the MDN docs:
well i would suggest you to check condition in your controller with a function returning true or false .
<div class="week-wrap" ng-class="{today: getTodayForHighLight(todayDate, day.date)}">{{day.date}}</div>
and in your controller check the condition
$scope.getTodayForHighLight = function(today, date){
return (today == date);
}
I just hit this error after trying to "git submodule init" on a new checkout of my repo. Turns out I had specified the module sub-folder with the wrong case initially. Since I'm on a Mac with a case-sensitive filesystem (hurr) it was failing. For example:
git submodule add [email protected]:user/project.git MyApp/Resources/Project
Cloning into 'MyApp/Resources/Project'
succeeds but the trouble is that on disk the path is
Myapp/Resources/Project
What I don't understand is why git is init'ing the module to wrong folder (ignoring the incorrect case in my command) but then operating correctly (by failing) with subsequent commands.
You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").
So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.
Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am
or -pl
command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
The Swift 2 version:
// start detecting pan gesture
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TTAltimeterDetailViewController.panGestureDetected(_:)))
panGestureRecognizer.minimumNumberOfTouches = 1
self.chartOverlayView.addGestureRecognizer(panGestureRecognizer)
func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
print("pan gesture recognized")
}
10.0.2.2 is alis made for base machine localhost.
port number same : 1521 no need to change
abs works fine for me ..
There's no fully compliant, official HTML way to do it, but a little javascript can go a long way. Another problem you'll run into is that disabled fields don't show up in the POST data
Add following code to the 'activity' of Manifest file.
android:windowSoftInputMode="adjustResize"
If this example can help, adds a "custom confirm popin" on some links (I keep the code of "$.ui.Modal.confirm", it's just an exemple for the callback that executes the original action) :
//Register "custom confirm popin" on click on specific links
$(document).on(
"click",
"A.confirm",
function(event){
//prevent default click action
event.preventDefault();
//show "custom confirm popin"
$.ui.Modal.confirm(
//popin text
"Do you confirm ?",
//action on click 'ok'
function() {
//Unregister handler (prevent loop)
$(document).off("click", "A.confirm");
//Do default click action
$(event.target)[0].click();
}
);
}
);
You have to set both layout_gravity and layout_columntWeight on your columns
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
</android.support.v7.widget.GridLayout>
An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim
id
overviewAn Android id
is an integer commonly used to identify views; this id
can be assigned via XML (when possible) and via code (programmatically.) The id
is most useful for getting references for XML-defined View
s generated by an Inflater
(such as by using setContentView
.)
id
via XML
android:id="@+id/
somename"
to your view.android:id
will be assigned a unique int
for use in code.android:id
's int
value in code using "R.id.
somename" (effectively a constant.)int
can change from build to build so never copy an id from gen/
package.name/R.java
, just use "R.id.
somename".id
assigned to a Preference
in XML is not used when the Preference
generates its View
.)id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)id
sXML
-assigned id
s will be unique.id
s do not have to be uniqueid
s can (theoretically) conflict with XML
-assigned id
s.id
s won't matter if queried correctly (keep reading).id
s don't matterfindViewById(int)
will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View
it finds with a matching id
.id
s assigned before an XML-defined id
in the hierarchy, findViewById(R.id.somename)
will always return the XML-defined View so id
'd.ID
sViewGroup
with id
.LinearLayout
with android:id="@+id/placeholder"
.ViewGroup
with View
s.id
s that are convenient to each view.Query these child views using placeholder.findViewById(convenientInt);
API 17 introduced View.generateViewId()
which allows you to generate a unique ID.
If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext()
and be sure to set each reference to null in onDestroy
. Apparently leaking the Activity
(hanging onto it after is is destroyed) is wasteful.. :)
android:id
for use in codeAPI 17 introduced View.generateViewId()
which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
Here, values/ids.xml defines a custom id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
myViewGroup.setId(R.id.reservedNamedId);
id
exampleFor clarity by way of obfuscating example, lets examine what happens when there is an id
conflict behind the scenes.
layout/mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
To simulate a conflict, lets say our latest build assigned R.id.placeholder
(@+id/placeholder
) an int
value of 12
..
Next, MyActivity.java defines some adds views programmatically (via code):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
So placeholder
and one of our new TextView
s both have an id
of 12! But this isn't really a problem if we query placeholder's child views:
// Will return a generated TextView:
placeholder.findViewById(12);
// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);
*Not so bad
var ids = [];
$('input[id="find-table"]:checked').each(function() {
ids.push(this.value);
});
This one worked for me!
I had the same question but about rather short vector<bool>
(afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):
-O0 -O3
-------- --------
memset 0.666 1.045
fill 19.357 1.066
iterator 67.368 1.043
assign 17.975 0.530
for i 22.610 1.004
So apparently for these sizes, vector<bool>::assign()
is faster. The code used for tests:
#include <vector>
#include <cstring>
#include <cstdlib>
#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;
using namespace std;
int main(int argc, char** argv) {
std::vector<int> v(TEST_ARRAY_SIZE, 0);
for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
std::fill(v.begin(), v.end(), false);
#elif TEST_METHOD == 3
for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
*it = 0;
}
#elif TEST_METHOD == 4
v.assign(v.size(),false);
#elif TEST_METHOD == 5
for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
v[i] = false;
}
#endif
}
return EXIT_SUCCESS;
}
I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:
g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
My answer
/**
* Display form to reply comment
*/
function displayReplyForm(commentId) {
var replyForm = $('#reply-form-' + commentId);
if (replyForm.css('display') == 'block') { // Current display
replyForm.css('display', 'none');
} else { // Hide reply form
replyForm.css('display', 'block');
}
}
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
You can try below code in Global.asax file.
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
Can you not use like this?
@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);
P.S. I write queries in SQL Server 2012 a lot and using nolock
in server is a good practice, you can ignore nolock
if a local db is used.
Seems like your db name is not being mapped correctly (after you've updated your question)
If you get the the text inside the element use
$(".element-classname").text();
In your code:
$('.HOEnZb').text();
if you want get all the data including html Tags use:
$(".element-classname").html();
In your code:
$('.HOEnZb').html();
Hope it helps:)
static_cast
is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast
performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:
void func(void *data) {
// Conversion from MyClass* -> void* is implicit
MyClass *c = static_cast<MyClass*>(data);
...
}
int main() {
MyClass c;
start_thread(&func, &c) // func(&c) will be called
.join();
}
In this example, you know that you passed a MyClass
object, and thus there isn't any need for a runtime check to ensure this.
dynamic_cast
is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast
exception is thrown in that case).
if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
...
}
You cannot use dynamic_cast
if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base
doesn't contain any virtual function:
struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast<Derived*>(b); // Invalid
}
An "up-cast" (cast to the base class) is always valid with both static_cast
and dynamic_cast
, and also without any cast, as an "up-cast" is an implicit conversion.
These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast
. Needless to say, this is much more powerful as it combines all of const_cast
, static_cast
and reinterpret_cast
, but it's also unsafe, because it does not use dynamic_cast
.
In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast
sequence would give you a compile-time error for that.
Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.
My issue was a missing set of quotes;
Foo: bar 'baz'
should be
Foo: "bar 'baz'"
There's a much better answer than using spliteratorUnknownSize
directly, which is both easier and gets a better result. Iterable
has a spliterator()
method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize
), but in the more common case, where your Iterable
is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:
StreamSupport.stream(iterable.spliterator(), false)
.filter(...)
.moreStreamOps(...);
As you can see, getting a stream from an Iterable
(see also this question) is not very painful.
It's a pretty old question, but for the sake of newcomers, this is how we can protect an IEnumerable<T>
from a null exception
. Another word, to create an empty instance of a variable of type IEnumerable<T>
public IEnumerable<T> MyPropertyName { get; set; } = Enumerable.Empty<T>();
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=net-5.0
Cheers.
You have already executed your query here
$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");
So this line has the problem
$retval = mysql_query( $sql, $conn ); //$sql is not a query its a result set here
Try something like this:
$sql = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'";
$retval = mysql_query( $sql, $conn ); //execute your query
As a sidenote: MySQL_* extension is deprecated use MySQLi_* or PDO instead.
Just check against null.
($myObject.MyProperty -ne $null)
If you have not set PowerShell to StrictMode, this works even if the property does not exist:
$obj = New-Object PSObject;
Add-Member -InputObject $obj -MemberType NoteProperty -Name Foo -Value "Bar";
$obj.Foo; # Bar
($obj.MyProperty -ne $null); # False, no exception
To just get a list of the commit hashes use git rev-list
git rev-list HEAD <filename>
Output:
b7c4f0d7ebc3e4c61155c76b5ebc940e697600b1
e3920ac6c08a4502d1c27cea157750bd978b6443
ea62422870ea51ef21d1629420c6441927b0d3ea
4b1eb462b74c309053909ab83451e42a7239c0db
4df2b0b581e55f3d41381f035c0c2c9bd31ee98d
which means 5 commits have touched this file. It's reverse chronological order, so the first commit in the list b7c4f0d7
is the most recent one.
HTML css works fine if body tag does nothing you can write as well
<body scroll="no" style="overflow: hidden">
In this case overriding should be on the body tag, it is easier to control but sometimes gives headaches.
A bit late to the party here but here's how simple this is:
ViewBag.Countries = new SelectList(countries.GetCountries(), "id", "countryName", "82");
this uses my method getcountries to populate a model called countries, obviousley you would replace this with whatever your datasource is, a model etc, then sets the id as the value in the selectlist. then just add the last param, in this case "82" to select the default selected item.
[edit] Here's how to use this in Razor:
@Html.DropDownListFor(model => model.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries, new { @class = "form-control" })
Important: Also, 1 other thing to watch out for, Make sure the model field that you use to store the selected Id (in this case model.CountryId) from the dropdown list is nullable and is set to null on the first page load. This one gets me every time.
Hope this saves someone some time.
First off i would like to thank Avanka for helping me solve my focus problem. There is however a bug in the code he posted, namely in the line: if (e.OldValue == null)
The problem I had was that if you first click in your view and focus the control, e.oldValue is no longer null. Then when you set the variable to focus the control for the first time, this results in the lostfocus and gotfocus handlers not being set. My solution to this was as follows:
public static class ExtensionFocus
{
static ExtensionFocus()
{
BoundElements = new List<string>();
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool?),
typeof(ExtensionFocus), new FrameworkPropertyMetadata(false, IsFocusedChanged));
private static List<string> BoundElements;
public static bool? GetIsFocused(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus GetIsFocused called with null element");
}
return (bool?)element.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject element, bool? value)
{
if (element == null)
{
throw new ArgumentNullException("ExtensionFocus SetIsFocused called with null element");
}
element.SetValue(IsFocusedProperty, value);
}
private static void IsFocusedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)d;
// OLD LINE:
// if (e.OldValue == null)
// TWO NEW LINES:
if (BoundElements.Contains(fe.Name) == false)
{
BoundElements.Add(fe.Name);
fe.LostFocus += OnLostFocus;
fe.GotFocus += OnGotFocus;
}
if (!fe.IsVisible)
{
fe.IsVisibleChanged += new DependencyPropertyChangedEventHandler(fe_IsVisibleChanged);
}
if ((bool)e.NewValue)
{
fe.Focus();
}
}
private static void fe_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var fe = (FrameworkElement)sender;
if (fe.IsVisible && (bool)((FrameworkElement)sender).GetValue(IsFocusedProperty))
{
fe.IsVisibleChanged -= fe_IsVisibleChanged;
fe.Focus();
}
}
private static void OnLostFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, false);
}
}
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
if (sender != null && sender is Control s)
{
s.SetValue(IsFocusedProperty, true);
}
}
}
While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.
Nettica must be running a custom redirection solution for this, here is the problem:
You could create a CNAME alias like aws.example.com
for myaccount.signin.aws.amazon.com
, however, DNS provides no official support for aliasing a subdirectory like console
in this example.
https://myaccount.signin.aws.amazon.com/
(I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.
So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.
How about this:
import sys
import subprocess
theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate() # ^^^^^^^^^^^^
This tells subprocess
to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.
Additionally, this will search the PATH for "myscript.py" - which could be desirable.
Use DBNull.Value
Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime>
parameter if the parameter will sometimes be a valid DateTime object
Git 1.8.2 features a new option ,--remote
, that will enable exactly this behavior. Running
git submodule update --rebase --remote
will fetch the latest changes from upstream in each submodule, rebase them, and check out the latest revision of the submodule. As the documentation puts it:
--remote
This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.
This is equivalent to running git pull
in each submodule, which is generally exactly what you want.
(This was copied from this answer.)
Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.
For example:
<#include "Component/BoxComponent.h"
This will result in the error. Instead, it needs to be:
<#include "Components/BoxComponent.h"
Have you considered using factory functions? They usually are a much better alternative to classes or constructor functions in Javascript. Here is an example of how it works:
function car () {
var privateVariable = 4
function privateFunction () {}
return {
color: 'red',
drive: function (miles) {},
stop: function() {}
....
}
}
Thanks to closures you have access to all private functions and variabels inside the returned object, but you can not access them from outside.
This is an encoding issue. It looks like at some point, the data gets represented as ISO-8859-1.
Every part of your process needs to be UTF-8 encoded.
The database connection
The database tables
Your PHP file (if you are using special characters inside that file as shown in your example above)
The content-type
headers that you output
Did you import it? Importing matplotlib
is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot
works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt
Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])
instead of
matplotlib.pyplot.plot([1,2,3,4,5])
And: pyplot
is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
What database are you connecting to? I know Oracle can be picky about date formats and likes ISO 8601 format.
**Note: Oops, I just read you are on MySQL. Just format the date and try it as a separate direct SQL call to test.
In Python, you can get an ISO date like
now.isoformat()
For instance, Oracle likes dates like
insert into x values(99, '31-may-09');
Depending on your database, if it is Oracle you might need to TO_DATE it:
insert into x
values(99, to_date('2009/05/31:12:00:00AM', 'yyyy/mm/dd:hh:mi:ssam'));
The general usage of TO_DATE is:
TO_DATE(<string>, '<format>')
If using another database (I saw the cursor and thought Oracle; I could be wrong) then check their date format tools. For MySQL it is DATE_FORMAT() and SQL Server it is CONVERT.
Also using a tool like SQLAlchemy will remove differences like these and make your life easy.
The following worked just fine in all scenarios i needed :
"dependencies": {
"GitRepo": "git+https://<token-from-github>:[email protected]/<user>/<GitRepo>.git"
}
From .NET 4.5 on, there is the Stream.CopyToAsync
method
input.CopyToAsync(output);
This will return a Task
that can be continued on when completed, like so:
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
Note that depending on where the call to CopyToAsync
is made, the code that follows may or may not continue on the same thread that called it.
The SynchronizationContext
that was captured when calling await
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the Stream.CopyTo
method
input.CopyTo(output);
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length
? Because that Length may not be available! From the docs:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
You could recreate the progress bar using CSS3 animations to give it a better look.
HTML
<div class="outer_div">
<div class="inner_div">
<div id="percent_count">
</div>
</div>
CSS/CSS3
.outer_div {
width: 250px;
height: 25px;
background-color: #CCC;
}
.inner_div {
width: 5px;
height: 21px;
position: relative; top: 2px; left: 5px;
background-color: #81DB92;
box-shadow: inset 0px 0px 20px #6CC47D;
-webkit-animation-name: progressBar;
-webkit-animation-duration: 3s;
-webkit-animation-fill-mode: forwards;
}
#percent_count {
font: normal 1em calibri;
position: relative;
left: 10px;
}
@-webkit-keyframes progressBar {
from {
width: 5px;
}
to {
width: 200px;
}
}
Here is just another (responsive) approach:
html,
body {
height: 100%;
}
body {
margin: 0;
}
.table {
display: table;
width: auto;
table-layout:auto;
height: 100%;
}
.table:nth-child(even) {
background: #a9edc3;
}
.table:nth-child(odd) {
background: #eda9ce;
}
.tr {
display: table-row;
}
.td {
display: table-cell;
width: 50%;
vertical-align: middle;
}
Padding a UILabel
, full solution. Updated for 2021.
It turns out there are three things that must be done.
In the typical example below, the text unit is in a table view, stack view or similar construction, which gives it a fixed width. In the example we want padding of 60,20,20,24.
Thus, we take the "existing" intrinsicContentSize and actually add 80 to the height.
You have to literally "get" the height calculated "so far" by the engine, and change that value.
I find that process confusing, but, that is how it works. For me, Apple should expose a call named something like "preliminary height calculation".
Secondly we have to actually use the textRect#forBounds call with our new smaller size.
So in textRect#forBounds we first make the size smaller and then call super.
If you carefully investigate all the attempts and discussion on this page, that is the exact problem.
Notice some solutions "seem to usually work". This is indeed the exact reason - confusingly you must "call super afterwards", not before.
If you call super "in the wrong order", it usually works, but fails for certain specific text lengths.
Here is an exact visual example of "incorrectly doing super first":
Notice the 60,20,20,24 margins are correct BUT the size calculation is actually wrong, because it was done with the "super first" pattern in textRect#forBounds.
Fixed:
Only now does the textRect#forBounds engine know how to do the calculation properly:
Finally!
Again, in this example the UILabel is being used in the typical situation where width is fixed. So in intrinsicContentSize we have to "add" the overall extra height we want. (You don't need to "add" in any way to the width, that would be meaningless as it is fixed.)
Then in textRect#forBounds you get the bounds "suggested so far" by autolayout, you subtract your margins, and only then call again to the textRect#forBounds engine, that is to say in super, which will give you a result.
Finally and simply in drawText you of course draw in that same smaller box.
Phew!
let UIEI = UIEdgeInsets(top: 60, left: 20, bottom: 20, right: 24) // as desired
override var intrinsicContentSize:CGSize {
numberOfLines = 0 // don't forget!
var s = super.intrinsicContentSize
s.height = s.height + UIEI.top + UIEI.bottom
s.width = s.width + UIEI.left + UIEI.right
return s
}
override func drawText(in rect:CGRect) {
let r = rect.inset(by: UIEI)
super.drawText(in: r)
}
override func textRect(forBounds bounds:CGRect,
limitedToNumberOfLines n:Int) -> CGRect {
let b = bounds
let tr = b.inset(by: UIEI)
let ctr = super.textRect(forBounds: tr, limitedToNumberOfLines: 0)
// that line of code MUST be LAST in this function, NOT first
return ctr
}
Once again. Note that the answers on this and other QA that are "almost" correct suffer the problem in the first image above - the "super is in the wrong place". You must force the size bigger in intrinsicContentSize and then in textRect#forBounds you must first shrink the first-suggestion bounds and then call super.
That's the secret.
Note that you do not need to and should not need to additionally call invalidate, sizeThatFits, needsLayout or any other forcing call. A correct solution should work properly in the normal autolayout draw cycle.
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
I use open query to perform this task like so:
select top 1 *
INTO [DATABASE_TO_INSERT_INTO].[dbo].[TABLE_TO_SELECT_INTO]
from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)
The example above uses open query to select data from a database on a linked server into a database of your choosing.
Note: For completeness of reference, you may perform a simple select like so:
select top 1 * from openquery(
[LINKED_SERVER_NAME],
'select * from [DATABASE_ON_LINKED_SERVER].[dbo].[TABLE_TO_SELECT_FROM]'
)
this worked for me to solve the problem in IE8:
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=1)";
Cheers
As jeremyjjbrow said, :active
pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a>
tag, and apply the :active
on it, like this:
<a class="test">
<img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
</a>
And the css:
.test:active .crossRotate {
transform: rotate(45deg);
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
}
Try it out... It works (at least on Chrome)!
For example, to set the background to your favorite/Branding color
Add Below Meta property to your HTML code in HEAD Section
<head>
...
<meta name="theme-color" content="Your Hexadecimal Code">
...
</head>
Example
<head>
...
<meta name="theme-color" content="#444444">
...
</head>
In Below Image, I just mentioned How Chrome taken your theme-color Property
Firefox OS, Safari, Internet Explorer and Opera Coast allow you to define colors for elements of the browser, and even the platform using meta tags.
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
From the guidelinesDocuments Here
Hiding Safari User Interface Components
Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.
<meta name="apple-mobile-web-app-capable" content="yes">
Changing the Status Bar Appearance
You can change the appearance of the default status bar to either black or black-translucent. With black-translucent, the status bar floats on top of the full screen content, rather than pushing it down. This gives the layout more height, but obstructs the top. Here’s the code required:
<meta name="apple-mobile-web-app-status-bar-style" content="black">
For more on status bar appearance, see apple-mobile-web-app-status-bar-style.
For Example:
Screenshot using black-translucent
Screenshot using black
You are missing the view engine, for example use jade:
change your
app.set('view engine', 'html');
with
app.set('view engine', 'jade');
If you want use a html friendly syntax use instead ejs
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
EDIT
As you can read from view.js Express View Module
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
* @param {String} name
* @param {Object} options
* @api private
*/
function View(name, options) {
options = options || {};
this.name = name;
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
}
You must have installed a default engine
Express
search default layout view by program.template
as you can read below:
mkdir(path + '/views', function(){
switch (program.template) {
case 'ejs':
write(path + '/views/index.ejs', ejsIndex);
break;
case 'jade':
write(path + '/views/layout.jade', jadeLayout);
write(path + '/views/index.jade', jadeIndex);
break;
case 'jshtml':
write(path + '/views/layout.jshtml', jshtmlLayout);
write(path + '/views/index.jshtml', jshtmlIndex);
break;
case 'hjs':
write(path + '/views/index.hjs', hoganIndex);
break;
}
});
and as you can read below:
program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';
the default view engine is jade
Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.
I also found that I didn't need the JavaScript.
I added the following class to my Models folder:
public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object InvalidValue { get; set; }
private readonly RequiredAttribute _innerAttribute;
public RequiredIfNotAttribute(String propertyName, Object invalidValue)
{
PropertyName = propertyName;
InvalidValue = invalidValue;
_innerAttribute = new RequiredAttribute();
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
if (dependentValue.ToString() != InvalidValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredifnot",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;
yield return rule;
}
I didn't need to make any changes to my view, but did make a change to the properties of my model:
[RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
public string TemplateGTSource { get; set; }
public string TemplateGTMedium
{
get
{
return "Email";
}
}
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
public string TemplateGTCampaign { get; set; }
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
public string TemplateGTTerm { get; set; }
Hope this helps!
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
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
sub Release()
set objExcelApp = Nothing
end sub
I would use
\b[A-Za-z]*Id\b
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.
The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.
Note that this will match words that have capital letters in the middle such as 'teStId'.
I use http://www.regular-expressions.info/ for regex reference
1) use for tommorow's date startDate: '+1d'
2) use for yesterday's date startDate: '-1d'
3) use for today's date startDate: new Date()
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
// Get script file location
// doesn't work for older browsers
var getScriptLocation = function() {
var fileName = "fileName";
var stack = "stack";
var stackTrace = "stacktrace";
var loc = null;
var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };
try {
// Invalid code
0();
} catch (ex) {
if(fileName in ex) { // Firefox
loc = ex[fileName];
} else if(stackTrace in ex) { // Opera
ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
} else if(stack in ex) { // WebKit, Blink and IE10
ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
}
return loc;
}
};
You can see it here.
This is worked for me, anyone can try it
$("#myModal").on("hidden.bs.modal", function () {
for (instance in CKEDITOR.instances)
CKEDITOR.instances[instance].destroy();
$('#myModal .modal-body').html('');
});
you can open ckEditor in Modal window
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S), Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations. GET - represent() POST - acceptRepresention() PUT - storeRepresention() DELETE - removeRepresention()
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better. SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not. The SOAP has comprehensive support for both ACID based transaction management for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.
source http://java-success.blogspot.in/2012/02/java-web-services-interview-questions.html
You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.
Step 1, generate public and private key on build server as user jenkins
build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa):
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...]
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw------- 1 jenkins jenkins 1679 Feb 28 11:55 id_rsa
-rw-r--r-- 1 jenkins jenkins 411 Feb 28 11:55 id_rsa.pub
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]
Step 2, paste the pub file contents onto the target server.
target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)
Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644
Step 3, configure Jenkins
Golden Rule: If you alloc
then you release
!
UPDATE: Unless you are using ARC
One option is weinre. It provides DOM & Style editing along with the console. If you don't want to set it up yourself, there is an instance hosted at http://debug.phonegap.com
The other option is JSHybugger. It's certainly the most complete debugging environment available for android browser. It's a paid product, but probably worth it.
SUBSTITUTE()
in a string can be nasty, however, it's always possible to arrange it: I have to mention the path.py library, which I use very often.
Fetching the immediate subdirectories become as simple as that:
my_dir.dirs()
The full working example is:
from path import Path
my_directory = Path("path/to/my/directory")
subdirs = my_directory.dirs()
NB: my_directory still can be manipulated as a string, since Path is a subclass of string, but providing a bunch of useful methods for manipulating paths
The code blocks are not equivalent. The finally
clause will also be run if run_code1()
throws an exception other than TypeError
, or if run_code2()
throws an exception, while other_code()
in the first version wouldn't be run in these cases.
Started a jsFiddle here.
It seems the horizontal alignment works with a text-align : center
. Still trying to get the vertical align to work; might have to use absolute
positioning and something like top: 50%
or a pre-calculated padding
from the top.
Try checking for the :visible property instead.
if($('#car2').not(':visible'))
{
alert('car 2 is hidden');
}
On mac os, please follow below steps:
Stop MySQL
$ sudo /usr/local/mysql/support-files/mysql.server stop Start it in safe mode:
$ sudo mysqld_safe --skip-grant-tables (above line is the whole command)
This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; Start MySQL
sudo /usr/local/mysql/support-files/mysql.server start your new password is 'password'.
I understand SelectMany
to work like a join shortcut.
So you can:
var orders = customers
.Where(c => c.CustomerName == "Acme")
.SelectMany(c => c.Orders);
Well, i also made a piece of code for limit high frequency ajax request cause by Keyup / Keydown. Check this out:
https://github.com/raincious/jQueue
Do your query like this:
var q = new jQueue(function(type, name, callback) {
return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.
And bind event like this:
$('#field-username').keyup(function() {
q.run('Username', this.val(), function() { /* calling back */ });
});
as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options
ticks: {
callback: function(value) {
return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'});
},
},
Below added code is working for me if you are using pattern dd-MM-yyyy.
public boolean isValidDate(String date) {
boolean check;
String date1 = "^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-([12][0-9]{3})$";
check = date.matches(date1);
return check;
}
After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).
int[] Data= { 1, 212, 333,2,12,3311,122,23 };
int large = Data.Max();
Console.WriteLine(large);
Before you add the chromedriver to your path, make sure it's the same version as your browser.
If not, you will need to match versions: either update/downgrade you chrome, and upgrade/downgrade your webdriver.
I recommend updating your chrome version as much as possible, and the matching the webdriver.
To update chrome:
help
-> About Google Chrome
Then download the compatible version from here: http://chromedriver.chromium.org/downloads .
Note: The newest chromedriver doesn't always match the newest version of chrome!
Now you can add it to the PATH:
create a new folder somewhere in your computer, where you will place your web drivers.
I created a folder named webdrivers
in C:\Program Files
copy the folder path. In my case it was C:\Program Files\webdrivers
right click on this PC
-> properties
:
Advanced System settings
Environment Variables
System variables
, click on path
and click edit
new
Thats it! I used pycharm and I had to reopen it. Maybe its the same with other IDEs or terminals.
A better and optimised solution to display multiple validation messages for a single element would be like this.
<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
<span class="error" ng-message="required"> <your message> </span>
<span class="error" ng-message="size"> <your message> </span>
<span class="error" ng-message="filetype"> <your message> </span>
</div>
Controller Code should be the one suggested by @ Ben Lesh
you can't use input.click()
directly, but you can call this in other element click event.
html
<input type="file">
<button>Select file</button>
js
var botton = document.querySelector('button');
var input = document.querySelector('input');
botton.addEventListener('click', function (e) {
input.click();
});
this tell you Using hidden file input elements using the click() method
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
For this to work i think you need to define the padding to ex. top? like this:
<div><p>some unnecessary content</p></div>
div{
border: 1px solid red;
width: 40%;
padding-top: 40%;
box-sizing: border-box;
position: relative;
}
p{
position: absolute;
top: 0;
left: 0;
}
anyways, thats how i got it to work, since with just padding all arround it would not be a square.
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
You're close. You can strip the whitespace by using the replace
method like this:
$answer.replace(' ','')
There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).
You don't need to define intersection. It's already a first-class part of set.
>>> b1 = [1,2,3,4,5,9,11,15]
>>> b2 = [4,5,6,7,8]
>>> set(b1).intersection(b2)
set([4, 5])
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions
var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
// map singleItem
return new OrderDetails()
{
Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),
// use reusable mapper for re-curring scenarios
Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),
Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),
// read date and total as string, as they're displayed/formatted on the excel
DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
};
});
Note: The linked Jenkins issue has since been solved.
As mention in JENKINS-26133 it was not possible to get shell output as a variable. As a workaround suggested using of writ-read from temporary file. So, your example would have looked like:
sh "echo foo > result";
def output=readFile('result').trim()
echo "output=$output";
import { FormControl, FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';_x000D_
_x000D_
_x000D_
this.userInfoForm = new FormGroup({_x000D_
userInfoUserName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoSurName: new FormControl({ value: '' }, Validators.compose([Validators.required]))_x000D_
});
_x000D_
<form [formGroup]="userInfoForm" class="form-horizontal">_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> User Name</label>_x000D_
<input type="text" formControlName="userInfoUserName" class="form-control" [(ngModel)]="userInfo.userName">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Name</label>_x000D_
<input type="text" formControlName="userInfoName" class="form-control" [(ngModel)]="userInfo.name">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Surname</label>_x000D_
<input type="text" formControlName="userInfoSurName" class="form-control" [(ngModel)]="userInfo.surName">_x000D_
</div>_x000D_
</form>
_x000D_
$ git diff tag1 tag2
or show log between them:
$ git log tag1..tag2
sometimes it may be convenient to see only the list of files that were changed:
$ git diff tag1 tag2 --stat
and then look at the differences for some particular file:
$ git diff tag1 tag2 -- some/file/name
A tag is only a reference to the latest commit 'on that tag', so that you are doing a diff on the commits between them.
(Make sure to do git pull --tags
first)
Also, a good reference: http://learn.github.com/p/diff.html
If you need to have control over the format of the date (in other words not just the yyyy-mm-dd format is acceptable), another solution could be adding a helper property that is of type string and add a date validator to that property, and bind to this property on UI.
[Display(Name = "Due date")]
[Required]
[AllowHtml]
[DateValidation]
public string DueDateString { get; set; }
public DateTime? DueDate
{
get
{
return string.IsNullOrEmpty(DueDateString) ? (DateTime?)null : DateTime.Parse(DueDateString);
}
set
{
DueDateString = value == null ? null : value.Value.ToString("d");
}
}
And here is a date validator:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class DateValidationAttribute : ValidationAttribute
{
public DateValidationAttribute()
{
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
DateTime date;
if (value is string)
{
if (!DateTime.TryParse((string)value, out date))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
else
date = (DateTime)value;
if (date < new DateTime(1900, 1, 1) || date > new DateTime(3000, 12, 31))
{
return new ValidationResult(validationContext.DisplayName + " must be a valid date.");
}
}
return null;
}
}
To all Windows users: I found a good way to run an asynchronous PHP script (actually it works with almost everything).
It's based on popen() and pclose() commands. And works well both on Windows and Unix.
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
Original code from: http://php.net/manual/en/function.exec.php#86329
What would you think of this for 3D ArrayList - can be used similarly to arrays - see the comments in the code:
import java.util.ArrayList;
import java.util.List;
/**
* ArrayList3D simulates a 3 dimensional array,<br>
* e.g: myValue = arrayList3D.get(x, y, z) is the same as: <br>
* myValue = array[x][y][z] <br>
* and<br>
* arrayList3D.set(x, y, z, myValue) is the same as:<br>
* array[x][y][z] = myValue; <br>
* but keeps its full ArrayList functionality, thus its
* benefits of ArrayLists over arrays.<br>
* <br>
* @param <T> data type
*/
public class ArrayList3D <T> {
private final List<List<List<T>>> arrayList3D;
public ArrayList3D() {
arrayList3D = newArrayDim1();
}
/**
* Get value of the given array element.<br>
* E.g: get(2, 5, 3);<br>
* For 3 dim array this would equal to:<br>
* nyValue = array[2][5][3];<br>
* <br>
* Throws: IndexOutOfBoundsException
* - if any index is out of range
* (index < 0 || index >= size())<br>
* <br>
* @param dim1 index of the first dimension of the array list
* @param dim2 index of the second dimension of the array list
* @param dim3 index of the third dimension of the array list
* @return value of the given array element (of type T)
*/
public T get(int dim1, int dim2, int dim3) {
List<List<T>> ar2 = arrayList3D.get(dim1);
List<T> ar3 = ar2.get(dim2);
return ar3.get(dim3);
}
/**
* Set value of the given array.<br>
* E.g: set(2, 5, 3, "my value");<br>
* For 3 dim array this would equal to:<br>
* array[2][5][3]="my value";<br>
* <br>
* Throws: IndexOutOfBoundsException
* - if any index is out of range
* (index < 0 || index >= size())<br>
* <br>
* @param dim1 index of the first dimension of the array list
* @param dim2 index of the second dimension of the array list
* @param dim3 index of the third dimension of the array list
* @param value value to assign to the given array
* <br>
*/
public void set(int dim1, int dim2, int dim3, T value) {
arrayList3D.get(dim1).get(dim2).set(dim3, value);
}
/**
* Set value of the given array element.<br>
* E.g: set(2, 5, 3, "my value");<br>
* For 3 dim array this would equal to:<br>
* array[2][5][3]="my value";<br>
* <br>
* Throws: IndexOutOfBoundsException
* - if any index is less then 0
* (index < 0)<br>
* <br>
* @param indexDim1 index of the first dimension of the array list
* @param indexDim2 index of the second dimension of the array list
* If you set indexDim1 or indexDim2 to value higher
* then the current max index,
* the method will add entries for the
* difference. The added lists will be empty.
* @param indexDim3 index of the third dimension of the array list
* If you set indexDim3 to value higher
* then the current max index,
* the method will add entries for the
* difference and fill in the values
* of param. 'value'.
* @param value value to assign to the given array index
*/
public void setOrAddValue(int indexDim1,
int indexDim2,
int indexDim3,
T value) {
List<T> ar3 = setOrAddDim3(indexDim1, indexDim2);
int max = ar3.size();
if (indexDim3 < 0)
indexDim3 = 0;
if (indexDim3 < max)
ar3.set(indexDim3, value);
for (int ix = max-1; ix < indexDim3; ix++ ) {
ar3.add(value);
}
}
private List<List<List<T>>> newArrayDim1() {
List<T> ar3 = new ArrayList<>();
List<List<T>> ar2 = new ArrayList<>();
List<List<List<T>>> ar1 = new ArrayList<>();
ar2.add(ar3);
ar1.add(ar2);
return ar1;
}
private List<List<T>> newArrayDim2() {
List<T> ar3 = new ArrayList<>();
List<List<T>> ar2 = new ArrayList<>();
ar2.add(ar3);
return ar2;
}
private List<T> newArrayDim3() {
List<T> ar3 = new ArrayList<>();
return ar3;
}
private List<List<T>> setOrAddDim2(int indexDim1) {
List<List<T>> ar2 = null;
int max = arrayList3D.size();
if (indexDim1 < 0)
indexDim1 = 0;
if (indexDim1 < max)
return arrayList3D.get(indexDim1);
for (int ix = max-1; ix < indexDim1; ix++ ) {
ar2 = newArrayDim2();
arrayList3D.add(ar2);
}
return ar2;
}
private List<T> setOrAddDim3(int indexDim1, int indexDim2) {
List<List<T>> ar2 = setOrAddDim2(indexDim1);
List<T> ar3 = null;
int max = ar2.size();
if (indexDim2 < 0)
indexDim2 = 0;
if (indexDim2 < max)
return ar2.get(indexDim2);
for (int ix = max-1; ix < indexDim2; ix++ ) {
ar3 = newArrayDim3();
ar2.add(ar3);
}
return ar3;
}
public List<List<List<T>>> getArrayList3D() {
return arrayList3D;
}
}
And here is a test code:
ArrayList3D<Integer> ar = new ArrayList3D<>();
int max = 3;
for (int i1 = 0; i1 < max; i1++) {
for (int i2 = 0; i2 < max; i2++) {
for (int i3 = 0; i3 < max; i3++) {
ar.setOrAddValue(i1, i2, i3, (i3 + 1) + (i2*max) + (i1*max*max));
int x = ar.get(i1, i2, i3);
System.out.println(" - " + i1 + ", " + i2 + ", " + i3 + " = " + x);
}
}
}
Result output:
Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding.
It is present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859-1, and it's an annoying but now-standard web browser behaviour that if you serve your pages as ISO-8859-1, the browser will treat them as cp1252 instead. However, they really are two distinct encodings:
>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'
If you are using your database only as a byte store, you can use cp1252 to encode “
and other characters present in the Windows Western code page. But still other Unicode characters which are not present in cp1252 will cause errors.
You can use encode(..., 'ignore')
to suppress the errors by getting rid of the characters, but really in this century you should be using UTF-8 in both your database and your pages. This encoding allows any character to be used. You should also ideally tell MySQL you are using UTF-8 strings (by setting the database connection and the collation on string columns), so it can get case-insensitive comparison and sorting right.
are you sure you told it to expect the exception?
for newer junit (>= 4.7), you can use something like (from here)
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testRodneCisloRok(){
exception.expect(IllegalArgumentException.class);
exception.expectMessage("error1");
new RodneCislo("891415",dopocitej("891415"));
}
and for older junit, this:
@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
This should do it:
ALTER TABLE test MODIFY locationExpert VARCHAR(120)
To convert the private key from PKCS#1 to PKCS#8 with openssl:
# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key
That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.
ES8(2017) try
obj = await (await fetch(url)).json();
async function load() {_x000D_
let url = 'https://my-json-server.typicode.com/typicode/demo/db';_x000D_
let obj = await (await fetch(url)).json();_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
you can handle errors by try-catch
async function load() {_x000D_
let url = 'http://query.yahooapis.com/v1/publ...';_x000D_
let obj = null;_x000D_
_x000D_
try {_x000D_
obj = await (await fetch(url)).json();_x000D_
} catch(e) {_x000D_
console.log('error');_x000D_
}_x000D_
_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
A combination of both float: left;
white-space: nowrap;
worked for me.
Each of them independently didn't accomplish the desired result.
For Ubuntu-like distro with your own git compiled: you might be missing libcurl4-openssl-dev
. apt install libcurl4-openssl-dev
then reconfigure, then make install
I know this already has a marked answer, but I feel I have an improvement to it.
The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.
One thing not mentioned here, is that the words may break in the middle of a word and look messed up.
My solution, forces the break to happen between words, a nice word wrap.
.btn-responsive {
white-space: normal !important;
word-wrap: break-word;
}
<a href="#" class="btn btn-primary btn-responsive">Click Here</a>
Package graphql-type-json supports custom-scalars type JSON. Use it can show all the field of your json objects. Here is the link of the example in ApolloGraphql Server. https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#custom-scalars
I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
For anyone else trying to accomplish the same thing, here is what I came up with.
This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.
using System;
using System.Windows.Forms;
namespace Check_UnCheck_All
{
public partial class Check_UnCheck_All : Form
{
public Check_UnCheck_All()
{
InitializeComponent();
dataGridView1.RowCount = 10;
dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
}
public int chkInt = 0;
public bool chked = false;
public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk.Value) == true) chkInt++;
if (Convert.ToBoolean(chk.Value) == false) chkInt--;
if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
{
checkBox1.CheckState = CheckState.Indeterminate;
chked = true;
}
else if (chkInt == 0)
{
checkBox1.CheckState = CheckState.Unchecked;
chked = false;
}
else if (chkInt == dataGridView1.Rows.Count)
{
checkBox1.CheckState = CheckState.Checked;
chked = true;
}
}
}
public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
// End of edition on each click on column of checkbox
if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
{
dataGridView1.EndEdit();
}
dataGridView1.BeginEdit(true);
}
public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
{
if (dataGridView1.CurrentCell.IsInEditMode)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.EndEdit();
}
}
dataGridView1.BeginEdit(true);
}
}
public void checkBox1_Click(object sender, EventArgs e)
{
if (chked == true)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
chked = false;
chkInt = 0;
return;
}
if (chked == false)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView1.Rows[row.Index].SetValues(true);
}
chked = true;
chkInt = dataGridView1.Rows.Count;
}
}
}
}
Actually, the is
operator checks for identity and == operator checks for equality.
From the language reference:
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)
So from the above statement we can infer that the strings, which are immutable types, may fail when checked with "is" and may succeed when checked with "is".
The same applies for int
and tuple
which are also immutable types.
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
I took every possibilities I had in mind to do it with pure ruby code, here they are :
capitalize and gsub
'app_user'.capitalize.gsub(/_(\w)/){$1.upcase}
split and map using &
shorthand (thanks to user3869936’s answer)
'app_user'.split('_').map(&:capitalize).join
split and map (thanks to Mr. Black’s answer)
'app_user'.split('_').map{|e| e.capitalize}.join
And here is the Benchmark for all of these, we can see that gsub is quite bad for this. I used 126 080 words.
user system total real
capitalize and gsub : 0.360000 0.000000 0.360000 ( 0.357472)
split and map, with &: 0.190000 0.000000 0.190000 ( 0.189493)
split and map : 0.170000 0.000000 0.170000 ( 0.171859)
Use white-space:nowrap
and overflow:hidden
Here's another approach:
sprintf("%02x", 10).upcase
see the documentation for sprintf
here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf
for ( int i=0 ; i<=list.size() ; i++){
....}
By executing this for loop , the loop will execute with a thrown exception as IndexOutOfBoundException
cause, suppose list size is 10 , so when index i will get to 10 i.e when i=10 the exception will be thrown cause index=size
, i.e. i=size
and as known that Java considers index starting from 0,1,2...etc the expression which Java agrees upon is index < size
. So the solution for such exception is to make the statement in loop as i<list.size()
for ( int i=0 ; i<list.size() ; i++){
...}
If you want to do windows authentication, use the latest MS-JDBC driver and follow the instructions here:
https://msdn.microsoft.com/en-us/library/gg558122(v=sql.110).aspx
The haversine is definitely a good formula for probably most cases, other answers already include it so I am not going to take the space. But it is important to note that no matter what formula is used (yes not just one). Because of the huge range of accuracy possible as well as the computation time required. The choice of formula requires a bit more thought than a simple no brainer answer.
This posting from a person at nasa, is the best one I found at discussing the options
http://www.cs.nyu.edu/visual/home/proj/tiger/gisfaq.html
For example, if you are just sorting rows by distance in a 100 miles radius. The flat earth formula will be much faster than the haversine.
HalfPi = 1.5707963;
R = 3956; /* the radius gives you the measurement unit*/
a = HalfPi - latoriginrad;
b = HalfPi - latdestrad;
u = a * a + b * b;
v = - 2 * a * b * cos(longdestrad - longoriginrad);
c = sqrt(abs(u + v));
return R * c;
Notice there is just one cosine and one square root. Vs 9 of them on the Haversine formula.
SELECT CAST(DATEDIFF(dy, @DOB, GETDATE()+1)/365.25 AS int)
It is not supported but there are several options like using parameter object pattern with some syntax sugar:
public class Foo() {
private static class ParameterObject {
int param1 = 1;
String param2 = "";
}
public static void main(String[] args) {
new Foo().myMethod(new ParameterObject() {{ param1 = 10; param2 = "bar";}});
}
private void myMethod(ParameterObject po) {
}
}
In this sample we construct ParameterObject
with default values and override them in class instance initialization section { param1 = 10; param2 = "bar";}
You can use the auto_now
and auto_now_add
options for updated_at
and created_at
respectively.
class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
I recently hit the same error. Some digging brought up this: http://support.microsoft.com/kb/815645
Basically, if you have spaces in the path of the .lib, that's bad. Don't know if that's what's happening for you, but seems reasonably possible.
The fix is either 1) put the lib reference in "quotes", or 2) add the lib's path to your Library Directories (Configuration Properties >> VC++ Directories).
Based o my previous answer, here is a more elegant solution with a custom class:
First define this custom class:
import UIKit
import Foundation
class ActivityIndicatorView
{
var view: UIView!
var activityIndicator: UIActivityIndicatorView!
var title: String!
init(title: String, center: CGPoint, width: CGFloat = 200.0, height: CGFloat = 50.0)
{
self.title = title
let x = center.x - width/2.0
let y = center.y - height/2.0
self.view = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
self.view.backgroundColor = UIColor(red: 255.0/255.0, green: 204.0/255.0, blue: 51.0/255.0, alpha: 0.5)
self.view.layer.cornerRadius = 10
self.activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.activityIndicator.color = UIColor.blackColor()
self.activityIndicator.hidesWhenStopped = false
let titleLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
titleLabel.text = title
titleLabel.textColor = UIColor.blackColor()
self.view.addSubview(self.activityIndicator)
self.view.addSubview(titleLabel)
}
func getViewActivityIndicator() -> UIView
{
return self.view
}
func startAnimating()
{
self.activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
func stopAnimating()
{
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.view.removeFromSuperview()
}
//end
}
Now on your UIViewController
class:
var activityIndicatorView: ActivityIndicatorView!
override func viewDidLoad()
{
super.viewDidLoad()
self.activityIndicatorView = ActivityIndicatorView(title: "Processing...", center: self.view.center)
self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())
}
func doSomething()
{
self.activityIndicatorView.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
//do something here that will taking time
self.activityIndicatorView.stopAnimating()
}
The BitmapFactory.decode* methods, discussed in the Load Large Bitmaps Efficiently lesson, should not be executed on the main UI thread if the source data is read from disk or a network location (or really any source other than memory). The time this data takes to load is unpredictable and depends on a variety of factors (speed of reading from disk or network, size of image, power of CPU, etc.). If one of these tasks blocks the UI thread, the system flags your application as non-responsive and the user has the option of closing it (see Designing for Responsiveness for more information).
TL;DR: Use 404
See This Blog. It explains it very well.
Summary of the blog's comments on 204
:
204 No Content
is not terribly useful as a response code for a browser (although according to the HTTP spec browsers do need to understand it as a 'don't change the view' response code).204 No Content
is however, very useful for ajax web services which may want to indicate success without having to return something. (Especially in cases like DELETE
or POST
s that don't require feedback).The answer, therefore, to your question is use 404
in your case. 204
is a specialized reponse code that you shouldn't often return to a browser in response to a GET
.
The other response codes that are even less appropriate than 204
and 404
:
200
should be returned with the body of whatever you successfully fetched. Not appropriate when the entity you're fetching doesn't exist.202
is used when the server has begun work on an object but the object isn't fully ready yet. Certainly not the case here. You haven't begun, nor will you begin, construction of user 9 in response to a GET
request. That breaks all sorts of rules.400
is used in response to a poorly formatted HTTP request (for instance malformed http headers, incorrectly ordered segments, etc). This will almost certainly be handled by whatever framework you're using. You shouldn't have to deal with this unless you're writing your own server from scratch. Edit: Newer RFCs now allow for 400 to be used for semantically invalid requests.Wikipedia's description of the HTTP status codes are particularly helpful. You can also see the definitions in the HTTP/1.1 RFC2616 document at www.w3.org
On Mac OS for IntelliJ v12, shut down the IDE, and then you can execute:
rm -rf ~/Library/Preferences/IdeaIC12/*
Restart the IDE, or open a pom.xml of your choosing. You will be asked whether you want to import the preferences from an existing IntelliJ instance. Select the "No, I do not have a previous IntelliJ version" radio button.
with your own soup object:
soup.p.next_sibling.strip()
soup.p
*(this hinges on it being the first <p> in the parse tree)next_sibling
on the tag object that soup.p
returns since the desired text is nested at the same level of the parse tree as the <p> .strip()
is just a Python str method to remove leading and trailing whitespace*otherwise just find the element using your choice of filter(s)
in the interpreter this looks something like:
In [4]: soup.p
Out[4]: <p>something</p>
In [5]: type(soup.p)
Out[5]: bs4.element.Tag
In [6]: soup.p.next_sibling
Out[6]: u'\n THIS IS MY TEXT\n '
In [7]: type(soup.p.next_sibling)
Out[7]: bs4.element.NavigableString
In [8]: soup.p.next_sibling.strip()
Out[8]: u'THIS IS MY TEXT'
In [9]: type(soup.p.next_sibling.strip())
Out[9]: unicode
What's the idiomatic syntax for prepending to a short python list?
You don't usually want to repetitively prepend to a list in Python.
If it's short, and you're not doing it a lot... then ok.
list.insert
The list.insert
can be used this way.
list.insert(0, x)
But this is inefficient, because in Python, a list
is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.
Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:
for (i = n; --i >= where; )
items[i+1] = items[i];
If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque
.
deque.appendleft
A collections.deque
has many of the methods of a list. list.sort
is an exception, making deque
definitively not entirely Liskov substitutable for list
.
>>> set(dir(list)) - set(dir(deque))
{'sort'}
The deque
also has an appendleft
method (as well as popleft
). The deque
is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:
>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])
deque.extendleft
Also relevant is the deque's extendleft
method, which iteratively prepends:
>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])
Note that each element will be prepended one at a time, thus effectively reversing their order.
list
versus deque
First we setup with some iterative prepending:
import timeit
from collections import deque
def list_insert_0():
l = []
for i in range(20):
l.insert(0, i)
def list_slice_insert():
l = []
for i in range(20):
l[:0] = [i] # semantically same as list.insert(0, i)
def list_add():
l = []
for i in range(20):
l = [i] + l # caveat: new list each time
def deque_appendleft():
d = deque()
for i in range(20):
d.appendleft(i) # semantically same as list.insert(0, i)
def deque_extendleft():
d = deque()
d.extendleft(range(20)) # semantically same as deque_appendleft above
and performance:
>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931
The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft
you'll probably get the best performance that way.
Poor me ! spent a whole day behind this.Writing it down here if any body replicates this issue.
I was trying to load as Adam suggested but then got caught with AMD64 vs IA 32 exception.If in any case after working as per Adam's(no doubt the best pick) walkthrough,try to have a 64 bit version of latest jre.Make sure your JRE AND JDK are 64 bit and you have correctly added it to your classpath.
My working example goes here:unstatisfied link error
For me it only worked when I added the following code:
.change();
For me it only worked when I added the following code: As I wanted to "reset" the form, that is, select all the first options of all the selects of the form, I used the following code:
$('form').find('select').each(function(){
$(this).val($("select option:first").val());
$(this).change();
});
You could store your JSON inside of an array and then insert the JSON data into the array with push
Check this out https://jsfiddle.net/cx2rk40e/2/
$(document).ready(function(){
// using jQuery just to load function but will work without library.
$( "button" ).on( "click", go );
// Array of JSON we will append too.
var jsonTest = [{
"colour": "blue",
"link": "http1"
}]
// Appends JSON to array with push. Then displays the data in alert.
function go() {
jsonTest.push({"colour":"red", "link":"http2"});
alert(JSON.stringify(jsonTest));
}
});
Result of JSON.stringify(jsonTest)
[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]
This answer maybe useful to users who wish to emulate a similar result.
This is the simplest example I found for pagination! http://code.ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/
"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.
You do not need to use substring at all since your format
doesn't hold that info.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";
Date fechaNueva = format.parse(fechaStr);
System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29
For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true
setting in the config file:
firefox: {_x000D_
desiredCapabilities: {_x000D_
browserName: 'firefox',_x000D_
alwaysMatch: {_x000D_
// Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
acceptInsecureCerts: true,_x000D_
'moz:firefoxOptions': {_x000D_
args: [_x000D_
// '-headless',_x000D_
// '-verbose'_x000D_
],_x000D_
}_x000D_
}_x000D_
}_x000D_
},
_x000D_
By default Jsonresult "Deny get"
Suppose if we have method like below
[HttpPost]
public JsonResult amc(){}
By default it "Deny Get".
In the below method
public JsonResult amc(){}
When you need to allowget or use get ,we have to use JsonRequestBehavior.AllowGet.
public JsonResult amc()
{
return Json(new Modle.JsonResponseData { Status = flag, Message = msg, Html = html }, JsonRequestBehavior.AllowGet);
}
From enable-cors.org:
CORS on ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Well, I believe that I've solved the password configuration 'issue' - WampServer 2.2 - Windows 7.
The three steps that I did:
In the MySQL console set a new password. To make that: mysqladmin -u root password 'your_password'
In phpMyAdmin
click in users and set the same password to the user root
.
Finally, set your new password in the config.inc.php
. Don't change anything else in this file.
This worked for me. Good luck!
Daniel
I think this may have been a conscious design choice to force developers to create functions whose names clearly communicate their intentions. In C++ developers would overload operators with functionality that would often have no relation to the commonly accepted nature of the given operator, making it nearly impossible to determine what a piece of code does without looking at the definition of the operator.
public void Linq95()
{
List<Customer> customers = GetCustomerList();
List<Product> products = GetProductList();
var customerNames =
from c in customers
select c.CompanyName;
var productNames =
from p in products
select p.ProductName;
var allNames = customerNames.Concat(productNames);
Console.WriteLine("Customer and product names:");
foreach (var n in allNames)
{
Console.WriteLine(n);
}
}
I would use something like this.
public class MyViewModel
{
public MyDataTable Data { get; set; }
public MyViewModel()
{
loadData(() => GetData());
}
private async void loadData(Func<DataTable> load)
{
try
{
MyDataTable = await Task.Run(load);
}
catch (Exception ex)
{
//log
}
}
private DataTable GetData()
{
DataTable data;
// get data and return
return data;
}
}
This is as close to I can get for constructors.
You can bootstrap multiple angular applications, but:
1) You need to manually bootstrap them
2) You should not use "document" as the root, but the node where the angular interface is contained to:
var todoRootNode = jQuery('[ng-controller=TodoController]');
angular.bootstrap(todoRootNode, ['TodoApp']);
This would be safe.
There are two different discussions here: One is how many people can connect to your server. This one has been answered adequately by others, so I won't go into that.
Other is how many ports yours server can listen on? I believe this is where the 64K number came from. Actually, TCP protocol uses a 16-bit identifier for a port, which translates to 65536 (a bit more than 64K). This means that you can have that many different "listeners" on the server per IP Address.
If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.
In Bundle ID Suffix you should write full name of bundle ID.
Example:
Bundle ID suffix = thebestapp (NOT CORRECT!!!!)
Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)
The reason for this is explained in the Developer Portal:
The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g.
ABCDE12345
), and an App ID Suffix (a Bundle ID search string, e.g.com.mycompany.appname
). [emphasis added]
So in this case the suffix is the full string com.awesomeapps.thebestapp
.
To solve this, I opened httpd.conf
and changed the following line:
Allow from 127.0.0.1
to:
Allow from 127.0.0.1 ::1
Delete the .lock file from the C:\mongodb\data\ path and then restart the mongodb service.
npm i html-react-parser;
import Parser from 'html-react-parser';
<td>{Parser(this.state.archyves)}</td>
From Wikipedia:
I love how this is explained in the article Cool performance features of EclipseLink 2.5
Indexing Foreign Keys
The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.