In addition to the accepted answer, one other check is to make sure that you have the right reference to your entity package in sessionFactory.setPackagesToScan(...) while setting up your session factory.
Try this. It works for me:
mkdir <repos>/tags/Release1.0
svn commit <repos>/tags/Release1.0
svn copy <repos>/trunk/* <repos>/tag/Release1.0
svn commit <repos/tags/Release1.0 -m "Tagging Release1.0"
Got a solution to above problem in a different way where in although i would read entire csv file, but would tweek the display part to show only the content which is desired.
import pandas as pd
df = pd.read_csv('data.csv', skipinitialspace=True)
print df[['star_name', 'ra']]
This one could help in some of the scenario's in learning basics and filtering data on the basis of columns in dataframe.
I don't think jQuery itself includes datetimepicker. You must use jQuery UI instead (src="jquery.ui").
Use the .classList.add()
method:
const element = document.querySelector('div.foo');_x000D_
element.classList.add('bar');_x000D_
console.log(element.className);
_x000D_
<div class="foo"></div>
_x000D_
This method is better than overwriting the className
property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList
(see the MDN documentation).
A type independent variation (UPDATED - thanks to Volley for instantiating T):
@SuppressWarnings("unchecked")
public static <T> T[] join(T[]...arrays) {
final List<T> output = new ArrayList<T>();
for(T[] array : arrays) {
output.addAll(Arrays.asList(array));
}
return output.toArray((T[])Array.newInstance(
arrays[0].getClass().getComponentType(), output.size()));
}
var percent = Math.floor(100 * number1 / number2 - 100) + ' %';
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
You can do it with rgba color code
using CSS like this example given below.
.imgbox img{_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.overlay{_x000D_
background: rgba(74, 19, 61, 0.4);_x000D_
color: #FFF;_x000D_
text-shadow: 0px 2px 5px #000079;_x000D_
height: 100px;_x000D_
width: 300px;_x000D_
position: absolute;_x000D_
top: 10%;_x000D_
left: 25%;_x000D_
padding: 25px;_x000D_
}
_x000D_
<div class"imgbox">_x000D_
<img src="http://www.bhmpics.com/wallpapers/little_pony_art-800x480.jpg">_x000D_
<div class="overlay">_x000D_
<p>This is Simple Text.</p>_x000D_
</div>_x000D_
</div>
_x000D_
As per OpenCV docs(1), below steps using OpenCV manager is the recommended way to use OpenCV for production runs. But, OpenCV manager(2) is an additional install from Google play store. So, if you prefer a self contained apk(not using OpenCV manager) or is currently in development/testing phase, I suggest answer at https://stackoverflow.com/a/27421494/1180117.
Recommended steps for using OpenCV in Android Studio with OpenCV manager.
File -> Import Module
, choose sdk/java
folder in the unzipped opencv archive. build.gradle
under imported OpenCV module to update 4 fields to match your project's build.gradle
a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and 4) targetSdkVersion. Application -> Module Settings
, and select the Dependencies
tab. Click +
icon at bottom(or right), choose Module Dependency
and select the imported OpenCV module.As the final step, in your Activity class, add snippet below.
public class SampleJava extends Activity {
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch(status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG,"OpenCV Manager Connected");
//from now onwards, you can use OpenCV API
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
break;
case LoaderCallbackInterface.INIT_FAILED:
Log.i(TAG,"Init Failed");
break;
case LoaderCallbackInterface.INSTALL_CANCELED:
Log.i(TAG,"Install Cancelled");
break;
case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
Log.i(TAG,"Incompatible Version");
break;
case LoaderCallbackInterface.MARKET_ERROR:
Log.i(TAG,"Market Error");
break;
default:
Log.i(TAG,"OpenCV Manager Install");
super.onManagerConnected(status);
break;
}
}
};
@Override
protected void onResume() {
super.onResume();
//initialize OpenCV manager
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
}
}
Note: You could only make OpenCV calls after you receive success callback on onManagerConnected
method. During run, you will be prompted for installation of OpenCV manager from play store, if it is not already installed. During development, if you don't have access to play store or is on emualtor, use appropriate OpenCV manager apk present in apk
folder under downloaded OpenCV sdk archive .
Pros
Cons
All the calls to UI should be asynchronous, anything you change on the UI like updating table or changing text label should be done from main thread. using DispatchQueue.main will add your operation to the queue on the main thread.
Swift 4
DispatchQueue.main.async{
self.tableView.reloadData()
}
A combination of both float: left;
white-space: nowrap;
worked for me.
Each of them independently didn't accomplish the desired result.
Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes
or AxesSubplot
object. The functions of interest are set_autoscale_on
, set_autoscalex_on
, and set_autoscaley_on
.
In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on
property to False
. Here is a modified version of the FFT subplot snippet from your code:
fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))
You can also set custom padding as defaults in your $HOME/.matplotlib/matplotlib_rc
as follows. In the example below I have modified both the bottom and left out-of-the-box padding:
# The figure subplot parameters. All dimensions are a fraction of the
# figure width or height
figure.subplot.left : 0.1 #left side of the subplots of the figure
#figure.subplot.right : 0.9
figure.subplot.bottom : 0.15
...
One way to do this, first one an array, 2nd an object:
<select name="">
<option value='{"num_sequence":[0,1,2,3]}'>Option one</option>
<option value='{"foo":"bar","one":"two"}'>Option two</option>
</select>
Edited (3 years after answering) to put both values into JSON format (using JSON.stringify()
) because of a complaint that my proof-of-concept answer "could confuse a newbie developer."
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
Usually someone uses collections if something frequently changes.
E.g.
List<String> someList = new ArrayList<String>();
// initialize list
someList.add("Mango");
someList.add("....");
// remove all elements
someList.clear();
// empty list
An ArrayList
for example uses a backing Array
. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.
Create the classLoader instance of the class you need, then you can access the files or resources easily.
now you access path using getPath()
method of that class.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
With Scanner the default delimiters are the whitespace characters.
But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:
So useDelimiter()
methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:
And here is an Example:
public static void main(String[] args) {
// Initialize Scanner object
Scanner scan = new Scanner("Anna Mills/Female/18");
// initialize the string delimiter
scan.useDelimiter("/");
// Printing the tokenized Strings
while(scan.hasNext()){
System.out.println(scan.next());
}
// closing the scanner stream
scan.close();
}
Prints this output:
Anna Mills
Female
18
I recently ran into similar issues, and this is what worked for me.
If the variable is numeric, then a simple df$Var[df$Var == ""] <- NA
should suffice. But if the variable is a factor, then you need to convert it to the character first, then replace ""
cells with the value you want, and convert it back to factor. So case in point, your Sex
variable, I assume it would be a factor and if you want to replace the empty cell, I would do the following:
df$Var <- as.character(df$Var)
df$Var[df$Var==""] <- NA
df$Var <- as.factor(df$Var)
Using plain javascript
<html>
<head>
<!-- define on/off styles -->
<style type="text/css">
.on { background:blue; }
.off { background:red; }
</style>
<!-- define the toggle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
} else {
item.className="on";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />
</body>
</html>
Using jQuery
If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:
$(document).ready(function(){
$('a#myButton').click(function(){
$(this).toggleClass("btnClicked");
});
});
Using jQuery UI effects, you can animate transitions: http://jqueryui.com/demos/toggleClass/
// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);
if(sdDir.exists())
deleteRecursive(sdDir);
// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
In order to use import { readFileSync } from 'fs'
, you have to:
--experimental-modules
flag (in Node.js 10), e.g. node --experimental-modules server.mjs
(see #3 for explanation of .mjs)import
statements, to .mjs
, .js will not work, e.g. server.mjsThe other answers hit on 1 and 2, but 3 is also necessary. Also, note that this feature is considered extremely experimental at this point (1/10 stability) and not recommended for production, but I will still probably use it.
Here's the Node.js 10 ESM documentation.
If you're interested in the pure string:
[myUrl absoluteString];
If you're interested in the path represented by the URL (and to be used with NSFileManager
methods for example):
[myUrl path];
Just Press Alt + Command + Enter to open the Assistant editor. Assistant Editor will open up the Timeline view. Timeline by default shows your console output.
Additionally You can add any line to Timeline view by pressing the small circle next to the eye icon in the results area. This will enable history for this expression. So you can see the output of the variable over last 30 secs (you can change this as well) of execution.
Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip
to text
.
Create proper gradient:
background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);
Then clip the backgroud with text:
background-clip: text;
color: transparent;
https://jsfiddle.net/simonmysun/2h61Ljbn/4/
Tested under Chrome 75 under Windows 10.
This will not work on a local host, but uploaded on a server, this code should do the trick. Just make sure to enter your own email address for the $to line.
<?php
if (isset($_POST['name']) && isset($_POST['email'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$to = '[email protected]';
$subject = "New Message on YourWebsite.com";
$body = '<html>
<body>
<h2>Title</h2>
<br>
<p>Name:<br>'.$name.'</p>
<p>Email:<br>'.$email.'</p>
</body>
</html>';
//headers
$headers = "From: ".$name." <".$email.">\r\n";
$headers = "Reply-To: ".$email."\r\n";
$headers = "MIME-Version: 1.0\r\n";
$headers = "Content-type: text/html; charset=utf-8";
//send
$send = mail($to, $subject, $body, $headers);
if ($send) {
echo '<br>';
echo "Success. Thanks for Your Message.";
} else {
echo 'Error.';
}
}
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form action="" method="post">
<input type="text" name="name" placeholder="Your Name"><br>
<input type="text" name="email" placeholder="Your Email"><br>
<button type="submit">Subscribe</button>
</form>
</body>
</html>
A char
represents a character in Java (*). It is 2 bytes large (at least that's what the valid value range suggests).
That doesn't necessarily mean that every representation of a character is 2 bytes long. In fact many encodings only reserve 1 byte for every character (or use 1 byte for the most common characters).
When you call the String(byte[])
constructor you ask Java to convert the byte[]
to a String
using the platform default encoding. Since the platform default encoding is usually a 1-byte encoding such as ISO-8859-1 or a variable-length encoding such as UTF-8, it can easily convert that 1 byte to a single character.
If you run that code on a platform that uses UTF-16 (or UTF-32 or UCS-2 or UCS-4 or ...) as the platform default encoding, then you will not get a valid result (you'll get a String
containing the Unicode Replacement Character instead).
That's one of the reasons why you should not depend on the platform default encoding: when converting between byte[]
and char[]
/String
or between InputStream
and Reader
or between OutputStream
and Writer
, you should always specify which encoding you want to use. If you don't, then your code will be platform-dependent.
(*) that's not entirely true: a char
represents a UTF-16 codepoint. Either one or two UTF-16 codepoints represent a Unicode codepoint. A Unicode codepoint usually represents a character, but sometimes multiple Unicode codepoints are used to make up a single character. But the approximation above is close enough to discuss the topic at hand.
If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.
You can solve this by adding the following statement to the NAMESPACE:
exportPattern("^[^\\\\.]")
This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:
.myHiddenFunction <- function(x) cat("my hidden function")
Have you installed it?
On debian/ubuntu:
aptitude install python-numpy
On windows:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems:
http://sourceforge.net/projects/numpy/files/NumPy/
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
@KyleMit answer is one way to solve this, however we may chose to avoid the undivided input fields acheived by input-group
class. A better way to do this is by using form-group
and row
classes on a parent div
and use input
elements with grid-system classes provided by bootstrap.
<div class="form-group row">
<input class="form-control col-md-6" type="text">
<input class="form-control col-md-6" type="text">
</div>
You can use Environment.Exit(0);
and Application.Exit
Environment.Exit(0)
is cleaner.
This one works best to reset the form.
import React, { Component } from 'react'
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state ///>>>>>>>>> note this one.
}
resetForm = () => {
this.setState(this.baseState) ///>>>>>>>>> note this one.
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val })
render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}
Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.
If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:
Original answer:
Here is a not-so-great "ng-if" directive:
myApp.directive('ngIf', function() {
return {
link: function(scope, element, attrs) {
if(scope.$eval(attrs.ngIf)) {
// remove '<div ng-if...></div>'
element.replaceWith(element.children())
} else {
element.replaceWith(' ')
}
}
}
});
that allows for this HTML syntax:
<div ng-repeat="message in data.messages" ng-class="message.type">
<hr>
<div ng-if="showFrom(message)">
<div>From: {{message.from.name}}</div>
</div>
<div ng-if="showCreatedBy(message)">
<div>Created by: {{message.createdBy.name}}</div>
</div>
<div ng-if="showTo(message)">
<div>To: {{message.to.name}}</div>
</div>
</div>
replaceWith() is used to remove unneeded content from the DOM.
Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?
The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.
E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from
, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.
When using any form of Ajax, detailed documentation for the format of responses received from the CGI server seems to be lacking on the Web. Some entries here point out that newlines in returned text or json data must be escaped to prevent infinite loops (hangs) in JSON conversion (possibly created by throwing an uncaught exception), whether done automatically by jQuery or manually using Javascript system or library JSON parsing calls.
In each case where programmers post this problem, inadequate solutions are presented (most often replacing \n by \\n on the sending side) and the matter is dropped. Their inadequacy is revealed when passing string values that accidentally embed control escape sequences, such as Windows pathnames. An example is "C:\Chris\Roberts.php", which contains the control characters ^c and ^r, which can cause JSON conversion of the string {"file":"C:\Chris\Roberts.php"} to loop forever. One way of generating such values is deliberately to attempt to pass PHP warning and error messages from server to client, a reasonable idea.
By definition, Ajax uses HTTP connections behind the scenes. Such connections pass data using GET and POST, both of which require encoding sent data to avoid incorrect syntax, including control characters.
This gives enough of a hint to construct what seems to be a solution (it needs more testing): to use rawurlencode on the PHP (sending) side to encode the data, and unescape on the Javascript (receiving) side to decode the data. In some cases, you will apply these to entire text strings, in other cases you will apply them only to values inside JSON.
If this idea turns out to be correct, simple examples can be constructed to help programmers at all levels solve this problem once and for all.
Had same issue when I had to develop a fixed length field format.
Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set
< record_delimiter value="\n"/ >
but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.
Did following change and it just worked.
< record_delimiter value="\n"/> => < record_delimiter value="
"/ >
After unmarshaling Java interprets as new line character.
you can always cast any object to any type by up-casting it to Object first. in your case:
(List<Customer>)(Object)list;
you must be sure that at runtime the list contains nothing but Customer objects.
Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.
function getPercentUsed() {
$sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
return $val[0];
}
Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
padding: 2em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.double-border:before {_x000D_
background: none;_x000D_
border: 4px solid #fff;_x000D_
content: "";_x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 4px;_x000D_
left: 4px;_x000D_
right: 4px;_x000D_
bottom: 4px;_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
If you want borders that are consecutive to each other (no space between them), you can use multiple box-shadow
declarations (separated by commas) to do so:
body {_x000D_
background-image: linear-gradient(180deg, #ccc 50%, #fff 50%);_x000D_
background-repeat: no-repeat;_x000D_
height: 100vh;_x000D_
}_x000D_
.double-border {_x000D_
background-color: #ccc;_x000D_
border: 4px solid #fff;_x000D_
box-shadow:_x000D_
inset 0 0 0 4px #eee,_x000D_
inset 0 0 0 8px #ddd,_x000D_
inset 0 0 0 12px #ccc,_x000D_
inset 0 0 0 16px #bbb,_x000D_
inset 0 0 0 20px #aaa,_x000D_
inset 0 0 0 20px #999,_x000D_
inset 0 0 0 20px #888;_x000D_
/* And so on and so forth, if you want border-ception */_x000D_
margin: 0 auto;_x000D_
padding: 3em;_x000D_
width: 16em;_x000D_
height: 16em;_x000D_
position: relative;_x000D_
}
_x000D_
<div class="double-border">_x000D_
<!-- Content -->_x000D_
</div>
_x000D_
Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.
Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.
Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)
Good luck.
There are various way to concatenate strings in kotlin Example -
a = "Hello" , b= "World"
Using + operator
a+b
Using plus()
operator
a.plus(b)
Note - + is internally converted to .plus() method only
In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder
StringBuilder str = StringBuilder("Hello").append("World")
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
The chart control in the WPF Toolkit has a horrible bug: it never forgets any of the data points. So if you try to implement a floating chart you will get out of memory after round about 3000 DataPoint-objects. This bug has been reported to MS over a year ago but nobody seems to care...
Information on this topic is now available on Wikipedia at: Search data structure
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
In python, A dynamic array is an 'array' from the array module. E.g.
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).
The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.
But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.
I had this problem. I somehow registered the device for generic team on apple. I don't remember how I did it now. Then I was able to overcome this error.
It is a bit old, this post. But this is my code to show/hide the columns. I use the built in function to display the columns and just mark them.
Function that displays columns shown/hidden columns. The #jqGrid is the name of my grid, and the columnChooser is the jqGrid column chooser.
function showHideColumns() {
$('#jqGrid').jqGrid('columnChooser', {
width: 250,
dialog_opts: {
modal: true,
minWidth: 250,
height: 300,
show: 'blind',
hide: 'explode',
dividerLocation: 0.5
} });
Two things I noticed (they may be mistakes from when you wrote it down though).
$('.navlink').click
)return $(this).data("selected")==true
)This worked for me in Android Studio as well as VS Code. I only had to run these lines in my terminal/command prompt and problem was solved. There was no need to restart any of the IDEs again
Optionally you also run.
I know it's a bit old question but still people try to find efficient solution so instead you should use FULLTEXT index (it's available from MySQL 5.6.4).
Query on table with +35mil records by triple like
in where block took ~2.5s but after adding index on these fields and using BOOLEAN MODE inside match ... against ...
it took only 0.05s.
$('html, body').animate({scrollTop:1200},'50');
You can do this!
"UNION also sort the final output" - only as an implementation artifact. It is by no means guaranteed to perform the sort, and if you need a particular sort order, you should specify it with an ORDER BY
clause. Otherwise, the output order is whatever is most convenient for the server to provide.
As such, your request for a function that performs a UNION ALL
but that removes duplicates is easy - it's called UNION
.
From your clarification, you also appear to believe that a UNION ALL
will return all of the results from the first query before the results of the subsequent queries. This is also not guaranteed. Again, the only way to achieve a particular order is to specify it using an ORDER BY
clause.
One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.
Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:
p [tab][enter] Hello world!
When you type p [tab] Emmet expands it to:
<p></p>
Pressing [enter] then further expands it to:
<p>
</p>
With the cursor indented and on the line between the tags. Meaning that typing text results in:
<p>
Hello, world!
</p>
Simply restarting Visual Studio worked for me.
I just want to add some more information to what @Robert Paulson answered.
Let's assume that node contains key & data. So nodes with the same key might contain different data.
(So the search must find all nodes with the same key)
- left <= cur < right
- left < cur <= right
- left <= cur <= right
- left < cur < right && cur contain sibling nodes with the same key.
- left < cur < right, such that no duplicate keys exist.
1 & 2. works fine if the tree does not have any rotation-related functions to prevent skewness.
But this form doesn't work with AVL tree or Red-Black tree, because rotation will break the principal.
And even if search() finds the node with the key, it must traverse down to the leaf node for the nodes with duplicate key.
Making time complexity for search = theta(logN)
3. will work well with any form of BST with rotation-related functions.
But the search will take O(n), ruining the purpose of using BST.
Say we have the tree as below, with 3) principal.
12
/ \
10 20
/ \ /
9 11 12
/ \
10 12
If we do search(12) on this tree, even tho we found 12 at the root, we must keep search both left & right child to seek for the duplicate key.
This takes O(n) time as I've told.
4. is my personal favorite. Let's say sibling means the node with the same key.
We can change above tree into below.
12 - 12 - 12
/ \
10 - 10 20
/ \
9 11
Now any search will take O(logN) because we don't have to traverse children for the duplicate key.
And this principal also works well with AVL or RB tree.
Optimistic assumes that nothing's going to change while you're reading it.
Pessimistic assumes that something will and so locks it.
If it's not essential that the data is perfectly read use optimistic. You might get the odd 'dirty' read - but it's far less likely to result in deadlocks and the like.
Most web applications are fine with dirty reads - on the rare occasion the data doesn't exactly tally the next reload does.
For exact data operations (like in many financial transactions) use pessimistic. It's essential that the data is accurately read, with no un-shown changes - the extra locking overhead is worth it.
Oh, and Microsoft SQL server defaults to page locking - basically the row you're reading and a few either side. Row locking is more accurate but much slower. It's often worth setting your transactions to read-committed or no-lock to avoid deadlocks while reading.
Seamus Campbell's answer doesnot work on python2.x.
list1 = sorted(list1, key=lambda e: int(e))
using lambda
function works well.
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
You can use index of columns:
data_set[,1:9] <- sapply(dataset[,1:9],as.character)
ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.
$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));
The ng-if
directive removes the content from the page and ng-show/ng-hide
uses the CSS display
property to hide content.
This is useful in case you want to use :first-child
and :last-child
pseudo selectors to style.
TLDR: One liner
// This assumes your constructor method will assign properties from the arg.
.map((instanceData: MyClass) => new MyClass(instanceData));
The Detailed Answer
I would not recommend the Object.assign approach, as it can inappropriately litter your class instance with irrelevant properties (as well as defined closures) that were not declared within the class itself.
In the class you are trying to deserialize into, I would ensure any properties you want deserialized are defined (null, empty array, etc). By defining your properties with initial values you expose their visibility when trying to iterate class members to assign values to (see deserialize method below).
export class Person {
public name: string = null;
public favoriteSites: string[] = [];
private age: number = null;
private id: number = null;
private active: boolean;
constructor(instanceData?: Person) {
if (instanceData) {
this.deserialize(instanceData);
}
}
private deserialize(instanceData: Person) {
// Note this.active will not be listed in keys since it's declared, but not defined
const keys = Object.keys(this);
for (const key of keys) {
if (instanceData.hasOwnProperty(key)) {
this[key] = instanceData[key];
}
}
}
}
In the example above, I simply created a deserialize method. In a real world example, I would have it centralized in a reusable base class or service method.
Here is how to utilize this in something like an http resp...
this.http.get(ENDPOINT_URL)
.map(res => res.json())
.map((resp: Person) => new Person(resp) ) );
If tslint/ide complains about argument type being incompatible, just cast the argument into the same type using angular brackets <YourClassName>
, example:
const person = new Person(<Person> { name: 'John', age: 35, id: 1 });
If you have class members that are of a specific type (aka: instance of another class), then you can have them casted into typed instances through getter/setter methods.
export class Person {
private _acct: UserAcct = null;
private _tasks: Task[] = [];
// ctor & deserialize methods...
public get acct(): UserAcct {
return this.acct;
}
public set acct(acctData: UserAcct) {
this._acct = new UserAcct(acctData);
}
public get tasks(): Task[] {
return this._tasks;
}
public set tasks(taskData: Task[]) {
this._tasks = taskData.map(task => new Task(task));
}
}
The above example will deserialize both acct and the list of tasks into their respective class instances.
It would be the highest available priority setting, and would usually only be used on box that was dedicated to running that specific program. It's actually high enough that it could cause starvation of the keyboard and mouse threads to the extent that they become unresponsive.
So basicly, if you have to ask, don't use it :)
If you only want to suppress a warning in a single line of code, you can use the suppress
warning specifier:
#pragma warning(suppress: 4101)
// here goes your single line of code where the warning occurs
For a single line of code, this works the same as writing the following:
#pragma warning(push)
#pragma warning(disable: 4101)
// here goes your code where the warning occurs
#pragma warning(pop)
You may also return to the previous state of the local repo in another way:
git add
. git reset --hard
.void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
I wasn't happy with any of these approaches, so I came up with a Flexlist
class that allows for flexible indexing, either by integer, slice or index-list:
class Flexlist(list):
def __getitem__(self, keys):
if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
return [self[k] for k in keys]
Which, for your example, you would use as:
L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]
print(T) # ['a', 'd', 'h']
Checking the documentation shows that its returns false
on an error. So use the return status rather than or die()
. It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
add_shortcode( 'seriesposts', 'series_posts' );
function series_posts( $atts )
{ ob_start();
$myseriesoption = get_option( '_myseries', null );
$type = $myseriesoption;
$args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 5, 'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
endwhile;
echo '</ul>';
}
wp_reset_query();
return ob_get_clean(); }
//this will generate a shortcode function to be used on your site [seriesposts]
U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake
file, which will help you with generating Makefile
.
The content inside strings in Golang can be compared using ==
operator. If the results are not as expected there may be some hidden characters like \n
, \r
, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings
package in golang.
For Instance, spaces can be removed using strings.TrimSpace
function. You can also define a custom function to remove any character you need. strings.TrimFunc
function can give you more power.
You can use getElementsByTagName function, it returns a HTMLCollection of elements with the given tag name.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
alert('empty');
//Do something here
}
}
You can also use document.myform.getElementsByTagName
provided you have given a name to yoy form
.toggleClass()
will not animate, you should go for slideToggle()
or .animate()
method.
Or you could use:
exec bash
This does the same thing, and is easier to remember (at least for me).
The exec
command completely replaces the shell process by running the specified command-line. In our example, it replaces whatever the current shell is with a fresh instance of bash
(with the updated configuration files).
//for closeing the popover when user click outside it will close all popover
var hidePopover = function(element) {
var elementScope = angular.element($(element).siblings('.popover')).scope().$parent;
elementScope.isOpen = false;
elementScope.$apply();
//Remove the popover element from the DOM
$(element).siblings('.popover').remove();
};
$(document).ready(function(){
$('body').on('click', function (e) {
$("a").each(function () {
//Only do this for all popovers other than the current one that cause this event
if (!($(this).is(e.target) || $(this).has(e.target).length > 0)
&& $(this).siblings('.popover').length !== 0 && $(this).siblings('.popover').has(e.target).length === 0)
{
hidePopover(this);
}
});
});
});
ES6: In HTML, include the main JavaScript file using attribute type="module"
(browser support):
<script type="module" src="script.js"></script>
And in the script.js
file, include another file like this:
import { hello } from './module.js';
...
// alert(hello());
Inside the included file (module.js
), you must export the function/class that you will import:
export function hello() {
return "Hello World";
}
A working example is here. More information is here.
You need to make TestGetMethod async
too and attach await in front of GetIdList();
will unwrap the task to List<int>
, So if your helper function is returning Task make sure you have await as you are calling the function async
too.
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Another option
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
If you have a menu then changing ShortcutKeys
property of the ToolStripMenuItem
should do the trick.
If not, you could create one and set its visible
property to false.
Tested only on Firefox:
<script>
window.onload = window.onresize = function() {
var C = 0.8; // canvas width to viewport width ratio
var W_TO_H = 2/1; // canvas width to canvas height ratio
var el = document.getElementById("a");
// For IE compatibility http://www.google.com/search?q=get+viewport+size+js
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * C;
var canvasHeight = canvasWidth / W_TO_H;
el.style.position = "fixed";
el.setAttribute("width", canvasWidth);
el.setAttribute("height", canvasHeight);
el.style.top = (viewportHeight - canvasHeight) / 2;
el.style.left = (viewportWidth - canvasWidth) / 2;
window.ctx = el.getContext("2d");
ctx.clearRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = 'yellow';
ctx.moveTo(0, canvasHeight/2);
ctx.lineTo(canvasWidth/2, 0);
ctx.lineTo(canvasWidth, canvasHeight/2);
ctx.lineTo(canvasWidth/2, canvasHeight);
ctx.lineTo(0, canvasHeight/2);
ctx.fill()
}
</script>
<body>
<canvas id="a" style="background: black">
</canvas>
</body>
I like the Java enum, that's how I do it in Python:
def enum(clsdef):
class Enum(object):
__slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')])
def __new__(cls, *args, **kwargs):
if not '_the_instance' in cls.__dict__:
cls._the_instance = object.__new__(cls, *args, **kwargs)
return cls._the_instance
def __init__(self):
clsdef.values=lambda cls, e=Enum: e.values()
clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)
for ordinal, key in enumerate(self.__class__.__slots__):
args=getattr(clsdef, key)
instance=clsdef(*args)
instance._name=key
instance._ordinal=ordinal
setattr(self, key, instance)
@classmethod
def values(cls):
if not hasattr(cls, '_values'):
cls._values=[getattr(cls, name) for name in cls.__slots__]
return cls._values
def valueOf(self, name):
return getattr(self, name)
def __repr__(self):
return ''.join(['<class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '>'])
return Enum()
Sample use:
i=2
@enum
class Test(object):
A=("a",1)
B=("b",)
C=("c",2)
D=tuple()
E=("e",3)
while True:
try:
F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]
break;
except ValueError:
i+=1
def __init__(self, name="default", aparam=0):
self.name=name
self.avalue=aparam
All class variables are defined as a tuple, just like the constructor. So far, you can't use named arguments.
The <select>
element is generated by the application and styling is not part of the CSS/HTML spec.
You would have to fake it with your own DIV and overlay it on top of the existing one, or build your own control emulating the same functionality.
place your "a href" tag without any styling before div / span of text. then make your styling in the div/span tag.
for the most restricted styling email client.
<div><a href=""><span style="text-decoration:none">title</span><a/></div>
I am also using Ubuntu
based system (Mint mate 18), got the similar issue when clone large repo from github.
The simple solution worked for me is to use ssh protocol instead of http(s) protocol.
e.g
git clone [email protected]:xxx/yyy.git
If anybody is looking for Kotlin answer you just need this line.
Fragment
startActivity(Intent.makeRestartActivityTask(activity?.intent?.component))
Activity
startActivity(Intent.makeRestartActivityTask(this.intent?.component))
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
I think it's a better way to bind on the service itself instead of the attributes on it.
Here's why:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">
<div ng-controller="BindToServiceCtrl as ctrl">
ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
<br />
ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
<br />
<br />
<!-- This is empty since $scope.arrOne never changes -->
arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
<br />
<!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
<!-- Both of them point the memory space modified by the `push` function below -->
arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
</div>
<script type="text/javascript">
var app = angular.module("BindToService", []);
app.controller("BindToServiceCtrl", function ($scope, ArrService) {
$scope.ArrService = ArrService;
$scope.arrOne = ArrService.arrOne;
$scope.arrTwo = ArrService.arrTwo;
});
app.service("ArrService", function ($interval) {
var that = this,
i = 0;
this.arrOne = [];
that.arrTwo = [];
$interval(function () {
// This will change arrOne (the pointer).
// However, $scope.arrOne is still same as the original arrOne.
that.arrOne = that.arrOne.concat([i]);
// This line changes the memory block pointed by arrTwo.
// And arrTwo (the pointer) itself never changes.
that.arrTwo.push(i);
i += 1;
}, 1000);
});
</script>
</body>
You can play it on this plunker.
Use the print function (Python 3.x) or import it (Python 2.6+):
from __future__ import print_function
print(*sys.path, sep='\n')
These const mean that compiler will Error if the method 'with const' changes internal data.
class A
{
public:
A():member_()
{
}
int hashGetter() const
{
state_ = 1;
return member_;
}
int goodGetter() const
{
return member_;
}
int getter() const
{
//member_ = 2; // error
return member_;
}
int badGetter()
{
return member_;
}
private:
mutable int state_;
int member_;
};
The test
int main()
{
const A a1;
a1.badGetter(); // doesn't work
a1.goodGetter(); // works
a1.hashGetter(); // works
A a2;
a2.badGetter(); // works
a2.goodGetter(); // works
a2.hashGetter(); // works
}
Read this for more information
It is up to the browser but they behave in similar ways.
I have tested FF, IE7, Opera and Chrome.
F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".
CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.
If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.
Edit: Updated table
The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.
Updated table, 27 September 2010
+------------------------------------------------------------+
¦ UPDATED ¦ Firefox 3.x ¦
¦27 SEP 2010 ¦ +--------------------------------------------¦
¦ ¦ ¦ MSIE 8, 7 ¦
¦ Version 3 ¦ ¦ +-----------------------------------------¦
¦ ¦ ¦ ¦ Chrome 6.0 ¦
¦ ¦ ¦ ¦ +--------------------------------------¦
¦ ¦ ¦ ¦ ¦ Chrome 1.0 ¦
¦ ¦ ¦ ¦ ¦ +-----------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ Opera 10, 9 ¦
¦ ¦ ¦ ¦ ¦ ¦ +--------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
+------------+--+--+--+--+--+--------------------------------¦
¦ F5¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend: ¦
¦ CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since" ¦
¦ ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache" ¦
¦ ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache" ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦ CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦ ¦
+------------+--+--+--+--+--¦ ¦
¦ Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers ¦
¦ Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon. ¦
¦ Alt-Click¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦ ¦
+------------------------------------------------------------+
Versions tested:
Notes:
Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".
Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.
Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.
Ran into this issue with Parallels and VS 2013. Command + Insert also fixed it in my setup, in addition to the accepted answer. On my Windows USB keyboard Command == WindowsKey.
"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."
That inspired me to try using two spaces instead of just one - and it worked!!
(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)
You can find out the option for changing browser in Window menu
.
See image at below.
This image can be easy to understand.
As most answers seem to be pretty old here, referencing menu items I can't seem to find in the current versions of popular browsers, here's how to do it in the current version in Firefox Developer Edition:
CTRL + SHIFT + I
)There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:
A simple answer would be (26 characters):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
How this works is you convert the number to base 36, so you have the following characters:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
Not entirely sure about how fast running the two different examples client-side would compare though.
After going through all the answers I thought i will add two simple options
If you already accessed the record using FirstOrDefault() with tracking enabled (without using .AsNoTracking() function as it will disable tracking) and updated some fields then you can simply call context.SaveChanges()
In other case either you have entity posted to server using HtppPost or you disabled tracking for some reason then you should call context.Update(entityName) before context.SaveChanges()
1st option will only update the fields you changed but 2nd option will update all the fields in the database even though none of the field values were actually updated :)
Try to use flexbox model. It is easy and short to write.
Live Jsfiddle
CSS:
#wrapper {
display: flex;
border: 1px solid black;
}
#first {
border: 1px solid red;
}
#second {
border: 1px solid green;
}
default direction is row. So, it aligns next to each other inside the #wrapper. But it is not supported IE9 or less than that versions
Note: startDate and endDates are -> java.util.Date
import org.joda.time.Duration;
import org.joda.time.Interval;
// Use .getTime() unless it is a joda DateTime object
Interval interval = new Interval(startDate.getTime(), endDate.getTime());
Duration period = interval.toDuration();
//gives the number of days elapsed between start
period.getStandardDays();
and end date
Similar to days, you can also get hours, minutes and seconds
period.getStandardHours();
period.getStandardMinutes();
period.getStandardSeconds();
Before you do anything further, seek to understand the difference between encryption and authentication, and why you probably want authenticated encryption rather than just encryption.
To implement authenticated encryption, you want to Encrypt then MAC. The order of encryption and authentication is very important! One of the existing answers to this question made this mistake; as do many cryptography libraries written in PHP.
You should avoid implementing your own cryptography, and instead use a secure library written by and reviewed by cryptography experts.
Update: PHP 7.2 now provides libsodium! For best security, update your systems to use PHP 7.2 or higher and only follow the libsodium advice in this answer.
Use libsodium if you have PECL access (or sodium_compat if you want libsodium without PECL); otherwise...
Use defuse/php-encryption; don't roll your own cryptography!
Both of the libraries linked above make it easy and painless to implement authenticated encryption into your own libraries.
If you still want to write and deploy your own cryptography library, against the conventional wisdom of every cryptography expert on the Internet, these are the steps you would have to take.
hash_equals()
. If it fails, abort.mb_strlen()
and mb_substr()
, using the '8bit'
character set mode to prevent mbstring.func_overload
issues.mcrypt_create_iv()
, DO NOT USE MCRYPT_RAND
!
bin2hex()
, base64_encode()
, etc. may leak information about your encryption keys via cache timing. Avoid them if possible.Even if you follow the advice given here, a lot can go wrong with cryptography. Always have a cryptography expert review your implementation. If you are not fortunate enough to be personal friends with a cryptography student at your local university, you can always try the Cryptography Stack Exchange forum for advice.
If you need a professional analysis of your implementation, you can always hire a reputable team of security consultants to review your PHP cryptography code (disclosure: my employer).
Don't encrypt passwords. You want to hash them instead, using one of these password-hashing algorithms:
Never use a general-purpose hash function (MD5, SHA256) for password storage.
Don't encrypt URL Parameters. It's the wrong tool for the job.
If you are on PHP < 7.2 or otherwise do not have libsodium installed, you can use sodium_compat to accomplish the same result (albeit slower).
<?php
declare(strict_types=1);
/**
* Encrypt a message
*
* @param string $message - message to encrypt
* @param string $key - encryption key
* @return string
* @throws RangeException
*/
function safeEncrypt(string $message, string $key): string
{
if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw new RangeException('Key is not the correct size (must be 32 bytes).');
}
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = base64_encode(
$nonce.
sodium_crypto_secretbox(
$message,
$nonce,
$key
)
);
sodium_memzero($message);
sodium_memzero($key);
return $cipher;
}
/**
* Decrypt a message
*
* @param string $encrypted - message encrypted with safeEncrypt()
* @param string $key - encryption key
* @return string
* @throws Exception
*/
function safeDecrypt(string $encrypted, string $key): string
{
$decoded = base64_decode($encrypted);
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plain = sodium_crypto_secretbox_open(
$ciphertext,
$nonce,
$key
);
if (!is_string($plain)) {
throw new Exception('Invalid MAC');
}
sodium_memzero($ciphertext);
sodium_memzero($key);
return $plain;
}
Then to test it out:
<?php
// This refers to the previous code block.
require "safeCrypto.php";
// Do this once then store it somehow:
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';
$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
One of the projects I've been working on is an encryption library called Halite, which aims to make libsodium easier and more intuitive.
<?php
use \ParagonIE\Halite\KeyFactory;
use \ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;
// Generate a new random symmetric-key encryption key. You're going to want to store this:
$key = new KeyFactory::generateEncryptionKey();
// To save your encryption key:
KeyFactory::save($key, '/path/to/secret.key');
// To load it again:
$loadedkey = KeyFactory::loadEncryptionKey('/path/to/secret.key');
$message = 'We are all living in a yellow submarine';
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
All of the underlying cryptography is handled by libsodium.
<?php
/**
* This requires https://github.com/defuse/php-encryption
* php composer.phar require defuse/php-encryption
*/
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
require "vendor/autoload.php";
// Do this once then store it somehow:
$key = Key::createNewRandomKey();
$message = 'We are all living in a yellow submarine';
$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);
var_dump($ciphertext);
var_dump($plaintext);
Note: Crypto::encrypt()
returns hex-encoded output.
If you're tempted to use a "password", stop right now. You need a random 128-bit encryption key, not a human memorable password.
You can store an encryption key for long-term use like so:
$storeMe = bin2hex($key);
And, on demand, you can retrieve it like so:
$key = hex2bin($storeMe);
I strongly recommend just storing a randomly generated key for long-term use instead of any sort of password as the key (or to derive the key).
If you're using Defuse's library:
That's a bad idea, but okay, here's how to do it safely.
First, generate a random key and store it in a constant.
/**
* Replace this with your own salt!
* Use bin2hex() then add \x before every 2 hex characters, like so:
*/
define('MY_PBKDF2_SALT', "\x2d\xb7\x68\x1a\x28\x15\xbe\x06\x33\xa0\x7e\x0e\x8f\x79\xd5\xdf");
Note that you're adding extra work and could just use this constant as the key and save yourself a lot of heartache!
Then use PBKDF2 (like so) to derive a suitable encryption key from your password rather than encrypting with your password directly.
/**
* Get an AES key from a static password and a secret salt
*
* @param string $password Your weak password here
* @param int $keysize Number of bytes in encryption key
*/
function getKeyFromPassword($password, $keysize = 16)
{
return hash_pbkdf2(
'sha256',
$password,
MY_PBKDF2_SALT,
100000, // Number of iterations
$keysize,
true
);
}
Don't just use a 16-character password. Your encryption key will be comically broken.
This is the tiny limitation of Mysql in older version , actually after version 5.6 and later multiple timestamps works...
I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV
and HTML::Parser
.
JSON is "JavaScript Object Notation". JavaScript specifies its keys must be strings or symbols.
The following quotation from MDN Docs uses the terms "key/property" to refer to what I more often hear termed as "key/value".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Objects
In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.
Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.
$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
echo strip_tags_content($srting);
function strip_tags_content($text) {
return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
}
Output:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Something like this perhaps?
x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)
Actually, you don't need to modify the object
prototype and add a function there. The following should work well for your purpose.
var __next_objid=1;
function objectId(obj) {
if (obj==null) return null;
if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
return obj.__obj_id;
}
If you validate , option 1 comes up as an error in html 5, so option 2 is correct.
Swift 3
you can use index(where:) in Swift 3
func index(where predicate: @noescape Element throws -> Bool) rethrows -> Int?
example
if let i = theArray.index(where: {$0.name == "Foo"}) {
return theArray[i]
}
How about this:
ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest
PRIMARY KEY (wardNo, BHTNo, TestID)
Either of these 2:
NSString *subString = [dateString subStringWithRange:NSMakeRange(0,2)];
NSString *subString = [[dateString componentsSeparatedByString:@"/"] objectAtIndex:0];
Though keep in mind that sometimes a date string is not formatted properly and a day ( or a month for that matter ) is shown as 8, rather than 08 so the first one might be the worst of the 2 solutions.
The latter should be put into a separate array so you can actually check for the length of the thing returned, so you do not get any exceptions thrown in the case of a corrupt or invalid date string from whatever source you have.
I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.
In a previous answer from @kennytm:
^\d{5}(?:[-\s]\d{4})?$
…? = The pattern before it is optional (for condition 1)
If you want to allow both standard 5 digit and +4 zip codes, this is a great example.
To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ?
so it will always match the last 5 character group.
A useful tool I recommend for tinkering with RegEx is linked below:
I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.
If I got anything wrong or missed an important piece of information, please correct me.
DATEADD and GETDATE functions might not work in MySQL database. so if you are working with MySQL database, then the following command may help you.
select id, NewsHeadline as news_headline,
NewsText as news_text,
state, CreatedDate as created_on
from News
WHERE CreatedDate>= DATE_ADD(CURDATE(), INTERVAL -3 DAY);
I hope it will help you
This is what worked for me:
import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)
If you have access to create a new user privilege then do so to connect normally with node.js, that is worked for me
This is a hard question to answer definitively because the terms and often misused or confused.
Often, an emulator is a complete re-implementation of a particular device or platform. The emulator acts exactly like the real device would. For example, a NES emulator implements the CPU, the sound chip, the video output, the controller signals, etc. The unmodified code from a NES castridge can be dumped and then the resulting image can be loaded into our emulator and played.
A simulator is a partial implementation of a device/platform, it does just enough for its own purposes. For example, the iPhone Simulator runs an "iPhone app" that has been specifically compiled to target x86 and the Cocoa API rather than the real device's ARM CPU and Cocoa Touch API. However, the binary that we run in the simulator would not work on the real device.
This is what events are for.
HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});
On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:
// Script start
$rustart = getrusage();
// Code ...
// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}
$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";
Note that you don't need to calculate a difference if you are spawning a php instance for every test.
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
Try os.chdir
os.chdir(path)
        Change the current working directory to path. Availability: Unix, Windows.
If you want use it, use runat="server"
for that table. After that use tablename.visible=False
in server side code.
Clean your project Remove the /obj folder (probably using publish and deploy? - there is a bug in it)
replace required
by required="required"
I think you are looking for this: RowHeaderMouseDoubleClick event
private void DgwModificar_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
...
}
to get the row index:
int indice = e.RowIndex
JS
Create an external JavaScript file (i.e. mymap.js) with the following code
google.maps.visualRefresh = true; //Optional
var respMap;
function mymapini() {
var mapPos = new google.maps.LatLng(-0.172175,1.5); //Set the coordinates
var mapOpts = {
zoom: 10, //You can change this according your needs
disableDefaultUI: true, //Disabling UI Controls (Optional)
center: mapPos, //Center the map according coordinates
mapTypeId: google.maps.MapTypeId.ROADMAP
};
respMap = new google.maps.Map(document.getElementById('mymap'),
mapOpts);
var mapMarker = new google.maps.Marker({
position: mapPos,
map: respMap,
title: 'You can put any title'
});
//This centers automatically to the marker even if you resize your window
google.maps.event.addListener(respMap, 'idle', function() {
window.setTimeout(function() {
respMap.panTo(mapPos.getPosition());
}, 250);
});
}
google.maps.event.addDomListener(window, 'load', mymapini);
$("#modalOpen").click(function(){ //Use it like <a href="#" id="modalOpen"...
$("#myModal").show(); //ID from the Modal <div id="myModal">...
google.maps.event.trigger(respMap, 'resize');
});
HTML
Add the following code before the tag:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="js/mymap.js"></script>
Add this to the modal code:
<div id="mymap"></div>
CSS
Add this to your stylesheet:
#mymap { margin: 0; padding: 0; width:100%; height: 400px;}
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure.
For django-mptt, I used a structure like this:
id parent_id tree_id level lft rght -- --------- ------- ----- --- ---- 1 null 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12
Which describes a tree which looks like this (with id
representing each item):
1 +-- 2 | +-- 3 | +-- 4 | +-- 5 +-- 6 +-- 7
Or, as a nested set diagram which makes it more obvious how the lft
and rght
values work:
__________________________________________________________________________ | Root 1 | | ________________________________ ________________________________ | | | Child 1.1 | | Child 1.2 | | | | ___________ ___________ | | ___________ ___________ | | | | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | | 1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14 | |________________________________| |________________________________| | |__________________________________________________________________________|
As you can see, to get the entire subtree for a given node, in tree order, you simply have to select all rows which have lft
and rght
values between its lft
and rght
values. It's also simple to retrieve the tree of ancestors for a given node.
The level
column is a bit of denormalisation for convenience more than anything and the tree_id
column allows you to restart the lft
and rght
numbering for each top-level node, which reduces the number of columns affected by inserts, moves and deletions, as the lft
and rght
columns have to be adjusted accordingly when these operations take place in order to create or close gaps. I made some development notes at the time when I was trying to wrap my head around the queries required for each operation.
In terms of actually working with this data to display a tree, I created a tree_item_iterator
utility function which, for each node, should give you sufficient information to generate whatever kind of display you want.
More info about MPTT:
@user812954's answer was quite helpful, except I had to do this this in two steps:
sudo su
cd directory
Then, to exit out of "super user" mode, just type exit
.
The URL for a static file can be created using the static endpoint as following:
url_for('static', filename = 'name_of_file')
<link rel="stylesheet" href="{{url_for('static', filename='borders.css')}}" />
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '<
Very simple question that you can solved it easily ,
Please follow my step : change < to ( and >; to );
Just use: (
);
enter code here
` CREATE TABLE information (
-> id INT(11) NOT NULL AUTO_INCREMENT,
-> name VARCHAR(30) NOT NULL,
-> age INT(10) NOT NULL,
-> salary INT(100) NOT NULL,
-> address VARCHAR(100) NOT NULL,
-> PRIMARY KEY(id)
-> );`
Considering what @Robert said, I tried to play around with the config
command and it seems that there is a direct way to know both the name and email.
To know the username, type:
git config user.name
To know the email, type:
git config user.email
These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.
Uses Guava's static factory methods for Maps and is only 105 characters long.
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = Maps.newHashMap();
I had the same issue on macOS, after some time struggling and searching around, this answer actually solved the issue for me:
npm config rm proxy
npm config rm https-proxy
npm config set registry http://registry.npmjs.org/
Somehow all examples, while work well, are overcomplicated:
new Array()
, which is an overkill (and an overhead) for a simple associative array (AKA dictionary).new Object()
. It works fine, but why all this extra typing?This question is tagged "beginner", so let's make it simple.
The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":
// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {}; // Huh? {} is a shortcut for "new Object()"
// Add a key named fred with value 42
dict.fred = 42; // We can do that because "fred" is a constant
// and conforms to id rules
// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!"; // We use the subscript notation because
// the key is arbitrary (not id)
// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
val = ...; // Insanely complex calculations for the value
dict[key] = val;
// Read value of "fred"
val = dict.fred;
// Read value of 2bob2
val = dict["2bob2"];
// Read value of our cool secret key
val = dict[key];
Now let's change values:
// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs
// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3]; // Any legal value can be used
// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key
// Go over all keys and values in our dictionary
for (key in dict) {
// A for-in loop goes over all properties, including inherited properties
// Let's use only our own properties
if (dict.hasOwnProperty(key)) {
console.log("key = " + key + ", value = " + dict[key]);
}
}
Deleting values is easy too:
// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact
// Let's delete 2bob2
delete dict["2bob2"];
// Let's delete our secret key
delete dict[key];
// Now dict is empty
// Let's replace it, recreating all original data
dict = {
fred: 42,
"2bob2": "twins!"
// We can't add the original secret key because it was dynamic, but
// we can only add static keys
// ...
// oh well
temp1: val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
dict[key] = dict.temp1; // Copy the value
delete dict.temp1; // Kill the old key
} else {
// Do nothing; we are good ;-)
}
Open a command prompt:
Version: java -version
Location: where java (in Windows)
which java (in Unix, Linux, and Mac)
To set Java home in Windows:
Right click on My computer → Properties → Advanced system settings → Environment Variable → System Variable → New. Give the name as JAVA_HOME and the value as (e.g.) c:\programfiles\jdk
Select Path and click Edit, and keep it in the beginning as:
%JAVA_HOME%\bin;
...remaining settings goes here
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
Getting Datafrom MySQL database
hope this helps :)
fun(10) returns 10. If you want it to return 11 then you need to use ++i as opposed to i++.
int fun(int i)
{
return ++i;
}
To be verbose it the removal of extension is demonstrated for workbooks.. which now have a variety of extensions . . a new unsaved Book1 has no ext . works the same for files
Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean
Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
For Each wWB In Workbooks
WBNa = wWB.Name
If AnyExt Then
PD = InStr(WBNa, ".")
If PD > 0 Then WBNa = Left(WBNa, PD - 1)
PD = InStr(FWNa, ".")
If PD > 0 Then FWNa = Left(FWNa, PD - 1)
'
' the alternative of using split.. see commented out below
' looks neater but takes a bit longer then the pair of instr and left
' VBA does about 800,000 of these small splits/sec
' and about 20,000,000 Instr Lefts per sec
' of course if not checking for other extensions they do not matter
' and to any reasonable program
' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
' IN doing about doing 2000 of this routine per sec
' WBNa = Split(WBNa, ".")(0)
'FWNa = Split(FWNa, ".")(0)
End If
If WBNa = FWNa Then
WorkbookIsOpen = True
Exit Function
End If
Next wWB
End If
End Function
Insert a "line break" or a "paragraph break" in a RichTextBox "rtb" like this:
var range = new TextRange(rtb.SelectionStart, rtb.Selection.End);
range.Start.Paragraph.ContentStart.InsertLineBreak();
range.Start.Paragraph.ContentStart.InsertParagraphBreak();
The only way to get the NewLine items is by inserting text with "\r\n" items first, and then applying more code which works on Selection and/or TextRange objects. This makes sure that the \par items are converted to \line items, are saved as desired, and are still correct when reopening the *.Rtf file. That is what I found so far after hard tries. My three code lines need to be surrounded by more code (with loops) to set the TextPointer items (.Start .End .ContentStart .ContentEnd) where the Lines and Breaks should go, which I have done with success for my purposes.
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
If both columns can contain NULL
, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
This way you won't have to check for NULL
-ness of each column separately.
Alternatively, if both columns are actually defined as NOT NULL
, CONCAT() will be quite enough:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
As for COALESCE
, it's a bit different beast: given the list of arguments, it returns the first that's not NULL
.
In Sql Server 2012 - Management Studio:
Solution 1:
Execute the query
Right click the Results Window
Select Save Results As from the menu
Select CSV
Solution 2:
Right click on database
Select Tasks, Export Data
Select Source DB
Select Destination: Flat File Destination
Pick a file name
Select Format - Delimited
Choose a table or write a query
Pick a Column delimiter
Note: You can pick a Text qualifier that will delimit your text fields, such as quotes.
If you have a field with commas, don't use you use comma as a delimiter, because it does not escape commas. You can pick a column delimiter such as Vertical Bar: | instead of comma, or a tab character. Otherwise, write a query that escapes your commas or delimits your varchar field.
The escape character or text qualifier you need to use depends on your requirements.
You can use case
in bash to simulate a goto:
#!/bin/bash
case bar in
foo)
echo foo
;&
bar)
echo bar
;&
*)
echo star
;;
esac
produces:
bar
star
Validate email while typing, with button state handling.
$("#email").on("input", function(){
var email = $("#email").val();
var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!filter.test(email)) {
$(".invalid-email:empty").append("Invalid Email Address");
$("#submit").attr("disabled", true);
} else {
$("#submit").attr("disabled", false);
$(".invalid-email").empty();
}
});
Sorry, this is not possible with MS SQL Server (possible though with PostgreSQL):
select lastname + ', ' + firstname as fullname
from person
group by fullname
Otherwise just use this:
select x.fullname
from
(
select lastname + ', ' + firstname as fullname
from person
) as x
group by x.fullname
Or this:
select lastname + ', ' + firstname as fullname
from person
group by lastname, firstname -- no need to put the ', '
The above query is faster, groups the fields first, then compute those fields.
The following query is slower (it tries to compute first the select expression, then it groups the records based on that computation).
select lastname + ', ' + firstname as fullname
from person
group by lastname + ', ' + firstname
I won't refer too your example as it is quite simple for a general answer (for example it doesn't contain templated functions ,which force you to implement them on the header) , what I follow as a rule of thumb is the pimpl idiom
It has quite some benefits as you get faster compilation times and the syntactic sugar :
class->member
instead of class.member
The only drawback is the extra pointer you pay.
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
Here is a solution that looks good under iOS6/7/8/9.
Update 2016-06-10: this still works with iOS 9.3.3
Thanks for all your support, this is now on CocoaPods/Carthage/SPM at https://github.com/fulldecent/FDTextFieldTableViewCell
Basically we take the stock UITableViewCellStyleValue1
and staple a UITextField
where the detailTextLabel
is supposed to be. This gives us automatic placement for all scenarios: iOS6/7/8/9, iPhone/iPad, Image/No-image, Accessory/No-accessory, Portrait/Landscape, 1x/2x/3x.
Note: this is using storyboard with a UITableViewCellStyleValue1
type cell named "word".
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell = [tableView dequeueReusableCellWithIdentifier:@"word"];
cell.detailTextLabel.hidden = YES;
[[cell viewWithTag:3] removeFromSuperview];
textField = [[UITextField alloc] init];
textField.tag = 3;
textField.translatesAutoresizingMaskIntoConstraints = NO;
[cell.contentView addSubview:textField];
[cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:cell.textLabel attribute:NSLayoutAttributeTrailing multiplier:1 constant:8]];
[cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeTop multiplier:1 constant:8]];
[cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell.contentView attribute:NSLayoutAttributeBottom multiplier:1 constant:-8]];
[cell addConstraint:[NSLayoutConstraint constraintWithItem:textField attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:cell.detailTextLabel attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
textField.textAlignment = NSTextAlignmentRight;
textField.delegate = self;
return cell;
}
Add below setting to .eslintrc.js
/ .eslintrc.json
to ignore these errors:
rules: {
// suppress errors for missing 'import React' in files
"react/react-in-jsx-scope": "off",
// allow jsx syntax in js files (for next.js project)
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }], //should add ".ts" if typescript project
}
Why?
If you're using NEXT.js
then you do not require to import React
at top of files, nextjs does that for you.
Although parseInt
is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
It's also good to be convinced that a Graph can be represented as simply as :
class Node {
int value;
List<Node> adj;
}
and implement most the algorithms you find interesting by yourself. If you fall on this question in the middle of some practice/learning session on graphs, that's the best lib to consider. ;)
You can also prefer adjacency matrix for most common algorithms :
class SparseGraph {
int[] nodeValues;
List<Integer>[] edges;
}
or a matrix for some operations :
class DenseGraph {
int[] nodeValues;
int[][] edges;
}
To get a View from a specific position of recyclerView you need to call findViewHolderForAdapterPosition(position) on recyclerView object that will return RecyclerView.ViewHolder
from the returned RecyclerView.ViewHolder object with itemView you can access all Views at that particular position
RecyclerView.ViewHolder rv_view = recyclerView.findViewHolderForAdapterPosition(position);
ImageView iv_wish = rv_view.itemView.findViewById(R.id.iv_item);
Specify /D
to change the drive also.
CD /D %root%
By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:
CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ]
(
column [ ASC | DESC ] [ ,...n ]
)
Therefore, the resuting table definition would be:
CREATE TABLE [dbo].[user](
[userID] [int] IDENTITY(1,1) NOT NULL,
[fcode] [int] NULL,
[scode] [int] NULL,
[dcode] [int] NULL,
[name] [nvarchar](50) NULL,
[address] [nvarchar](50) NULL,
CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED
(
[userID] ASC
),
CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
(
[fcode], [scode], [dcode]
)
) ON [PRIMARY]
pmg's answer is very convincing. If you would like to know how static declarations work at object level then this below info could be interesting to you. I reused the same program written by pmg and compiler it into a .so(shared object) file
Following contents are after dumping the .so file into something human readable
0000000000000675 f1: address of f1 function
000000000000068c f2: address of f2(staticc) function
note the difference in the function address , it means something . For a function that's declared with different address , it can very well signify that f2 lives very far away or in a different segment of the object file.
Linkers use something called PLT(Procedure linkage table) and GOT(Global offsets table) to understand symbols that they have access to link to .
For now think that GOT and PLT magically bind all the addresses and a dynamic section holds information of all these functions that are visible by linker.
After dumping the dynamic section of the .so file we get a bunch of entries but only interested in f1 and f2 function.
The dynamic section holds entry only for f1 function at address 0000000000000675 and not for f2 !
Num: Value Size Type Bind Vis Ndx Name
9: 0000000000000675 23 FUNC GLOBAL DEFAULT 11 f1
And thats it !. From this its clear that the linker will be unsuccessful in finding the f2 function since its not in the dynamic section of the .so file.
I have used MySQL DB for Hive MetaStore. Please follow the below steps:
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:mysql://localhost/metastorecreateDatabaseIfNotExist=true&useSSL=false</value>
</property>
mysql -u hduser -p
drop database metastore
schematool -initSchema dbType mysql
Now error will go.
For a VARBINARY(MAX)
column, I had to use NVARCHAR(MAX)
:
cast(Content as nvarchar(max))
Or
CONVERT(NVARCHAR(MAX), Content, 0)
VARCHAR(MAX) didn't show the entire value
chmod +w <directory>
or chmod a+w <directory>
- Write permission for user, group and others
chmod u+w <directory>
- Write permission for user
chmod g+w <directory>
- Write permission for group
chmod o+w <directory>
- Write permission for others
CALL common.php
<style>
.ddsmoothmenu ul li{float: left; padding: 0 20px;}
.ddsmoothmenu ul li a{display: block;
padding: 40px 15px 20px 15px;
color: #4b4b4b;
font-size: 13px;
font-family: 'Open Sans', Arial, sans-serif;
text-align: right;
text-transform: uppercase;
margin-left: 1px; color: #fff; background: #000;}
.current .test{ background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php" class="test">Home <i>::</i> <span>welcome</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>"><a href="about.php" class="test">About us <i>::</i> <span>Who we are</span></a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>"><a href="course.php">Our Courses <i>::</i> <span>What we do</span></a></li>
</ul><!-- end #dropdown-menu -->
</div><!-- end .span8 -->
add each page
<?php include('common.php'); ?>
You could use a combination of the UNIX_TIMESTAMP() function to do that.
SELECT ... FROM ... WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(thefield) < 259200
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
I'm using this easy way out:
$(document).ready(function() {_x000D_
$("#btn").prop('title', 'Click to copy your shorturl');_x000D_
});_x000D_
_x000D_
function myFunction(){_x000D_
$(btn).tooltip('hide');_x000D_
$(btn).attr('data-original-title', 'Test');_x000D_
$(btn).tooltip('show');_x000D_
});
_x000D_
new Date().toLocaleDateString()
= "9/13/2015"
You don't need to set innerHTML, just by writing
<p>
<script> document.write(new Date().toLocaleDateString()); </script>
</p>
will work.
P.S.
new Date().toDateString()
= "Sun Sep 13 2015"
YouTube resolutions and images
http://img.youtube.com/vi/<video-id>/<resolution><image>.jpg
Resolution
- lowest resolution
sd - Standard Definition
mq - Medium Quality
hq - High Quality
maxres - MAXimum RESolution
Image
default - Default image (1, 2, 3 shot from video, or custom uploaded)
1 - First shot from video
2 - Second shot from video
3 - Third shot from video
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
You could also use boost, which defines important math constants with maximum accuracy for the requested type (i.e. float vs double).
const double pi = boost::math::constants::pi<double>();
Check out the boost documentation for more examples.
having dignosed the problem I was able to use the existing system default CA file, on debian6 this is:
/etc/ssl/certs/ca-certificates.crt
as root this can be done like:
echo curl.cainfo=/etc/ssl/certs/ca-certificates.crt >> /etc/php5/mods-available/curl.ini
then re-start the web-server.
If you want to add a product into the array you can use:
$item['product'] = $product;
For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:
From GHad's benchmark, there are a few issue people have mentioned:
1>Like BalusC mentioned: stream.available() is flowed in this case.
Because available() returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
So 1st to remove the URL this approach.
2>As StuartH mentioned - the order the test run also make the cache difference, so take that out by run the test separately.
Now start test:
When CHANNEL one run alone:
CHANNEL sum: 59691, per Iteration: 238.764
When LENGTH one run alone:
LENGTH sum: 48268, per Iteration: 193.072
So looks like the LENGTH one is the winner here:
@Override
public long getResult() throws Exception {
File me = new File(FileSizeBench.class.getResource(
"FileSizeBench.class").getFile());
return me.length();
}
In my case, restarting SQL Server 2014 (on my development server) fixed the issue.
I got the same error when:
Using a custom ModelView, both Actions (GET and POST) were passing the ModelView that contained two objects:
public ActionResult Add(int? categoryID)
{
...
ProductViewModel productViewModel = new ProductViewModel(
product,
rootCategories
);
return View(productViewModel);
}
And the POST also accepting the same model view:
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(ProductModelView productModelView)
{...}
Problem was the View received the ModelView (needed both product and list of categories info), but after submitted was returning only the Product object, but as the POST Add expected a ProductModelView it passed a NULL but then the ProductModelView only constructor needed two parameters(Product, RootCategories), then it tried to find another constructor with no parameters for this NULL case then fails with "no parameterles..."
So, fixing the POST Add as follows correct the problem:
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Product product)
{...}
Hope this can help somebody (I spent almost half day to find this out!).
If you are using Swift, the Just library does this for you. Example from it's readme file:
// talk to registration end point
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
if (r.ok) { /* success! */ }
}
This can be done in javascript without the need to open another browser window.
window.location.assign('url');
Replace 'url' with the link to your file. You can put this in a function and call it with ng-click
if you need to trigger the download from a button.
If you do have a TemplateField
inside the columns of your GridView
and you have, say, a control named blah bound to it. Then place the outlook_id
as a HiddenField
there like this:
<asp:TemplateField HeaderText="OutlookID">
<ItemTemplate>
<asp:Label ID="blah" runat="server">Existing Control</asp:Label>
<asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now, grab the row in the event you want the outlook_id
and then access the control.
For RowDataBound
access it like:
string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;
Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.
I tried many methods including defined here. What I got is,
Make sure the name of repository is valid. The best way is to copy the link from repository site and paste in git bash.
Make sure you have commited the selected files.
git commit -m "Your commit here"
If both steps don't work, try
git push -u -f origin master
This is a great example of using the wrong tool for the job. Regular expressions do not handle arbitrarily nested sub-matches very well. What you should do instead is use a real lexer and parser (a grammar for C++ should be easy to find) and look for unexpectedly empty loop bodies.
Line ending format used in OS
CR
(Carriage Return \r
) and LF
(LineFeed \n
) pairLF
(LineFeed \n
)We can configure git to auto-correct line ending formats for each OS in two ways.
.gitattributes
filegit config --global core.autocrlf input
This will fix any CRLF
to LF
when you commit.
git config --global core.autocrlf true
This will make sure when you checkout in windows, all LF
will convert to CRLF
It is a good idea to keep a .gitattributes
file as we don't want to expect everyone in our team set their config. This file should keep in repo's root path and if exist one, git will respect it.
* text=auto
This will treat all files as text files and convert to OS's line ending on checkout and back to LF
on commit automatically. If wanted to tell explicitly, then use
* text eol=crlf
* text eol=lf
First one is for checkout and second one is for commit.
*.jpg binary
Treat all .jpg
images as binary files, regardless of path. So no conversion needed.
Or you can add path qualifiers:
my_path/**/*.jpg binary
Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:
def check_authorization(f):
def wrapper(*args):
print args[0].url
return f(*args)
return wrapper
class Client(object):
def __init__(self, url):
self.url = url
@check_authorization
def get(self):
print 'get'
>>> Client('http://www.google.com').get()
http://www.google.com
get
The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr
if you don't want to hardcode the attribute name:
def check_authorization(attribute):
def _check_authorization(f):
def wrapper(self, *args):
print getattr(self, attribute)
return f(self, *args)
return wrapper
return _check_authorization
Observer-Observable: it is used in ApplicationContext's event mechanism
An alternative way if you don't want to raise errors if one of the keys is absent (so that your main code can run without interruption):
def get_value(self,your_dict,*keys):
curr_dict_ = your_dict
for k in keys:
v = curr_dict.get(k,None)
if v is None:
break
if isinstance(v,dict):
curr_dict = v
return v
In this case, if any of the input keys is not present, None is returned, which can be used as a check in your main code to perform an alternative task.
Use true
as the second parameter to json_decode
. This will decode the json into an associative array instead of stdObject
instances:
$my_array = json_decode($my_json, true);
See the documentation for more details.
how about this?
fun <- function(x, ...){
y=NULL
parms=list(...)
for (name in names(parms) ) {
assign(name, parms[[name]])
}
print(is.null(y))
}
Then try:
> fun(1,y=4)
[1] FALSE
> fun(1)
[1] TRUE
There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
"
Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"
To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:
/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
where TKey : IEquatable<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>
where TRoleClaim : IdentityRoleClaim<TKey>
where TUserToken : IdentityUserToken<TKey>
{
/// <summary>
/// Initializes a new instance of <see cref="IdentityDbContext"/>.
/// </summary>
/// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
public IdentityDbContext(DbContextOptions options) : base(options)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
/// </summary>
protected IdentityDbContext()
{ }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
/// </summary>
public DbSet<TUser> Users { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
/// </summary>
public DbSet<TUserClaim> UserClaims { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
/// </summary>
public DbSet<TUserLogin> UserLogins { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
/// </summary>
public DbSet<TUserRole> UserRoles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
/// </summary>
public DbSet<TUserToken> UserTokens { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
/// </summary>
public DbSet<TRole> Roles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
/// </summary>
public DbSet<TRoleClaim> RoleClaims { get; set; }
/// <summary>
/// Configures the schema needed for the identity framework.
/// </summary>
/// <param name="builder">
/// The builder being used to construct the model for this context.
/// </param>
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>(b =>
{
b.HasKey(u => u.Id);
b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
b.ToTable("AspNetUsers");
b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.UserName).HasMaxLength(256);
b.Property(u => u.NormalizedUserName).HasMaxLength(256);
b.Property(u => u.Email).HasMaxLength(256);
b.Property(u => u.NormalizedEmail).HasMaxLength(256);
b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<TRole>(b =>
{
b.HasKey(r => r.Id);
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.Name).HasMaxLength(256);
b.Property(u => u.NormalizedName).HasMaxLength(256);
b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
});
builder.Entity<TUserClaim>(b =>
{
b.HasKey(uc => uc.Id);
b.ToTable("AspNetUserClaims");
});
builder.Entity<TRoleClaim>(b =>
{
b.HasKey(rc => rc.Id);
b.ToTable("AspNetRoleClaims");
});
builder.Entity<TUserRole>(b =>
{
b.HasKey(r => new { r.UserId, r.RoleId });
b.ToTable("AspNetUserRoles");
});
builder.Entity<TUserLogin>(b =>
{
b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
b.ToTable("AspNetUserLogins");
});
builder.Entity<TUserToken>(b =>
{
b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
b.ToTable("AspNetUserTokens");
});
}
}
Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:
First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.
public class ApplicationDbContext
: IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
Extra Notes:
1) We can also change asp.net Identity default table names with the following solution:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(): base("DefaultConnection")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("user");
modelBuilder.Entity<ApplicationUser>().ToTable("user");
modelBuilder.Entity<IdentityRole>().ToTable("role");
modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
}
}
2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...
public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
public ApplicationRole()
{
this.Id = Guid.NewGuid().ToString();
}
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
// Add any custom Role properties/code here
}
// Must be expressed in terms of our custom types:
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole,
string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.
Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code
SQLite database FAQ: How do I drop a SQLite database?
People used to working with other databases are used to having a "drop database" command, but in SQLite there is no similar command. The reason? In SQLite there is no "database server" -- SQLite is an embedded database, and your database is entirely contained in one file. So there is no need for a SQLite drop database command.
To "drop" a SQLite database, all you have to do is delete the SQLite database file you were accessing.
copy from http://alvinalexander.com/android/sqlite-drop-database-how
You can use df.index
to access the index object and then get the values in a list using df.index.tolist()
. Similarly, you can use df['col'].tolist()
for Series.
Reflection is your friend, as has been pointed out. But you need to use the correct method;
Assembly.GetEntryAssembly() //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly() // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t ) // gives you the assembly in which the specified type is defined.
This simple solution worked for me.
import 'rxjs/add/operator/pairwise';
import { Router } from '@angular/router';
export class TempComponent {
constructor(private router: Router) {
this.router.events.pairwise().subscribe((event) => {
console.log(event); // NavigationEnd will have last and current visit url
});
};
}
Disabling Use command-line client
from the settings worked well form me on IntelliJ Ultimate 14.0.
How about using a JavaScript trick?
var Avals = ss.getRange("A1:A").getValues();
var Alast = Avals.filter(String).length;
I borrowed this idea from this answer. The Array.filter()
method is operating on the Avals
array, which contains all the cells in column A. By filtering on a native function's constructor, we get back only non-null elements.
This works for a single column only; if the range contains multiple columns,then the outcome of filter()
will include cells from all columns, and thus be outside the populated dimensions of the range.
One reason why you might prefer to use a JOIN
rather than NOT IN
is that if the Values in the NOT IN
clause contain any NULL
s you will always get back no results. If you do use NOT IN
remember to always consider whether the sub query might bring back a NULL value!
RE: Question in Comments
'x' NOT IN (NULL,'a','b')
= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'
= Unknown and True and True
= Unknown
Try this procedure:
def procedure(input):
a=0
print input[a]
ecs = input[a] #ecs stands for each character separately
while ecs != input:
a = a + 1
print input[a]
In order to use it you have to know how to use procedures and although it works, it has an error in the end so you have to work that out too.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
While configuring idea plugin in gradle, you should define output directories as follows.
idea{
module{
inheritOutputDirs = false
outputDir = compileJava.destinationDir
testOutputDir = compileTestJava.destinationDir
}
}
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T>
members and aggregate the source list):
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
public class ModifiableList<T> : List<T>
{
private readonly IList<T> pendingAdditions = new List<T>();
private int activeEnumerators = 0;
public ModifiableList(IEnumerable<T> collection) : base(collection)
{
}
public ModifiableList()
{
}
public new void Add(T t)
{
if(activeEnumerators == 0)
base.Add(t);
else
pendingAdditions.Add(t);
}
public new IEnumerator<T> GetEnumerator()
{
++activeEnumerators;
foreach(T t in ((IList<T>)this))
yield return t;
--activeEnumerators;
AddRange(pendingAdditions);
pendingAdditions.Clear();
}
}
class Program
{
static void Main(string[] args)
{
ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });
foreach(int i in ints)
ints.Add(i * 2);
foreach(int i in ints)
Console.WriteLine(i * 2);
}
}
}
First off I recommend you use the following constructor instead of the one you currently use:
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
Next, you really should remove this code:
// Wait 10 Seconds for data...
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(10);
Console.WriteLine(sp.Read(buf,0,bufSize)); //prints data directly to the Console
}
And instead just loop until the user presses a key or something, like so:
namespace serialPortCollection
{ class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort("COM10", 115200);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
// My Event Handler Method
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString());
}
Console.WriteLine();
}
}
}
Also, note the revisions to the data received event handler, it should actually print the buffer now.
UPDATE 1
I just ran the following code successfully on my machine (using a null modem cable between COM33 and COM34)
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Thread writeThread = new Thread(new ThreadStart(WriteThread));
SerialPort sp = new SerialPort("COM33", 115200, Parity.None, 8, StopBits.One);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
writeThread.Start();
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
byte[] buf = new byte[spL.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
spL.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
Console.Write(b.ToString() + " ");
}
Console.WriteLine();
}
private static void WriteThread()
{
SerialPort sp2 = new SerialPort("COM34", 115200, Parity.None, 8, StopBits.One);
sp2.Open();
byte[] buf = new byte[100];
for (byte i = 0; i < 100; i++)
{
buf[i] = i;
}
sp2.Write(buf, 0, buf.Length);
sp2.Close();
}
}
}
UPDATE 2
Given all of the traffic on this question recently. I'm beginning to suspect that either your serial port is not configured properly, or that the device is not responding.
I highly recommend you attempt to communicate with the device using some other means (I use hyperterminal frequently). You can then play around with all of these settings (bitrate, parity, data bits, stop bits, flow control) until you find the set that works. The documentation for the device should also specify these settings. Once I figured those out, I would make sure my .NET SerialPort is configured properly to use those settings.
Some tips on configuring the serial port:
Note that when I said you should use the following constructor, I meant that use that function, not necessarily those parameters! You should fill in the parameters for your device, the settings below are common, but may be different for your device.
new SerialPort("COM10", 115200, Parity.None, 8, StopBits.One);
It is also important that you setup the .NET SerialPort to use the same flow control as your device (as other people have stated earlier). You can find more info here:
http://www.lammertbies.nl/comm/info/RS-232_flow_control.html
You need to give a relative file path of <a href="../index.html">Home</a>
Alternately you can specify a link from the root of your site with
<a href="/pages/en/index.html">Home</a>
..
and .
have special meanings in file paths, ..
means up one directory and .
means current directory.
so <a href="index.html">Home</a>
is the same as <a href="./index.html">Home</a>
If you already have Visual Studio Build Tools installed but you're still getting that error, then you may need to "Modify" your installation to include the Visual C++ build tools.
To do that:
Open up the Visual Studio Installer (you can search for it in the Start Menu if needed).
Find Visual Studio Build Tools and click "Modify":
After the C++ tools finish installing, run the pip command again and it should work.