Rda is just a short name for RData. You can just save(), load(), attach(), etc. just like you do with RData.
Rds stores a single R object. Yet, beyond that simple explanation, there are several differences from a "standard" storage. Probably this R-manual Link to readRDS() function clarifies such distinctions sufficiently.
So, answering your questions:
You can create your own method, passing throught the array and the value you want removed:
function removeItem(arr, item){
return arr.filter(f => f !== item)
}
Then you can call this with:
ary = removeItem(ary, 'seven');
I had a similar issue to this. I solved it by making all the projects within my solution target the same .NET Framework 4 Client Profile and then rebuilding the entire solution.
I think what you want is something like:
=INDEX(B:B,MATCH(C2,A:A,0))
I should mention that MATCH checks the position at which the value can be found within A:A (given the 0
, or FALSE, parameter, it looks only for an exact match and given its nature, only the first instance found) then INDEX returns the value at that position within B:B.
I wrote a function for the FFT in Java: http://www.wikijava.org/wiki/The_Fast_Fourier_Transform_in_Java_%28part_1%29
It's in the Public Domain so you can use those functions everywhere (personal or business projects too). Just cite me in the credits and send me just a link of your work, and you're ok.
It is completely reliable. I've checked its output against the Mathematica's FFT and they were always correct until the 15th decimal digit. I think it's a very good FFT implementation for Java. I wrote it on the J2SE 1.6 version, and tested it on the J2SE 1.5-1.6 version.
If you count the number of instruction (it's a lot much simpler than a perfect computational complexity function estimation) you can clearly see that this version is great even if it's not optimized at all. I'm planning to publish the optimized version if there are enough requests.
Let me know if it was useful, and tell me any comment you like.
I share the same code right here:
/**
* @author Orlando Selenu
*
*/
public class FFTbase {
/**
* The Fast Fourier Transform (generic version, with NO optimizations).
*
* @param inputReal
* an array of length n, the real part
* @param inputImag
* an array of length n, the imaginary part
* @param DIRECT
* TRUE = direct transform, FALSE = inverse transform
* @return a new array of length 2n
*/
public static double[] fft(final double[] inputReal, double[] inputImag,
boolean DIRECT) {
// - n is the dimension of the problem
// - nu is its logarithm in base e
int n = inputReal.length;
// If n is a power of 2, then ld is an integer (_without_ decimals)
double ld = Math.log(n) / Math.log(2.0);
// Here I check if n is a power of 2. If exist decimals in ld, I quit
// from the function returning null.
if (((int) ld) - ld != 0) {
System.out.println("The number of elements is not a power of 2.");
return null;
}
// Declaration and initialization of the variables
// ld should be an integer, actually, so I don't lose any information in
// the cast
int nu = (int) ld;
int n2 = n / 2;
int nu1 = nu - 1;
double[] xReal = new double[n];
double[] xImag = new double[n];
double tReal, tImag, p, arg, c, s;
// Here I check if I'm going to do the direct transform or the inverse
// transform.
double constant;
if (DIRECT)
constant = -2 * Math.PI;
else
constant = 2 * Math.PI;
// I don't want to overwrite the input arrays, so here I copy them. This
// choice adds \Theta(2n) to the complexity.
for (int i = 0; i < n; i++) {
xReal[i] = inputReal[i];
xImag[i] = inputImag[i];
}
// First phase - calculation
int k = 0;
for (int l = 1; l <= nu; l++) {
while (k < n) {
for (int i = 1; i <= n2; i++) {
p = bitreverseReference(k >> nu1, nu);
// direct FFT or inverse FFT
arg = constant * p / n;
c = Math.cos(arg);
s = Math.sin(arg);
tReal = xReal[k + n2] * c + xImag[k + n2] * s;
tImag = xImag[k + n2] * c - xReal[k + n2] * s;
xReal[k + n2] = xReal[k] - tReal;
xImag[k + n2] = xImag[k] - tImag;
xReal[k] += tReal;
xImag[k] += tImag;
k++;
}
k += n2;
}
k = 0;
nu1--;
n2 /= 2;
}
// Second phase - recombination
k = 0;
int r;
while (k < n) {
r = bitreverseReference(k, nu);
if (r > k) {
tReal = xReal[k];
tImag = xImag[k];
xReal[k] = xReal[r];
xImag[k] = xImag[r];
xReal[r] = tReal;
xImag[r] = tImag;
}
k++;
}
// Here I have to mix xReal and xImag to have an array (yes, it should
// be possible to do this stuff in the earlier parts of the code, but
// it's here to readibility).
double[] newArray = new double[xReal.length * 2];
double radice = 1 / Math.sqrt(n);
for (int i = 0; i < newArray.length; i += 2) {
int i2 = i / 2;
// I used Stephen Wolfram's Mathematica as a reference so I'm going
// to normalize the output while I'm copying the elements.
newArray[i] = xReal[i2] * radice;
newArray[i + 1] = xImag[i2] * radice;
}
return newArray;
}
/**
* The reference bitreverse function.
*/
private static int bitreverseReference(int j, int nu) {
int j2;
int j1 = j;
int k = 0;
for (int i = 1; i <= nu; i++) {
j2 = j1 / 2;
k = 2 * k + j1 - 2 * j2;
j1 = j2;
}
return k;
}
}
The answer for git branch -r --contains <commit>
works well for normal remote branches, but if the commit is only in the hidden head
namespace that GitHub creates for PRs, you'll need a few more steps.
Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r
doesn't know about PR #42 because refs like refs/pull/42/head
aren't listed as a remote branch by default.
In .git/config
for the [remote "origin"]
section add a new line:
fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
(This gist has more context.)
Then when you git fetch
you'll get all the PR branches, and when you run git branch -r --contains <commit>
you'll see origin/pr/42
contains the commit.
In some systems like your office system, there is sometimes a firewall/security client that is installed for security purpose. Try uninstalling that and then run the command again, it should start the download.
My system had Netskope Client installed and was blocking the ssl communication.
Search in finder -> uninstall netskope, run it, and try installing homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
PS: consider installing the security client.
This can be done using HTML5, but will only work in browsers that support it. Here's an example.
Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
Try this:
Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK
The primary key in Cassandra usually consists of two parts - Partition key and Clustering columns.
primary_key((partition_key), clustering_col )
Partition key - The first part of the primary key. The main aim of a partition key is to identify the node which stores the particular row.
CREATE TABLE phone_book ( phone_num int, name text, age int, city text, PRIMARY KEY ((phone_num, name), age);
Here, (phone_num, name) is the partition key. While inserting the data, the hash value of the partition key is generated and this value decides which node the row should go into.
Consider a 4 node cluster, each node has a range of hash values it can store. (Write) INSERT INTO phone_book VALUES (7826573732, ‘Joey’, 25, ‘New York’);
Now, the hash value of the partition key is calculated by Cassandra partitioner. say, hash value(7826573732, ‘Joey’) ? 12 , now, this row will be inserted in Node C.
(Read) SELECT * FROM phone_book WHERE phone_num=7826573732 and name=’Joey’;
Now, again the hash value of the partition key (7826573732,’Joey’) is calculated, which is 12 in our case which resides in Node C, from which the read is done.
There can be more than one partition key and clustering columns in a primary key depending on the query you are solving.
primary_key((pk1, pk2), col 1,col2)
If you want to use the same function on different events the following code block can be used
$('input').on('keyup blur focus', function () {
//function block
})
This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.
brief mnemonics:
git reset HEAD : index = HEAD
git checkout : file_tree = index
git reset --hard HEAD : file_tree = index = HEAD
For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
if (this.hasClass(arguments[i])) {
return true;
}
}
return false;
}
Then, in your example, you could use this:
if ($('html').hasAnyClass('m320', 'm768')) {
// do stuff
}
You can pass as many class names as you want.
Here's an enhanced version that also lets you pass multiple class names separated by a space:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
var classes = arguments[i].split(" ");
for (var j = 0; j < classes.length; j++) {
if (this.hasClass(classes[j])) {
return true;
}
}
}
return false;
}
if ($('html').hasAnyClass('m320 m768')) {
// do stuff
}
Working demo: http://jsfiddle.net/jfriend00/uvtSA/
It was almost correct just change your last line like:
String stopEnd = stop.substring(0, stop.length() - 1); //replace stopName with stop.
OR
you can replace your last two lines;
String stopEnd = stopName.substring(0, stopName.length() - 2);
You can use the negation pseudo-class :not()
against the :last-child
pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:
:not(:last-child) { /* styles */ }
Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".
A snippet from Psycopg2's tutorial page at Postgresql.org (see bottom):
A last item I would like to show you is how to insert multiple rows using a dictionary. If you had the following:
namedict = ({"first_name":"Joshua", "last_name":"Drake"},
{"first_name":"Steven", "last_name":"Foo"},
{"first_name":"David", "last_name":"Bar"})
You could easily insert all three rows within the dictionary by using:
cur = conn.cursor()
cur.executemany("""INSERT INTO bar(first_name,last_name) VALUES (%(first_name)s, %(last_name)s)""", namedict)
It doesn't save much code, but it definitively looks better.
C++ virtual constructor is not possible.For example you can not mark a constructor as virtual.Try this code
#include<iostream.h>
using namespace std;
class aClass
{
public:
virtual aClass()
{
}
};
int main()
{
aClass a;
}
It causes an error.This code is trying to declare a constructor as virtual. Now let us try to understand why we use virtual keyword. Virtual keyword is used to provide run time polymorphism. For example try this code.
#include<iostream.h>
using namespace std;
class aClass
{
public:
aClass()
{
cout<<"aClass contructor\n";
}
~aClass()
{
cout<<"aClass destructor\n";
}
};
class anotherClass:public aClass
{
public:
anotherClass()
{
cout<<"anotherClass Constructor\n";
}
~anotherClass()
{
cout<<"anotherClass destructor\n";
}
};
int main()
{
aClass* a;
a=new anotherClass;
delete a;
getchar();
}
In main a=new anotherClass;
allocates a memory for anotherClass
in a pointer a
declared as type of aClass
.This causes both the constructor (In aClass
and anotherClass
) to call automatically.So we do not need to mark constructor as virtual.Because when an object is created it must follow the chain of creation (i.e first the base and then the derived classes).
But when we try to delete a delete a;
it causes to call only the base destructor.So we have to handle the destructor using virtual keyword. So virtual constructor is not possible but virtual destructor is.Thanks
Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:
def split_into_two_lists(lst, f):
a = []
b = []
for elem in lst:
if f(elem):
a.append(elem)
else:
b.append(elem)
return a, b
That way you are not processing anything twice and also are not repeating code.
You could use sweetalert: https://sweetalert.js.org/guides/
npm install sweetalert --save
Then, simply import it into your application:
import swal from 'sweetalert';
If you pass two arguments, the first one will be the modal's title, and the second one its text.
swal("Here's the title!", "...and here's the text!");
Yet another way to remove an element(s) from a list by index.
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# remove the element at index 3
a[3:4] = []
# a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
# remove the elements from index 3 to index 6
a[3:7] = []
# a is now [0, 1, 2, 7, 8, 9]
a[x:y] points to the elements from index x
to y-1
. When we declare that portion of the list as an empty list ([]
), those elements are removed.
While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.
function varyArg () {
return arguments[0] + arguments[1];
}
When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.
Let's explicitly state the same function has variable parameters:
function varyArg (var_args) {
return arguments[0] + arguments[1];
}
There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.
SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS
In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.
function varyArg (args_obj) {
return args_obj.name+" "+args_obj.weight;
}
varyArg({name: "Brian", weight: 150});
This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!
function sumOfAll (var_args) {
return arguments.reduce(function(a, b) {
return a + b;
}, 0);
}
sumOfAll(1,2,3); // returns 6
function myObjArgs(args_obj) {
// MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
if (typeof args_obj !== "object") {
return "Arguments passed must be in object form!";
}
return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
}
myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old
As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:
Array.prototype.map.call(arguments, function (val, idx, arr) {});
To avoid this use the rest parameter:
function varyArgArr (...var_args) {
return var_args.sort();
}
varyArgArr(5,1,3); // returns 1, 3, 5
If the list is sorted, you can use the Get-Unique cmdlet:
$a | Get-Unique
import java.util.*;
public class Restring {
public static void main(String[] args) {
String input,output;
Scanner kbd=new Scanner(System.in);
System.out.println("Please Enter a String");
input=kbd.nextLine();
int n=input.length();
char tmp[]=new char[n];
char nxt[]=new char[n];
tmp=input.toCharArray();
int m=0;
for(int i=n-1;i>=0;i--)
{
nxt[m]=tmp[i];
m++;
}
System.out.print("Reversed String is ");
for(int i=0;i<n;i++)
{
System.out.print(nxt[i]);
}
}
See Wikipedia's article on Color Difference for the right leads. Basically, you want to compute a distance metric in some multidimensional colorspace.
But RGB
is not "perceptually uniform", so your Euclidean RGB
distance metric suggested by Vadim will not match the human-perceived distance between colors. For a start, L*a*b*
is intended to be a perceptually uniform colorspace, and the deltaE metric is commonly used. But there are more refined colorspaces and more refined deltaE formulas that get closer to matching human perception.
You'll have to learn more about colorspaces and illuminants to do the conversions. But for a quick formula that is better than the Euclidean RGB
metric, just do this:
RGB
values are in the sRGB
colorspacesRGB
to L*a*b*
conversion formulassRGB
colors to L*a*b*
L*a*b*
valuesIt's not computationally expensive, it's just some nonlinear formulas and some multiplications and additions.
Gradle with Android Studio could do it this way (link).
It's in the paragraph "Configuring the Structure"
sourceSets {
main {
java {
srcDir 'src/java'
}
resources {
srcDir 'src/resources'
}
}
}
Check your firewall setting and set
<property>
<name>fs.default.name</name>
<value>hdfs://MachineName:9000</value>
</property>
replace localhost to machine name
Using Zxing this way requires a user to also install the barcode scanner app, which isn't ideal. What you probably want is to bundle Zxing into your app directly.
I highly recommend using this library: https://github.com/dm77/barcodescanner
It takes all the crazy build issues you're going to run into trying to integrate Xzing or Zbar directly. It uses those libraries under the covers, but wraps them in a very simple to use API.
Seems like only real solutions today revolve around scaling out or sharding. All modern databases (NoSQLs as well as NewSQLs) support horizontal scaling right out of the box, at the database layer, without the need for the application to have sharding code or something.
Unfortunately enough, for the trusted good-old MySQL, sharding is not provided "out of the box". ScaleBase (disclaimer: I work there) is a maker of a complete scale-out solution an "automatic sharding machine" if you like. ScaleBae analyzes your data and SQL stream, splits the data across DB nodes, and aggregates in runtime – so you won’t have to! And it's free download.
Don't get me wrong, NoSQLs are great, they're new, new is more choice and choice is always good!! But choosing NoSQL comes with a price, make sure you can pay it...
You can see here some more data about MySQL, NoSQL...: http://www.scalebase.com/extreme-scalability-with-mongodb-and-mysql-part-1-auto-sharding
Hope that helped.
If you've got HTML5:
oninput
(fires only when a change actually happens, but does so immediately)Otherwise you need to check for all these events which might indicate a change to the input element's value:
onchange
onkeyup
(not keydown
or keypress
as the input's value won't have the new keystroke in it yet)onpaste
(when supported)and maybe:
onmouseup
(I'm not sure about this one)Here's a simple example :
Process.Start("cmd","/C copy c:\\file.txt lpt1");
I had a similar issue where visual studio keeps loading symbol and got stuck.
It turns out I added some "Command line arguments" in the Debug options, and one of the parameters is invalid(I am supposed to pass in some values).
After I remove the extra parameter, it starts working again.
I like working with python object built-in types keys or values.
For attributes regardless they are methods or variables:
o.keys()
For values of those attributes:
o.values()
Do somthing like this by adding these line to your view files;
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file'); Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');
Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:
<!-- <content> blah </content> -->
You can take two approaches here:
Be careful.
I am also not so sure you can match all new lines at once. @Quartz suggested this one:
<content>([^\n]*\n+)+</content>
This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:
<content>.*</content>
BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.
I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.
I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...
UPDATE 1:
Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):
To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.
Similarly, to search for content tags, use: .*?
Also, You may be able to try this out, and access each newline character with the match objects groups():
<content>(.*?(\n))+.*?</content>
I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.
UPDATE 2:
So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:
#!/usr/bin/python
import re
def FindContentNewlines(xml_text):
# May want to compile these regexes elsewhere, but I do it here for brevity
comments = re.compile(r"<!--.*?-->", re.DOTALL)
content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)
# strip comments: this actually may not be reliable for "nested comments"
# How does xml handle <!-- <!-- --> -->. I am not sure. But that COULD
# be trouble.
xml_text = re.sub(comments, "", xml_text)
result = []
all_contents = re.findall(content, xml_text)
for c in all_contents:
result.extend(re.findall(newlines, c))
return result
if __name__ == "__main__":
example = """
<!-- This stuff
ought to be omitted
<content>
omitted
</content>
-->
This stuff is good
<content>
<p>
haha!
</p>
</content>
This is not found
"""
print FindContentNewlines(example)
This program prints the result:
['', '<p>', ' haha!', '</p>', '']
The first and last empty strings come from the newline chars immediately preceeding the first <p>
and the one coming right after the </p>
. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.
Hope this helps :-).
PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.
update:
React Router v5 with hooks:
import React from 'react';
import { useHistory } from "react-router-dom";
function LoginLayout() {
const history = useHistory();
const routeChange = () =>{
let path = `newPath`;
history.push(path);
}
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
export default LoginLayout;
with React Router v5:
import { useHistory } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink } from 'reactstrap';
class LoginLayout extends Component {
routeChange=()=> {
let path = `newPath`;
let history = useHistory();
history.push(path);
}
render() {
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={this.routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}
export default LoginLayout;
with React Router v4:
import { withRouter } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row, NavLink } from 'reactstrap';
class LoginLayout extends Component {
constuctor() {
this.routeChange = this.routeChange.bind(this);
}
routeChange() {
let path = `newPath`;
this.props.history.push(path);
}
render() {
return (
<div className="app flex-row align-items-center">
<Container>
...
<Row>
<Col xs="6">
<Button color="primary" className="px-4"
onClick={this.routeChange}
>
Login
</Button>
</Col>
<Col xs="6" className="text-right">
<Button color="link" className="px-0">Forgot password?</Button>
</Col>
</Row>
...
</Container>
</div>
);
}
}
export default withRouter(LoginLayout);
Contains information about how to fetch a resource from its location. For example:
http://example.com/mypage.html
ftp://example.com/download.zip
mailto:[email protected]
file:///home/user/file.txt
http://example.com/resource?foo=bar#fragment
/other/link.html
(A relative URL, only useful in the context of another URL)URLs always start with a protocol (http
) and usually contain information such as the network host name (example.com
) and often a document path (/foo/mypage.html
). URLs may have query parameters and fragment identifiers.
Identifies a resource by name. It always starts with the prefix urn:
For example:
urn:isbn:0451450523
to identify a book by its ISBN number.urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
a globally unique identifierurn:publishing:book
- An XML namespace that identifies the document as a type of book.URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.
URIs encompasses both URLs, URNs, and other ways to indicate a resource.
An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World
. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.
There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/
. A URC is another type of URI that is neither URL nor URN.
The w3 spec for HTML says that the href
of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">
. Your browser would then resolve that URN to a URL and download the book for you.
Not that I know of, but modern web browser do implement the data URI scheme.
Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn:
which is not a valid network protocol.
No. Both relative and absolute URLs are URLs (and URIs.)
No. Both URLs with and without query parameters are URLs (and URIs.)
No. Both URLs with and without fragment identifiers are URLs (and URIs.)
tel:
URI a URL or a URN?For example tel:1-800-555-5555
. It doesn't start with urn:
and it has a protocol for reaching a resource over a network. It must be a URL.
Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
it's simple just type : $facebook->setSession(null); for logout
you can call privite api like this ,apple ignore:
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; SEL sel = NSSelectorFromString(@"firstResponder"); UIView *firstResponder = [keyWindow performSelector:sel];
DriverManager
is a fairly old way of doing things. The better way is to get a DataSource
, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
So a Mixed Solution from @nvdo and @Abdelhameed Mahmoud worked for me
footer {
position: sticky;
height: 100px;
top: calc( 100vh - 100px );
}
more info here: http://code.google.com/apis/maps/documentation/geocoding/
For 2.3 seconds you should do:
System.Threading.Thread.Sleep(2300);
I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.
I use this
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version>
</plugin>
Typically you model the enum itself as a class with the enum
stereotype
If you want to guarantee the same order regardless of the order of elements in the input array, here is a stable sorting:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
It's simple enough when you find out.
Open /etc/hosts
(unix) or C:\WINDOWS\system32\drivers\etc\hosts
.
If your domain is foo.com, then add this line:
127.0.0.1 local.foo.com
When you are testing, open local.foo.com
in your browser and it should work.
http://www.codeproject.com/KB/cs/SingleInstancingWithIpc.aspx
Controller
[HttpGet]
public async Task<ActionResult> Index(int page =1)
{
if (page < 0 || page ==0 )
{
page = 1;
}
int pageSize = 5;
int totalPage = 0;
int totalRecord = 0;
BusinessLayer bll = new BusinessLayer();
MatchModel matchmodel = new MatchModel();
matchmodel.GetMatchList = bll.GetMatchCore(page, pageSize, out totalRecord, out totalPage);
ViewBag.dbCount = totalPage;
return View(matchmodel);
}
BusinessLogic
public List<Match> GetMatchCore(int page, int pageSize, out int totalRecord, out int totalPage)
{
SignalRDataContext db = new SignalRDataContext();
var query = new List<Match>();
totalRecord = db.Matches.Count();
totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
query = db.Matches.OrderBy(a => a.QuestionID).Skip(((page - 1) * pageSize)).Take(pageSize).ToList();
return query;
}
View for displaying total page count
if (ViewBag.dbCount != null)
{
for (int i = 1; i <= ViewBag.dbCount; i++)
{
<ul class="pagination">
<li>@Html.ActionLink(@i.ToString(), "Index", "Grid", new { page = @i },null)</li>
</ul>
}
}
With ES6 you can write this:
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('<ul>', { class: "mylist" }).append(
countries.map(country =>
$("<li>").append($("<a>").text(country))
)
);
Something like this:
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
var select = document.getElementById("id-to-my-select-box");
select.appendChild(option);
I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).
The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)
Observable
/*
function geo_success(position) {
do_something(position.coords.latitude, position.coords.longitude);
}
function geo_error() {
alert("Sorry, no position available.");
}
var geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
*/
getLocation(): Observable<Position> {
return Observable.create((observer) => {
const watchID = navigator.geolocation.watchPosition((position: Position) => {
observer.next(position);
});
return () => {
navigator.geolocation.clearWatch(watchID);
};
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
I faced the same problem while using angular 11. But finally found a solution.
<option disabled selected value="undefined">Select an Option</option>
complete example with ngFor.
<select name="types" id="types" [(ngModel)]="model.type" #type="ngModel">
<option class="" disabled selected value="undefined">Select an Option</option>
<option *ngFor="let item of course_types; let x = index" [ngValue]="type.id">
{{ item.name }} </option>
</select>
Hudson can be configured to ignore changes to certain paths and files so that it does not prompt a new build.
On the job configuration page, under Source Code Management, click the Advanced button. In the Excluded Regions box you enter one or more regular expression to match exclusions.
For example to ignore changes to the version.properties file you can use:
/MyProject/trunk/version.properties
This will work for languages other than C# and allows you to store your version info within subversion.
After you determine that a number is composite (not prime), your work is done. You can exit the loop with break
.
while num > a :
if num%a==0 & a!=num:
print('not prime')
break # not going to update a, going to quit instead
else:
print('prime')
a=(num)+1
Also, you might try and become more familiar with some constructs in Python. Your loop can be shortened to a one-liner that still reads well in my opinion.
any(num % a == 0 for a in range(2, num))
onclick="this.focus();this.select()"
For multiple files input using lodash or underscore:
.directive("fileread", [function () {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
return _.map(changeEvent.target.files, function(file){
scope.fileread = [];
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
scope.fileread.push(loadEvent.target.result);
});
}
reader.readAsDataURL(file);
});
});
}
}
}]);
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
I know I'm a little late, but something I found that works (and doesn't require using csv
) is to write a for loop that writes to your file for every element in your list.
# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']
# Open File
resultFyle = open("output.csv",'w')
# Write data to file
for r in RESULTS:
resultFyle.write(r + "\n")
resultFyle.close()
I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.
On Windows:
CHDIR Displays the name of or changes the current directory.
In Linux:
PWD Displays the name of current directory.
I also prefer an enum approach, but I would use a abstract base class to force the subclasses to implement the getType()
method.
public abstract class Base
{
protected enum TYPE
{
DERIVED_A, DERIVED_B
}
public abstract TYPE getType();
class DerivedA extends Base
{
@Override
public TYPE getType()
{
return TYPE.DERIVED_A;
}
}
class DerivedB extends Base
{
@Override
public TYPE getType()
{
return TYPE.DERIVED_B;
}
}
}
Let's make this a little easier on ourselves and just use a module...
Try: pip install compago
Then write:
import compago
app = compago.Application()
@app.command
def hello():
print "hi there!"
@app.command
def goodbye():
print "see ya later."
if __name__ == "__main__":
app.run()
Then use like so:
$ python test.py hello
hi there!
$ python test.py goodbye
see ya later.
Note: There's a bug in Python 3 at the moment, but works great with Python 2.
Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire
. From their GitHub:
Here's a simple example.
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Then, from the command line, you can run:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
Work for me in CentOS:
$ service mysql stop
$ mysqld --skip-grant-tables &
$ mysql -u root mysql
mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
$ service mysql restart
npm set registry http://85.10.209.91/
(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).
The other solutions seem to have outdated versions.
If you want to pass class instances (objects), you either use
void function(const MyClass& object){
// do something with object
}
or
void process(MyClass& object_to_be_changed){
// change member variables
}
On the other hand if you want to "pass" the class itself
template<class AnyClass>
void function_taking_class(){
// use static functions of AnyClass
AnyClass::count_instances();
// or create an object of AnyClass and use it
AnyClass object;
object.member = value;
}
// call it as
function_taking_class<MyClass>();
// or
function_taking_class<MyStruct>();
with
class MyClass{
int member;
//...
};
MyClass object1;
Yes. There is a simple way to remove everything in iPython. In iPython console, just type:
%reset
Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:
%reset -f
This should work..
There are a wide varieties of solutions to this problem documented here, including this little gem:
CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
I've gotten the same issue and one of the posted example in the manual worked. A character set must be specified as one of the posters here already mentioned. http://www.php.net/manual/en/function.ob-flush.php#109314
header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
echo $i . '<br />';
flush();
ob_flush();
sleep(1);
}
echo 'End ...<br />';
I solved Using:
Dictionary<short, string[]>
Like this
Dictionary<short, string[]> result = new Dictionary<short, string[]>();
result.Add(1,
new string[]
{
"FirstString",
"Second"
}
);
}
return result;
This problem due to that you try to compile project that has the files of OLder SVN than you currently use.
You have two solutions to resolve this problem
User.FindFirst(ClaimTypes.NameIdentifier).Value
EDIT for constructor
Below code works:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
Edit for RTM
You should register IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}
I had the exact same problem and solved it running the folowing command from the command line as an admin :
1) first stop the service with the following
net stop http /y
2) then disable the startup (optional)
sc config http start= disabled
Just for completeness, the || and && are the conditional version of the | and & operators.
A reference to the ECMA C# Language specification is here.
From the specification:
3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
In the |
version both sides are evaluated.
The conditional version short circuits evaluation and so allows for code like:
if (x == null || x.Value == 5)
// Do something
Or (no pun intended) using your example:
if (title == "User greeting" || title == "User name")
// {do stuff}
How and where is
app.run()
used? After module definition or afterapp.config()
, afterapp.controller()
?
In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js
Make it look like this
var app = angular.module('mean.dashboard', ['ui.bootstrap']);
app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
function($scope, Global, Dashboard) {
$scope.global = Global;
$scope.package = {
name: 'dashboard'
};
// ...
}
]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
For Windows Vista and Windows 7 you need to get the Remote Server Administration Tools (RSAT) - the Active Directory Users & Computers Snap-In is included in that pack. Download link: Remote Server Administration Tools for Windows 7.
TypeScript v3.7.3
export enum YourEnum {
enum1 = 'enum1',
enum2 = 'enum2',
enum3 = 'enum3',
}
const status = 'enumnumnum';
if (!(status in YourEnum)) {
throw new UnprocessableEntityResponse('Invalid enum val');
}
From the menu:
Build|Generate Signed APK
or
Build|Build APK
(the latter if you don't need a signed one to publish to the Play Store)
You can to use split to do it:
String[] elements = s.split(",");
for(String s1: elements) {
String[] keyValue = s1.split(":");
myMap.put(keyValue[0], keyValue[1]);
}
Nevertheless, myself I will go for guava based solution. https://stackoverflow.com/a/10514513/1356883
if it's background, use background-size: cover;
body{_x000D_
background-image: url('http://i.stack.imgur.com/kx8MT.gif');_x000D_
background-size: cover;_x000D_
_x000D_
_x000D_
_x000D_
height: 100vh;_x000D_
padding:0;_x000D_
margin:0;_x000D_
}
_x000D_
-apple-system allows you to pick San Francisco in Safari. BlinkMacSystemFont is the corresponding alternative for Chrome.
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
Roboto or Helvetica Neue could be inserted as fallbacks even before sans-serif.
https://www.smashingmagazine.com/2015/11/using-system-ui-fonts-practical-guide/#details-of-approach-a (how or previously http://furbo.org/2015/07/09/i-left-my-system-fonts-in-san-francisco/ do a great job explaining the details.
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
I copy-pasted the whole pdf in a text editor and got something like:
...
31 Netherlands (Kingdom of the)
32 Belgium
33 France
34 Spain
350 Gibraltar
351 Portugal
352 Luxembourg
353 Ireland
354 Iceland
...
You could easily parse this to create a xml :)
Github blog spoke yesterday about Egit plugin:
This is by no means exhaustive advice. But number one thing to keep in mind when writing with the thought of avoiding future memory leaks (loops) is to make sure that anything which accepts a reference to a call-back, should store that call-back as a weak reference.
AndroChef Java Decompiler produces very good code that you can use directly in your projects...
This is expected.
Refer to Javadocs for split
.
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
1. Set a limited size on the key field ex. nvarchar(100)
2. Create a check constraint that compares the value with all the keys in the table.
The condition is:
([dbo].[CheckKey]([key])=(1))
and [dbo].[CheckKey] is a scalar function defined as:
CREATE FUNCTION [dbo].[CheckKey]
(
@key nvarchar(max)
)
RETURNS bit
AS
BEGIN
declare @res bit
if exists(select * from key_value where [key] = @key)
set @res = 0
else
set @res = 1
return @res
END
But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.
WITH NOCHECK
is used as well when one has existing data in a table that doesn't conform to the constraint as defined and you don't want it to run afoul of the new constraint that you're implementing...
Are you sure that floated block-level elements are the best solution to this problem?
Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.
Just download the apk from talkback website
Drag the downloaded apk to the started emulator, Go to settings on emulator > Search for talkback, you will now find it there
Those who updated their device to Android 4.2 Jelly Bean or higher or having a 4.2 JB or higher android powered device, will not found the Developers Options in Settings menu. The Developers Options hide by default on 4.2 jelly bean and later android versions. Follow the below steps to Unhide Developers Options.
Go to Settings>> More/General tab>> About (On Samsung Galaxy S3, Galaxy S4, Galaxy Note 8.0, Galaxy Tab 3 and other galaxy Smartphone and tablet having Android 4.2/4.3 Jelly Bean) OR
Go to Settings>> General>> About (On Samsung Galaxy Note 2, Galaxy Note 3 and some other Galaxy devices having Android 4.3 Jelly Bean or 4.4 KitKat) OR
Go to Settings> About> Software Information> More (On HTC One or other HTC devices having Android 4.2 Jelly Bean or higher) 2. Now Scroll onto Build Number and tap it 7 times repeatedly. A message will appear saying that u are now a developer.
Credit to www.androidofficer.com
You might want to modify your jQuery code a bit to '#demolist li a'
so it specifically selects the text that is in the link rather than the text that is in the li element. That would allow you to have a sub-menu without causing issues. Also since your are specifically selecting the a tag you can access it with $(this).text();
.
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
Documentation of Math.round
says:
Returns the result of rounding the argument to an integer. The result is equivalent to
(int) Math.floor(f+0.5)
.
No need to cast to int
. Maybe it was changed from the past.
If you have the luxury of working in C++, use this:
template<typename T>
void swapPrimitives(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
Granted, in the case of char*
, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?
Or you can do this:
<table>
<tr>
<td><b>Return:</b></td>
<td><input id="return1" name='return1'
class=" input input-sm" style="width:150px"
type="text" value='8/28/2013'></td>
</tr>
</table>
I tried every one of the suggestions above and none of them worked. I don't want to pick a fixed number of columns in the 12 column grid. I want the prompt, and the input right after it, and I want the columns to stretch as needed.
Yes, I know, that is against what bootstrap is all about. And you should NEVER use a table. Because DIV is so much better than tables. But the problem is that tables, rows, and cells actually WORK.
YES - I REALLY DO know that there are CSS zealots, and the knee-jerk reaction is never never never use TABLE, TR, and TD. Yes, I do know that DIV class="table" with DIV class="row" and DIV class="cell" is much much better. Except when it doesn't work, and there are many cases. I don't believe that people should blindly ignore those situations. There are times that the TABLE/TR/TD will work just fine, and there is not reason to use a more complicated and more fragile approach just because it is considered more elegant. A developer should understand what the benefits of the various approaches are, and the tradeoffs, and there is no absolute rule that DIVs are better.
"Case in point - based on this discussion I converted a few existing tds and trs to divs. 45 minutes messing about with it trying to get everything to line up next to each other and I gave up. TDs back in 10 seconds later - works - straight away - on all browsers, nothing more to do. Please try to make me understand - what possible justification do you have for wanting me to do it any other way!" See [https://stackoverflow.com/a/4278073/1758051]
And this: "
Layout should be easy. The fact that there are articles written on how to achieve a dynamic three column layout with header and footer in CSS shows that it is a poor layout system. Of course you can get it to work, but there are literally hundreds of articles online about how to do it. There are pretty much no such articles for a similar layout with tables because it's patently obvious. No matter what you say against tables and in favor of CSS, this one fact undoes it all: a basic three column layout in CSS is often called "The Holy Grail"." [https://stackoverflow.com/a/4964107/1758051]
I have yet to see a way to force DIVs to always line up in a column in all situations. I keep getting shown trivial examples that don't really run into the problems. "Responsive" is about providing a way that they will not always line up in a column. However, if you really want a column, you can waste hours trying to get DIV to work. Sometimes, you need to use appropriate technology no matter what the zealots say.
I use runjs
like:
runjs example.js
The package is called just run
npm install -g run
you could use getAttribute:
var p = document.getElementById("p");
var alignP = p.getAttribute("align");
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
I found the easiest way to locate it, you can use
which python
it will show something like this:
/usr/bin/python
Would not \\(.*?\\)
work? That is the non-greedy syntax.
This doesn't work for me. I've tried this both under Win7 64bit and Vista 32.
I'm using the below commandline to add this capability.
reg add "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v AutoRun /t REG_SZ /d "IF x"%COMSPEC%"==x%CMDCMDLINE% (cd /D c:)"
For Windows 10 x64
and Python
:
Open a Visual Studio x64 command prompt, and use dumpbin:
dumpbin /dependents [Python Module DLL or PYD file]
If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.
Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.
I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.
It was giving this error: ImportError: DLL load failed: The specified module could not be found
Opened a Visual Studio x64 command prompt.
Under Windows, a .pyd
file is a .dll
file in disguise, so we want to run dumpbin on this file.
cd MyLibrary\build\lib.win-amd64-3.7\Debug
dumpbin /dependents MyLibrary.cp37-win_amd64.pyd
which prints this:
Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file MyLibrary.cp37-win_amd64.pyd
File Type: DLL
Image has the following dependencies:
clang_rt.asan_dbg_dynamic-x86_64.dll
gtestd.dll
tbb_debug.dll
python37.dll
KERNEL32.dll
MSVCP140D.dll
VCOMP140D.DLL
VCRUNTIME140D.dll
VCRUNTIME140_1D.dll
ucrtbased.dll
Summary
1000 .00cfg
D6000 .data
7000 .idata
46000 .pdata
341000 .rdata
23000 .reloc
1000 .rsrc
856000 .text
Searched for clang_rt.asan_dbg_dynamic-x86_64.dll
, copied it into the same directory, problem solved.
Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.
Please feel free to add your own case studies here! I've made it a community wiki answer.
If you have the coreutils package installed you can generally use readlink -f relative_file_name
in order to retrieve the absolute one (with all symlinks resolved)
you can use this in terminal or shell
adb shell install -g MyApp.apk
see more in develope google
The other way to fix this in other circumstances is to use NODE_TLS_REJECT_UNAUTHORIZED=0
as an environment variable
NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js
WARNING: This is a bad idea security-wise
You can change your the Build Target for your project at any time:
Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.
Edit the following elements in the AndroidManifest.xml file (it is in your project root directory)
In this case, that will be:
<uses-sdk android:minSdkVersion="3" />
<uses-sdk android:targetSdkVersion="8" />
Save it
Rebuild your project.
Click the Project on the menu bar, select Clean...
Now, run the project again.
Right Click Project name, move on Run as, and select Android Application
By the way, reviewing Managing Projects from Eclipse with ADT will be helpful. Especially the part called Creating an Android Project.
if you are using spring security then you can get the current logged in user by
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
That's a good question. I'd love to say “yes”. I can't.
JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.
(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)
However, in reality this isn't quite true, in sneaky nasty ways.
The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
l.value+= 'log in\n';_x000D_
l.focus();_x000D_
l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
Results in log in, blur, log out
on all except IE. These events don't just fire because you called focus()
directly, they could happen because you called alert()
, or opened a pop-up window, or anything else that moves the focus.
This can also result in other events. For example add an i.onchange
listener and type something in the input before the focus()
call unfocuses it, and the log order is log in, change, blur, log out
, except in Opera where it's log in, blur, log out, change
and IE where it's (even less explicably) log in, change, log out, blur
.
Similarly calling click()
on an element that provides it calls the onclick
handler immediately in all browsers (at least this is consistent!).
(I'm using the direct on...
event handler properties here, but the same happens with addEventListener
and attachEvent
.)
There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
l.value+= 'alert in\n';_x000D_
alert('alert!');_x000D_
l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
Hit alert
and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out
in the textarea.
You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.
You might think, well, it's only resize
(and probably a few more like scroll
) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.
Places where events that you can cause to be generated can be raised whilst script is still threaded:
when the modal popups (alert
, confirm
, prompt
) are open, in all browsers but Opera;
during showModalDialog
on browsers that support it;
the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.
a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).
probably more. It's been a while since I tested this and browsers have gained complexity since.
In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.
If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval
function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage
will also hopefully soothe the pain of cross-document scripting in the future.
I use VS 2017. By default SQL Server Instance name is (LocalDB)\MSSQLLocalDB. However, downgrading the compatibility level of the database to 110 as in @user3390927's answer, I could attach the database file in VS, choosing Server Name as "localhost\SQLExpress".
We monitor this from the application code, just to include the time required to establish/close the connection and transmit data across the network. It's pretty straight-forward...
Dim Duration as TimeSpan Dim StartTime as DateTime = DateTime.Now 'Call the database here and execute your SQL statement Duration = DateTime.Now.Subtract(StartTime) Console.WriteLine(String.Format("Query took {0} seconds", Duration.TotalSeconds.ToString())) Console.ReadLine()
Root node is the DocumentElement
property of XmlDocument
XmlElement root = xmlDoc.DocumentElement
If you only have the node, you can get the root node by
XmlElement root = xmlNode.OwnerDocument.DocumentElement
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
I think this is what you are looking for -
select Address1+Address2 as CompleteAddress from YourTable
where Address1+Address2 like '%YourSearchString%'
To prevent a compound word being created when we append address1 with address2, you can use this -
select Address1 + ' ' + Address2 as CompleteAddress from YourTable
where Address1 + ' ' + Address2 like '%YourSearchString%'
So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.
In VB.NET using Function,
Dim query = From order In dc.Orders
From vendor In
dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
From status In
dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
Select Order = order, Vendor = vendor, Status = status
You can do it by using the td's index:
var tdIndex = $td.index() + 1;
var $th = $('#table tr').find('th:nth-child(' + tdIndex + ')');
Just in case you have a nullable property in your class object:
private static DataTable ConvertToDatatable<T>(List<T> data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
else
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
I would suggest adding stdout
and stderr
file in systemd service
file itself.
Referring : https://www.freedesktop.org/software/systemd/man/systemd.exec.html#StandardOutput=
As you have configured it should not like:
StandardOutput=/home/user/log1.log
StandardError=/home/user/log2.log
It should be:
StandardOutput=file:/home/user/log1.log
StandardError=file:/home/user/log2.log
This works when you don't want to restart the service again and again.
This will create a new file and does not append to the existing file.
Use Instead:
StandardOutput=append:/home/user/log1.log
StandardError=append:/home/user/log2.log
NOTE: Make sure you create the directory already. I guess it does not support to create a directory.
You can use componentWillReceiveProps.
constructor(props) {
super(props);
this.state = {
productdatail: ''
};
}
componentWillReceiveProps(nextProps){
this.setState({ productdatail: nextProps.productdetailProps })
}
You are missing setter for salt
property as indicated by the exception
Please add the setter as
public void setSalt(long salt) {
this.salt=salt;
}
Note that, image slicing is not creating a copy of the cropped image
but creating a pointer
to the roi
. If you are loading so many images, cropping the relevant parts of the images with slicing, then appending into a list, this might be a huge memory waste.
Suppose you load N images each is >1MP
and you need only 100x100
region from the upper left corner.
Slicing
:
X = []
for i in range(N):
im = imread('image_i')
X.append(im[0:100,0:100]) # This will keep all N images in the memory.
# Because they are still used.
Alternatively, you can copy the relevant part by .copy()
, so garbage collector will remove im
.
X = []
for i in range(N):
im = imread('image_i')
X.append(im[0:100,0:100].copy()) # This will keep only the crops in the memory.
# im's will be deleted by gc.
After finding out this, I realized one of the comments by user1270710 mentioned that but it took me quite some time to find out (i.e., debugging etc). So, I think it worths mentioning.
Write a Vim function in .vimrc using the searchpair
built-in function:
searchpair({start}, {middle}, {end} [, {flags} [, {skip}
[, {stopline} [, {timeout}]]]])
Search for the match of a nested start-end pair. This can be
used to find the "endif" that matches an "if", while other
if/endif pairs in between are ignored.
[...]
"
git fetch
" (hence "git pull
" as well) learned to check "fetch.prune
" and "remote.*.prune
" configuration variables and to behave as if the "--prune
" command line option was given.
That means that, if you set remote.origin.prune to true:
git config remote.origin.prune true
Any git fetch
or git pull
will automatically prune.
Note: Git 2.12 (Q1 2017) will fix a bug related to this configuration, which would make git remote rename
misbehave.
See "How do I rename a git remote?".
See more at commit 737c5a9:
Without "
git fetch --prune
", remote-tracking branches for a branch the other side already has removed will stay forever.
Some people want to always run "git fetch --prune
".To accommodate users who want to either prune always or when fetching from a particular remote, add two new configuration variables "
fetch.prune
" and "remote.<name>.prune
":
- "
fetch.prune
" allows to enable prune for all fetch operations.- "
remote.<name>.prune
" allows to change the behaviour per remote.The latter will naturally override the former, and the
--[no-]prune
option from the command line will override the configured default.Since
--prune
is a potentially destructive operation (Git doesn't keep reflogs for deleted references yet), we don't want to prune without users consent, so this configuration will not be on by default.
It is because the Creation was delayed. If you want the picture to be loaded immediately, you can simply add this code into the init phase.
src.CacheOption = BitmapCacheOption.OnLoad;
like this:
src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
Supported in latest chrome, opera and safari, you can do this:
-webkit-clip-path: inset(0 0 0 0 round 100px);
clip-path: inset(0 0 0 0 round 100px);
You should definitely check out the tool http://bennettfeely.com/clippy/!
seeing it in digital circuit domain
so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment
Actually, axios.delete
supports a request body.
It accepts two parameters: a URL
and an optional config
. That is...
axios.delete(url: string, config?: AxiosRequestConfig | undefined)
You can do the following to set the response body for the delete request:
let config = {
headers: {
Authorization: authToken
},
data: { //! Take note of the `data` keyword. This is the request body.
key: value,
... //! more `key: value` pairs as desired.
}
}
axios.delete(url, config)
I hope this helps someone!
But,if you want to store a bunch of them you could bit-shift them and store them all as one int, a little like unix file permissions/modes.
For mode 755 for instance, each digit refers to a different class of users: owner, group, public. Within each digit 4 is read, 2 is write, 1 is execute so 7 is all of them like binary 111. 5 is read and execute so 101. Make up your own encoding scheme.
I'm just writing something for storing TV schedule data from Schedules Direct and I have the binary or yes/no fields: stereo, hdtv, new, ei, close captioned, dolby, sap in Spanish, season premiere. So 7 bits, or an integer with a maximum of 127. One character really.
A C example from what I'm working on now. has() is a function that returns 1 if the 2nd string is in the first one. inp is the input string to this function. misc is an unsigned char initialized to 0.
if (has(inp,"sap='Spanish'") > 0)
misc += 1;
if (has(inp,"stereo='true'") > 0)
misc +=2;
if (has(inp,"ei='true'") > 0)
misc +=4;
if (has(inp,"closeCaptioned='true'") > 0)
misc += 8;
if (has(inp,"dolby=") > 0)
misc += 16;
if (has(inp,"new='true'") > 0)
misc += 32;
if (has(inp,"premier_finale='") > 0)
misc += 64;
if (has(inp,"hdtv='true'") > 0)
misc += 128;
So I'm storing 7 booleans in one integer with room for more.
If you set your Form
's AcceptButton
property to one of the Button
s on the Form
, you'll get that behaviour by default.
Otherwise, set the KeyPreview
property to true
on the Form
and handle its KeyDown
event. You can check for the Enter
key and take the necessary action.
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
Use the change event of the select:
$('#my_select').change(function()
{
$(this).parents('td').css('background', '#000000');
});
The following should work:
ABC: *\([a-zA-Z]+\) *(.+)
Explanation:
ABC: # match literal characters 'ABC:'
* # zero or more spaces
\([a-zA-Z]+\) # one or more letters inside of parentheses
* # zero or more spaces
(.+) # capture one or more of any character (except newlines)
To get your desired grouping based on the comments below, you can use the following:
(ABC:) *(\([a-zA-Z]+\).+)
This can be as simple as:
SQL> ALTER SYSTEM ENABLE RESTRICTED SESSION;
SQL> DROP USER test CASCADE;
SQL> ALTER SYSTEM DISABLE RESTRICTED SESSION;
You can actually simplify this by removing the v-on
directives:
<input type="radio" name="optionsRadios" id="optionsRadios1" value="1" v-model="srStatus">
And use the watch
method to listen for the change:
new Vue ({
el: "#app",
data: {
cases: [
{ name: 'case A', status: '1' },
{ name: 'case B', status: '0' },
{ name: 'case C', status: '1' }
],
activeCases: [],
srStatus: ''
},
watch: {
srStatus: function(val, oldVal) {
for (var i = 0; i < this.cases.length; i++) {
if (this.cases[i].status == val) {
this.activeCases.push(this.cases[i]);
alert("Fired! " + val);
}
}
}
}
});
select convert(varchar(10), cast(fmdate as date), 101) from sery
Without cast I was not getting fmdate converted, so fmdate was a string.
I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!
$('button').toggle(
function() {
$('#B').css('left', '0')
}, function() {
$('#B').css('left', '200px')
})
You can also see any animated version at http://jsfiddle.net/hThGb/2/
Another simpler option is to do:
> x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
> x[x==1] <- 0
> x
[1] 0 0 2 4 5 2 0 3 2
You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:
User-defined functions cannot be used to perform actions that modify the database state.
"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).
You should be using a stored procedure, not a function.
I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.
Here is an easy example of how to kill all Word Processes.
Process[] procs = Process.GetProcessesByName("winword");
foreach (Process proc in procs)
proc.Kill();
If you have the flutter SDK installed.
Run:
flutter doctor -v
The first line will show the install path..
(if you don't have it installed go to the documentation)
I think what you are looking for is as follows.
cars_by_cylinders_gears <- mtcars %>%
group_by(cyl, gear) %>%
summarise(count = n())
This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.
It's for both for Horizontal and for Vertical.
RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_recycler);
recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);
RecyclAdapter adapter = new RecyclAdapter();
//Vertical RecyclerView
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
//Horizontal RecyclerView
//recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
}
MATLAB, as mentioned by others, is great at matrix manipulation, and was originally built as an extension of the well-known BLAS and LAPACK libraries used for linear algebra. It interfaces well with other languages like Java, and is well favored by engineering and scientific companies for its well developed and documented libraries. From what I know of Python and NumPy, while they share many of the fundamental capabilities of MATLAB, they don't have the full breadth and depth of capabilities with their libraries.
Personally, I use MATLAB because that's what I learned in my internship, that's what I used in grad school, and that's what I used in my first job. I don't have anything against Python (or any other language). It's just what I'm used too.
Also, there is another free version in addition to scilab mentioned by @Jim C from gnu called Octave.
df.index
Index
object. list(df.index)
df.index['Row 2':'Row 5']
Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.
Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.
$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
var str = $("#s2id_search_code .select2-choice span").text();
DOSelectAjaxProd(e.val, str);
});
If you want to concatenate the fields using / as a separator, you can use concat_ws
:
select concat_ws('/', col1, col2, col3) from mytable
You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.
even simpler, adding up to String[]
,
use built-in filter filter(StringUtils::isNotEmpty)
of org.apache.commons.lang3
import org.apache.commons.lang3.StringUtils;
String test = "a\nb\n\nc\n";
String[] lines = test.split("\\n", -1);
String[] result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
System.out.println(Arrays.toString(lines));
System.out.println(Arrays.toString(result));
and output:
[a, b, , c, ]
[a, b, c]
Run taskmanager
.
Locate netcore
and delete it.
You can then delete the file manually or by running Clean
.
I know this question was old, but I wanted a solution that doesn't involve libraries outside those included JRE6 (i.e. Apache Commons is not acceptable), and I came up with a simple solution using the built-in java.io.StreamTokenizer
:
import java.io.*;
// ...
String literal = "\"Has \\\"\\\\\\\t\\\" & isn\\\'t \\\r\\\n on 1 line.\"";
StreamTokenizer parser = new StreamTokenizer(new StringReader(literal));
String result;
try {
parser.nextToken();
if (parser.ttype == '"') {
result = parser.sval;
}
else {
result = "ERROR!";
}
}
catch (IOException e) {
result = e.toString();
}
System.out.println(result);
Output:
Has "\ " & isn't
on 1 line.
In regards to your error and what's missing in your code. m
is a name which is not defined for getmd5()
function.
No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)
First, you are not using hashlib.md5.hexdigest()
method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:
>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'
However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:
>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'
As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.
A simple solution could be something like that:
# Import hashlib library (md5 method is part of it)
import hashlib
# File to check
file_name = 'filename.exe'
# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'
# Open,close, read file and calculate MD5 on its contents
with open(file_name) as file_to_check:
# read contents of the file
data = file_to_check.read()
# pipe contents of the file through
md5_returned = hashlib.md5(data).hexdigest()
# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
print "MD5 verified."
else:
print "MD5 verification failed!."
Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.
Best of luck.
Here is something else I found:
After I have the "prefs" URL Scheme defined, "prefs:root=Safari&path=ContentBlockers" is working on Simulator (iOS 9.1 English), but not working on Simulator (Simplified Chinese). It just jump to Safari, but not Content Blockers. If your app is international, be careful.
Update: Don't know why, now I can't jump into ContentBlockers anymore, the same code, the same version, doesn't work now. :(
On real devcies (mine is iPhone 6S & iPad mini 2), "Safari" should be "SAFARI", "Safari" not working on real device, "SAFARI" now working on simulator:
#if arch(i386) || arch(x86_64)
// Simulator
let url = NSURL(string: "prefs:root=Safari")!
#else
// Device
let url = NSURL(string: "prefs:root=SAFARI")!
#endif
if UIApplication.sharedApplication().canOpenURL(url) {
UIApplication.sharedApplication().openURL(url)
}
So far, did not find any differences between iPhone and iPad.
If you're looking to do something with a list of files, you can use find combined with the bash $()
construct (better than backticks since it's allowed to nest).
for example, say you're at the top level of your project directory and you want a list of all C files starting with "btree". The command:
find . -type f -name 'btree*.c'
will return a list of them. But this doesn't really help with doing something with them.
So, let's further assume you want to search all those file for the string "ERROR" or edit them all. You can execute one of:
grep ERROR $(find . -type f -name 'btree*.c')
vi $(find . -type f -name 'btree*.c')
to do this.
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });
Worked perfectly for what i needed. Thanks vol7ron
private void fillFilesRecursively(File file, List<File> resultFiles) {
if (file.isFile()) {
resultFiles.add(file);
} else {
for (File child : file.listFiles()) {
fillFilesRecursively(child, resultFiles);
}
}
}
public static String ReverseString(String str)
{
int word_length = 0;
String result = "";
for (int i=0; i<str.Length; i++)
{
if (str[i] == ' ')
{
result = " " + result;
word_length = 0;
} else
{
result = result.Insert(word_length, str[i].ToString());
word_length++;
}
}
return result;
}
This is C# code.
yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate()));_x000D_
alert(yyyymmdd(new Date));
_x000D_
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I've been told they are the same.
Actually they are documented in the same place under ruby-doc.org:
http://www.ruby-doc.org/core/classes/Array.html#M000249
- ary.collect {|item| block } ? new_ary
- ary.map {|item| block } ? new_ary
- ary.collect ? an_enumerator
- ary.map ? an_enumerator
Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.a = [ "a", "b", "c", "d" ] a.collect {|x| x + "!" } #=> ["a!", "b!", "c!", "d!"] a #=> ["a", "b", "c", "d"]
The simple solution
SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field
Replace checked="checked"
with checked={true}
. Or you could even shorten it to just checked
.
This is because the expected value type of the checked
prop is a boolean. not a string.
Another option is to set height: 0; overflow: visible;
to an element, though it won't be really outside the flow and therefore may break margin collapsing.
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
No answer seems to deal with the OverflowException/UnderflowException that comes from trying to convert a decimal that is outside the range of int.
int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));
This solution will return the maximum or minimum int value possible if the decimal value is outside the int range. You might want to add some rounding with Math.Round, Math.Ceiling or Math.Floor for when the value is inside the int range.
When you are looking for your "local" address, you should note that each machine has not only a single network interface, and each interface could has its own local address. Which means your machine is always owning several "local" addresses.
Different "local" addresses will be automatically chosen to use when you are connecting to different endpoints. For example, when you connect to google.com
, you are using an "outside" local address; but when you connect to your localhost
, your local address is always localhost
itself, because localhost is just a loopback.
Below is showing how to find out your local address when you are communicating with google.com
:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
socket.close();
What is the database version? Check out virtual columns in 11g:
Adding Columns with a Default Value http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-schemamanagement.html
There's are multiple ways to split a string :
_
import net package
host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
Split based on struct :
_
type ServerDetail struct {
Host string
Port string
err error
}
ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port
Now use in you code like ServerDetail.Host
and ServerDetail.Port
If you don't want to split specific string do it like this:
type ServerDetail struct {
Host string
Port string
}
ServerDetail = strings.Split([Your_String], ":") // Common split method
and use like ServerDetail.Host
and ServerDetail.Port
.
That's All.
See below
Use the below code, If you are using excel 2007 or 2010 and want to reorder the legends only. Make sure mChartName matched with your chart name.
Sub ReverseOrderLegends()
mChartName = "Chart 1"
Dim sSeriesCollection As SeriesCollection
Dim mSeries As Series
With ActiveSheet
.ChartObjects(mChartName).Chart.SetElement (msoElementLegendNone)
.ChartObjects(mChartName).Chart.SetElement (msoElementLegendRight)
Set sSeriesCollection = .ChartObjects(mChartName).Chart.SeriesCollection
For Each mSeries In sSeriesCollection
If mSeries.Values(1) = 0.000000123 Or mSeries.Values(1) = Empty Then
mSeries.Delete
End If
Next mSeries
LegendCount = .ChartObjects(mChartName).Chart.SeriesCollection.Count
For mLegend = 1 To LegendCount
.ChartObjects(mChartName).Chart.SeriesCollection.NewSeries
.ChartObjects(mChartName).Chart.SeriesCollection(LegendCount + mLegend).Name = .ChartObjects(mChartName).Chart.SeriesCollection(LegendCount - mLegend + 1).Name
.ChartObjects(mChartName).Chart.SeriesCollection(LegendCount + mLegend).Values = "={0.000000123}"
.ChartObjects(mChartName).Chart.SeriesCollection(LegendCount + mLegend).Format.Fill.ForeColor.RGB = .ChartObjects(mChartName).Chart.SeriesCollection(LegendCount - mLegend + 1).Format.Fill.ForeColor.RGB
Next mLegend
For mLegend = 1 To LegendCount
.ChartObjects(mChartName).Chart.Legend.LegendEntries(1).Delete
Next mLegend
End With
End Sub
Use strtotime to convert any date to unix timestamp and compare.
Use System.Diagnostics.Process to launch an instance of Notepad.exe.
This worked for me. Simplest solution by far.
If you are using GitHub for Windows and getting this error, the problem might be that you are trying to run the command in the wrong shell or mode. If you are trying to do git push origin master
in the regular command prompt or PowerShell, this is the problem.
You need to do it in a git shell. Simply open Github for Windows, right click, and select "Open Shell Here". It looks like a regular PowerShell window, but it's not, which makes it really confusing for newbies to git, like myself.
I hope others find this useful.
corrected Code:
jQuery('#testID2').addClass('test3').removeClass('test2');
I just came across this question while searching for the solution for myself. You might consider calling the system beep function by running some kernel32 stuff.
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
public static extern bool Beep(int freq, int duration);
public static void TestBeeps()
{
Beep(1000, 1600); //low frequency, longer sound
Beep(2000, 400); //high frequency, short sound
}
This is the same as you would run powershell:
[console]::beep(1000, 1600)
[console]::beep(2000, 400)
Bootstrap 4.4:
Show a choose file
bar. After a file is chosen show the file name along with its extension
<div class="custom-file">
<input type="file" class="custom-file-input" id="idEditUploadVideo"
onchange="$('#idFileName').html(this.files[0].name)">
<label class="custom-file-label" id="idFileName" for="idEditUploadVideo">Choose file</label>
</div>
double[][] arr = new double[20][4];
Arrays.fill(arr[0], 0);
Arrays.fill(arr[1], 0);
Arrays.fill(arr[2], 0);
Arrays.fill(arr[3], 0);
Arrays.fill(arr[4], 0);
Arrays.fill(arr[5], 0);
Arrays.fill(arr[6], 0);
Arrays.fill(arr[7], 0);
Arrays.fill(arr[8], 0);
Arrays.fill(arr[9], 0);
Arrays.fill(arr[10], 0);
Arrays.fill(arr[11], 0);
Arrays.fill(arr[12], 0);
Arrays.fill(arr[13], 0);
Arrays.fill(arr[14], 0);
Arrays.fill(arr[15], 0);
Arrays.fill(arr[16], 0);
Arrays.fill(arr[17], 0);
Arrays.fill(arr[18], 0);
Arrays.fill(arr[19], 0);
If you are not sure how many parameters are you going to be passed into callback functions, use apply
function.
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester(callback,params){
callback.apply(this,params);
}
callbackTester(tryMe,['hello','goodbye']);
It is easy to convert your OrderedDict
to a regular Dict
like this:
dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict
:
import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)
Or dump the data directly to a file:
with open('outFile.txt','w') as o:
json.dump(d, o)
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
To set a default value to a column, try this:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
<?php
// connect your database here first
//
// Actual code starts here
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'your_database_name'
AND ENGINE = 'MyISAM'";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
$tbl = $row[0];
$sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
mysql_query($sql);
}
?>
Regarding the question,
” can someone explain why the
compare()
function exists if a comparison can be made using simple operands?
Relative to <
and ==
, the compare
function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.
As an example of simplicity, for small integer values you can write a compare function like this:
auto compare( int a, int b ) -> int { return a - b; }
which is highly efficient.
Now for a structure
struct Foo
{
int a;
int b;
int c;
};
auto compare( Foo const& x, Foo const& y )
-> int
{
if( int const r = compare( x.a, y.a ) ) { return r; }
if( int const r = compare( x.b, y.b ) ) { return r; }
return compare( x.c, y.c );
}
Trying to express this lexicographic compare directly in terms of <
you wind up with horrendous complexity and inefficiency, relatively speaking.
With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.
Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:
msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection
Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.
The following function converts an integer to binary in a string (n is the number of bits):
// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
}
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):
// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
char* binary = (char*)malloc(n+1);
for (int i=0;i<n;i++)
binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
binary[n]='\0';
return binary;
}
This option allows you to write something like printf ("%s", int2bin(78));
but be careful, memory allocated for the string must be free later.
Test online on repl.it.
Source : AnsWiki.
The following function converts an integer to binary in another integer (8 bits maximum):
// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}
Test online on repl.it
The following function displays the binary conversion
// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{
for (int i=0;i<n;i++)
putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}
Test online on repl.it.
Source : AnsWiki.
I Suggest this helper class:
public static class Xml
{
#region Fields
private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};
private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName("", "")});
#endregion
#region Methods
public static string Serialize(object obj)
{
if (obj == null)
{
return null;
}
return DoSerialize(obj);
}
private static string DoSerialize(object obj)
{
using (var ms = new MemoryStream())
using (var writer = XmlWriter.Create(ms, WriterSettings))
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj, Namespaces);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
public static T Deserialize<T>(string data)
where T : class
{
if (string.IsNullOrEmpty(data))
{
return null;
}
return DoDeserialize<T>(data);
}
private static T DoDeserialize<T>(string data) where T : class
{
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
var serializer = new XmlSerializer(typeof (T));
return (T) serializer.Deserialize(ms);
}
}
#endregion
}
:)
public static string FromSqlType(string sqlTypeString)
{
if (! Enum.TryParse(sqlTypeString, out Enums.SQLType typeCode))
{
throw new Exception("sql type not found");
}
switch (typeCode)
{
case Enums.SQLType.varbinary:
case Enums.SQLType.binary:
case Enums.SQLType.filestream:
case Enums.SQLType.image:
case Enums.SQLType.rowversion:
case Enums.SQLType.timestamp://?
return "byte[]";
case Enums.SQLType.tinyint:
return "byte";
case Enums.SQLType.varchar:
case Enums.SQLType.nvarchar:
case Enums.SQLType.nchar:
case Enums.SQLType.text:
case Enums.SQLType.ntext:
case Enums.SQLType.xml:
return "string";
case Enums.SQLType.@char:
return "char";
case Enums.SQLType.bigint:
return "long";
case Enums.SQLType.bit:
return "bool";
case Enums.SQLType.smalldatetime:
case Enums.SQLType.datetime:
case Enums.SQLType.date:
case Enums.SQLType.datetime2:
return "DateTime";
case Enums.SQLType.datetimeoffset:
return "DateTimeOffset";
case Enums.SQLType.@decimal:
case Enums.SQLType.money:
case Enums.SQLType.numeric:
case Enums.SQLType.smallmoney:
return "decimal";
case Enums.SQLType.@float:
return "double";
case Enums.SQLType.@int:
return "int";
case Enums.SQLType.real:
return "Single";
case Enums.SQLType.smallint:
return "short";
case Enums.SQLType.uniqueidentifier:
return "Guid";
case Enums.SQLType.sql_variant:
return "object";
case Enums.SQLType.time:
return "TimeSpan";
default:
throw new Exception("none equal type");
}
}
public enum SQLType
{
varbinary,//(1)
binary,//(1)
image,
varchar,
@char,
nvarchar,//(1)
nchar,//(1)
text,
ntext,
uniqueidentifier,
rowversion,
bit,
tinyint,
smallint,
@int,
bigint,
smallmoney,
money,
numeric,
@decimal,
real,
@float,
smalldatetime,
datetime,
sql_variant,
table,
cursor,
timestamp,
xml,
date,
datetime2,
datetimeoffset,
filestream,
time,
}
config
is another option:
widget1.config(bg='black')
widget2.config(bg='#000000')
or:
widget1.config(background='black')
widget2.config(background='#000000')
You can use:
$ jq 'keys' file.json
$ cat file.json:
{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }
$ jq 'keys' file.json
[
"Archiver-Version",
"Build-Id",
"Build-Jdk",
"Build-Number",
"Build-Tag",
"Built-By",
"Created-By",
"Implementation-Title",
"Implementation-Vendor-Id",
"Implementation-Version",
"Manifest-Version",
"appname",
"build-date",
"version"
]
UPDATE: To create a BASH array using these keys:
Using BASH 4+:
mapfile -t arr < <(jq -r 'keys[]' ms.json)
On older BASH you can do:
arr=()
while IFS='' read -r line; do
arr+=("$line")
done < <(jq 'keys[]' ms.json)
Then print it:
printf "%s\n" ${arr[@]}
"Archiver-Version"
"Build-Id"
"Build-Jdk"
"Build-Number"
"Build-Tag"
"Built-By"
"Created-By"
"Implementation-Title"
"Implementation-Vendor-Id"
"Implementation-Version"
"Manifest-Version"
"appname"
"build-date"
"version"
If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:
mat = [[input() for i in range (col)] for j in range (row)]
and then enter the values you want.
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
I think you can also use a postgres backup container which would backup your databases within a given time duration.
pgbackups:
container_name: Backup
image: prodrigestivill/postgres-backup-local
restart: always
volumes:
- ./backup:/backups
links:
- db:db
depends_on:
- db
environment:
- POSTGRES_HOST=db
- POSTGRES_DB=${DB_NAME}
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_EXTRA_OPTS=-Z9 --schema=public --blobs
- SCHEDULE=@every 0h30m00s
- BACKUP_KEEP_DAYS=7
- BACKUP_KEEP_WEEKS=4
- BACKUP_KEEP_MONTHS=6
- HEALTHCHECK_PORT=81
This has to do with having two buttons with the same ID in two different Activities, sometimes Android Studio can't find, You just have to give your button a new ID and re Build the Project
For me, the most flexible way to run PowerShell script from C# was using PowerShell.Create().AddScript()
The snippet of the code is
string scriptDirectory = Path.GetDirectoryName(
ConfigurationManager.AppSettings["PathToTechOpsTooling"]);
var script =
"Set-Location " + scriptDirectory + Environment.NewLine +
"Import-Module .\\script.psd1" + Environment.NewLine +
"$data = Import-Csv -Path " + tempCsvFile + " -Encoding UTF8" +
Environment.NewLine +
"New-Registration -server " + dbServer + " -DBName " + dbName +
" -Username \"" + user.Username + "\" + -Users $userData";
_powershell = PowerShell.Create().AddScript(script);
_powershell.Invoke<User>();
foreach (var errorRecord in _powershell.Streams.Error)
Console.WriteLine(errorRecord);
You can check if there's any error by checking Streams.Error. It was really handy to check the collection. User is the type of object the PowerShell script returns.
my solution for your problem!
import java.util.HashMap;
import java.util.Map;
public enum MapEnumSample {
Mustang("One of the fastest cars in the world!"),
Mercedes("One of the most beautiful cars in the world!"),
Ferrari("Ferrari or Mercedes, which one is the best?");
private final String description;
private static Map<String, String> enumMap;
private MapEnumSample(String description) {
this.description = description;
}
public String getEnumValue() {
return description;
}
public static String getEnumKey(String name) {
if (enumMap == null) {
initializeMap();
}
return enumMap.get(name);
}
private static Map<String, String> initializeMap() {
enumMap = new HashMap<String, String>();
for (MapEnumSample access : MapEnumSample.values()) {
enumMap.put(access.getEnumValue(), access.toString());
}
return enumMap;
}
public static void main(String[] args) {
// getting value from Description
System.out.println(MapEnumSample.getEnumKey("One of the fastest cars in the world!"));
// getting value from Constant
System.out.println(MapEnumSample.Mustang.getEnumValue());
System.out.println(MapEnumSample.getEnumKey("One of the most beautiful cars in the world!"));
System.out.println(MapEnumSample.Mercedes.getEnumValue());
// doesnt exist in Enum
System.out.println("Mustang or Mercedes, which one is the best?");
System.out.println(MapEnumSample.getEnumKey("Mustang or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mustang, which one is the best?") + " is the best!.");
// exists in Enum
System.out.println("Ferrari or Mercedes, wich one is the best?");
System.out.println(MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") == null ? "I don't know!" : "I believe that "
+ MapEnumSample.getEnumKey("Ferrari or Mercedes, which one is the best?") + " is the best!");
}
}