Consider a Windows Application and using Button Click Event put this code in it.
dataGridView1.Rows
.Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });
If you are developing a child theme you can use:
<img src="<?php echo get_template_directory_uri(); ?>-child/images/example.png" />
get_template_directory_uri() will return url to your currently active theme (parent theme), then you add -child/, then add path to your image (the example above assumes your image is at <child-theme-directory>/images/example.png
)
I was facing the similar issue while toggling the disabled state of button! After firing the removeProp('disabled')
the button refused to get "disabled" again! I found an interesting solution : use prop("disabled",true)
to disable the button and prop("disabled",false)
to re-enable it!
Now I was able to toggle the "disabled" state of my button as many times I needed! Try it out.
To put it a different way "id()" is not what you care about. You want to know if the variable name can be modified without harming the source variable name.
>>> a = 'hello'
>>> b = a[:]
>>> c = a
>>> b += ' world'
>>> c += ', bye'
>>> a
'hello'
>>> b
'hello world'
>>> c
'hello, bye'
If you're used to C, then these are like pointer variables except you can't de-reference them to modify what they point at, but id() will tell you where they currently point.
The problem for python programmers comes when you consider deeper structures like lists or dicts:
>>> o={'a': 10}
>>> x=o
>>> y=o.copy()
>>> x['a'] = 20
>>> y['a'] = 30
>>> o
{'a': 20}
>>> x
{'a': 20}
>>> y
{'a': 30}
Here o and x refer to the same dict o['a'] and x['a'], and that dict is "mutable" in the sense that you can change the value for key 'a'. That's why "y" needs to be a copy and y['a'] can refer to something else.
Here's a good place to use the FormArray
https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
To start we'll build up our array of controls either with a FormBuilder
or newing up a FormArray
FormBuilder
this.checkboxGroup = _fb.group({
myValues: _fb.array([true, false, true])
});
new FormArray
let checkboxArray = new FormArray([
new FormControl(true),
new FormControl(false),
new FormControl(true)]);
this.checkboxGroup = _fb.group({
myValues: checkboxArray
});
Easy enough to do, but then we're going to change our template and let the templating engine handle how we bind to our controls:
template.html
<form [formGroup]="checkboxGroup">
<input *ngFor="let control of checkboxGroup.controls['myValues'].controls"
type="checkbox" id="checkbox-1" value="value-1" [formControl]="control" />
</form>
Here we're iterating over our set of FormControls
in our myValues
FormArray
and for each control we're binding [formControl]
to that control instead of to the FormArray
control and <div>{{checkboxGroup.controls['myValues'].value}}</div>
produces true,false,true
while also making your template syntax a little less manual.
You can use this example: http://plnkr.co/edit/a9OdMAq2YIwQFo7gixbj?p=preview to poke around
Most of the answers are too lengthy or too short not fulfilling the purpose. For those how are looking for Java or Kotlin code to Convert bitmap to File Object. Here is the detailed article I have written on the topic. Convert Bitmap to File in Android
public static File bitmapToFile(Context context,Bitmap bitmap, String fileNameToSave) { // File name like "image.png"
//create a file to write bitmap data
File file = null;
try {
file = new File(Environment.getExternalStorageDirectory() + File.separator + fileNameToSave);
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 , bos); // YOU can also save it in JPEG
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
return file;
}catch (Exception e){
e.printStackTrace();
return file; // it will return null
}
}
A process performing I/O will be put in D state (uninterruptable sleep), which frees the CPU until there is a hardware interrupt which tells the CPU to return to executing the program. See man ps
for the other process states.
Depending on your kernel, there is a process scheduler, which keeps track of a runqueue of processes ready to execute. It, along with a scheduling algorithm, tells the kernel which process to assign to which CPU. There are kernel processes and user processes to consider. Each process is allocated a time-slice, which is a chunk of CPU time it is allowed to use. Once the process uses all of its time-slice, it is marked as expired and given lower priority in the scheduling algorithm.
In the 2.6 kernel, there is a O(1) time complexity scheduler, so no matter how many processes you have up running, it will assign CPUs in constant time. It is more complicated though, since 2.6 introduced preemption and CPU load balancing is not an easy algorithm. In any case, it’s efficient and CPUs will not remain idle while you wait for the I/O.
Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.
"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.
When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.
When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."
To build uri with get parameters, Uri.Builder provides a more effective way.
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
You can try to use underscore.js
First convert the lines in arrays using the toArray function :
var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);
Then object the arrays together using the object function :
var json = _.object(letters, numbers);
By then, the json var should contain something like :
{"a": 1,"b": 2,"c": 3,"d": 4}
I merely created a div class using various heights i.e.
<div class="divider-10"></div>
The CSS is:
.divider-10 {
width:100%;
min-height:1px;
margin-top:10px;
margin-bottom:10px;
display:inline-block;
position:relative;
}
Just create a divider class for what ever heights are needed.
This is for format the date?
def format_date(day, month, year):
# {} betekent 'plaats hier stringvoorstelling van volgend argument'
return "{}/{}/{}".format(day, month, year)
There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.
Nick's answer shows how you can do something similar that handles arbitrary types using interface{}
. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{}
type)
My other answer shows how you can do something similar that avoids creating a type using anonymous structs.
These techniques have some properties of tuples, but no, they are not tuples.
In "Package Explorer" view, Right click your test class, then "Build Path">>"Include", it should be OK.
This is a helpful website listing the mapping for the latest releases of Chrome -
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
Install phantomjs
$ npm install phantomjs
Create a file github.js with following code
var page = require('webpage').create();
//viewportSize being the actual size of the headless browser
page.viewportSize = { width: 1024, height: 768 };
page.open('http://github.com/', function() {
page.render('github.png');
phantom.exit();
});
Pass the file as argument to phantomjs
$ phantomjs github.js
Set it in the JAVA_OPTS
variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.
JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
It means you're calling http from https. You can use src="//url.to/script.js"
in your script tag and it will auto-detect.
Alternately you can use use https in your src
even if you will be publishing it to a http page. This will avoid the potential issue mentioned in the comments.
Yes, it is possible. Try this:
body { background-image:
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>");
}
(Note that the SVG content needs to be url-escaped for this to work, e.g. #
gets replaced with %23
.)
This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.
Unions and intersections defined only for sets, not lists. As you mentioned.
Check guava library for filters. Also guava provides real intersections and unions
static <E> Sets.SetView<E >union(Set<? extends E> set1, Set<? extends E> set2)
static <E> Sets.SetView<E> intersection(Set<E> set1, Set<?> set2)
Never mind, figured it out:
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
Which I found by:
show all
And looking for some option that seemed relevant.
It is just not a valid Java syntax. You can do
names = new String[] {"Ankit","Bohra","Xyz"};
yes, these are the well-known quantifiers used in math. Another example is ? which reads as "exists".
You can also do way more complex commands, just to round out the examples above. So, say I want to get the number of processes running on the system and store it in the ${NUM_PROCS} variable.
All you have to so is generate the command pipeline and stuff it's output (the process count) into the variable.
It looks something like this:
NUM_PROCS=$(ps -e | sed 1d | wc -l)
I hope that helps add some handy information to this discussion.
At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON
AJAX method because it easily returns JSONP using the ?callback=?
without having any issues with CORS.
data ='USER=<?echo trim($USER)?>' +
'&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();
//Call the REST program/method returns: JSONP
$.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
.done(function( json ) {
// loading...
if ($.trim(json.ERROR) != '') {
$("#error-msg").text(message).show();
}
else{
$(".error").hide();
$("#jsonp").text(json.whatever);
}
})
.fail(function( jqXHR, textStatus, error ) {
var err = textStatus + ", " + error;
alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
});
NOTE: I concocted this solution before I was reminded about all the "special cases" that can occur in a valid CSV file, like escaped quotes. I'm leaving my answer for those who want something quick and dirty, but I recommend Evan's answer for accuracy.
This code will work when your data.txt
file is one long string of comma-separated entries, with no newlines:
data.txt:
heading1,heading2,heading3,heading4,heading5,value1_1,...,value5_2
javascript:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var record_num = 5; // or however many elements there are in each row
var allTextLines = allText.split(/\r\n|\n/);
var entries = allTextLines[0].split(',');
var lines = [];
var headings = entries.splice(0,record_num);
while (entries.length>0) {
var tarr = [];
for (var j=0; j<record_num; j++) {
tarr.push(headings[j]+":"+entries.shift());
}
lines.push(tarr);
}
// alert(lines);
}
The following code will work on a "true" CSV file with linebreaks between each set of records:
data.txt:
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
javascript:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
}
}
// alert(lines);
}
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
You can't use String.isEmpty()
if it is null. Best is to have your own method to check null or empty.
public static boolean isBlankOrNull(String str) {
return (str == null || "".equals(str.trim()));
}
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
You might be interested in the following:
I realize this is not a jQuery solution, but Sencha Touch framework is pretty good for building your target UI. Example (click the Carousel sidebar link): http://dev.sencha.com/deploy/touch/examples/kitchensink/
Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http
it returns observable instead of promise, like you did
return this.http
.get(this.configEndPoint)
.map(res => res.json());
then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()
.map() is used to convert the observable (received from http request)to any form like .json(), .text()
as stated in Angular's official website,
.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
The accepted solution has the inconvenient (for me) to not be "source-able":
if you call it from a "source ../../yourScript
", $0
would be "bash
"!
The following function (for bash >= 3.0) gives me the right path, however the script might be called (directly or through source
, with an absolute or a relative path):
(by "right path", I mean the full absolute path of the script being called, even when called from another path, directly or with "source
")
#!/bin/bash
echo $0 executed
function bashscriptpath() {
local _sp=$1
local ascript="$0"
local asp="$(dirname $0)"
#echo "b1 asp '$asp', b1 ascript '$ascript'"
if [[ "$asp" == "." && "$ascript" != "bash" && "$ascript" != "./.bashrc" ]] ; then asp="${BASH_SOURCE[0]%/*}"
elif [[ "$asp" == "." && "$ascript" == "./.bashrc" ]] ; then asp=$(pwd)
else
if [[ "$ascript" == "bash" ]] ; then
ascript=${BASH_SOURCE[0]}
asp="$(dirname $ascript)"
fi
#echo "b2 asp '$asp', b2 ascript '$ascript'"
if [[ "${ascript#/}" != "$ascript" ]]; then asp=$asp ;
elif [[ "${ascript#../}" != "$ascript" ]]; then
asp=$(pwd)
while [[ "${ascript#../}" != "$ascript" ]]; do
asp=${asp%/*}
ascript=${ascript#../}
done
elif [[ "${ascript#*/}" != "$ascript" ]]; then
if [[ "$asp" == "." ]] ; then asp=$(pwd) ; else asp="$(pwd)/${asp}"; fi
fi
fi
eval $_sp="'$asp'"
}
bashscriptpath H
export H=${H}
The key is to detect the "source
" case and to use ${BASH_SOURCE[0]}
to get back the actual script.
There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__
.
df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For example, to get every 2 rows, you can do
df[::2]
a b c
0 x x x
2 x x x
4 x x x
There's also GroupBy.first
/GroupBy.head
, you group on the index:
df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')
df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)
a b c
0 x x x
1 x x x
2 x x x
The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do
# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()
a b c
0 x x x
1 x x x
2 x x x
Using jQuery's .is( ":focus" )
$(".status").on("click","textarea",function(){
if ($(this).is( ":focus" )) {
// fire this step
}else{
$(this).focus();
// fire this step
}
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
Use it to access class in Javascript.
<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>
You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.
Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.
Tools
Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.
You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.
Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.
Language
PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.
A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.
Javascript-heavy sites
In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.
There are two approaches to this problem:
The low level approach:
You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.
The embedded browser approach:
Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.
If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.
You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.
Which approach is best?
That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.
The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.
Rate Limiting/Bot behaviour
You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.
Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.
You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.
Testing
Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.
There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.
The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.
You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.
Legal Issues
The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.
The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.
It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.
Who am I to write this giant wall of text anyway?
I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.
I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)
I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.
I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.
On Python 3 you can use the itertools islice
to slice the dict.items()
iterator
import itertools
d = {1: 2, 3: 4, 5: 6}
dict(itertools.islice(d.items(), 2))
{1: 2, 3: 4}
Note: this solution does not take into account specific keys. It slices by internal ordering of d
, which in Python 3.7+ is guaranteed to be insertion-ordered.
If you have just started with angular and bootstrap then simple answer would be below steps: 1. Add node package of bootstrap as dev dependency
npm install --save bootstrap
import bootstrap stylessheet in angular.json file.
"styles": [
"projects/my-app/src/styles.scss",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
and you are ready to use bootstrap for styling, grid etc.
<div class="container">My first bootstrap div</div>
The best part of this which I found was that we are directing using bootstrap without any third-party module dependency. We can upgrade bootstrap anytime by just updating the command npm install --save [email protected]
etc.
To add to Matt wilson's answer I had a bunch of code-first entity classes but no database as I hadn't taken a backup. So I did the following on my Entity Framework project:
Open Package Manager console in Visual Studio and type the following:
Enable-Migrations
Add-Migration
Give your migration a name such as 'Initial' and then create the migration. Finally type the following:
Update-Database
Update-Database -Script -SourceMigration:0
The final command will create your database tables from your entity classes (provided your entity classes are well formed).
If you don't remember your password, then run this command in the Shell:
mysqladmin.exe -u root password NewPassword
where 'NewPassword' is your new password.
Using display: flex
you can control the vertical alignment of HTML elements.
.box {_x000D_
height: 100px;_x000D_
display: flex;_x000D_
align-items: center; /* Vertical */_x000D_
justify-content: center; /* Horizontal */_x000D_
border:2px solid black;_x000D_
}_x000D_
_x000D_
.box div {_x000D_
width: 100px;_x000D_
height: 20px;_x000D_
border:1px solid;_x000D_
}
_x000D_
<div class="box">_x000D_
<div>Hello</div>_x000D_
<p>World</p>_x000D_
</div>
_x000D_
The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
I would use .*
. .
matches any character, *
signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with .
.
The other answers didn't work for me. I found the answer in their documentation:
http://api.highcharts.com/highcharts#Series
Using this method (see JSFiddle example):
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});
First / last visible child depends on the LayoutManager
.
If you are using LinearLayoutManager
or GridLayoutManager
, you can use
int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition();
int findLastCompletelyVisibleItemPosition();
For example:
GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
For LinearLayoutManager
, first/last depends on the adapter ordering. Don't query children from RecyclerView
; LayoutManager
may prefer to layout more items than visible for caching.
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
To be a bit more complete, Git works with:
git init
).git
, which will store the revisions of all your files)GIT_DIR
is an environment variable, which can be an absolute path or relative path to current working directory.
If it is not defined, the "path to the git repository" is by default at the root directory of your working tree (again, where you made a git init
).
You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:
git command --git-dir=<path> --work-tree=<path>
But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git
, assume this it also the root directory of your working tree, and use that .git
as the only container for all the revisions of your files.
Note: .git
is also hidden in Windows (msysgit).
You would have to do a dir /AH
to see it.
git 2.9 (June 2016) allows to configure that.
Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible to open multiple repositories, work with and then close them.
See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon
).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller
).
(Merged by Junio C Hamano -- gitster
-- in commit cf0b179, 11 Apr 2018)
repository
: introduce raw object store fieldThe raw object store field will contain any objects needed for access to objects in a given repository.
This patch introduces the raw object store and populates it with the
objectdir
, which used to be part of the repository struct.As the struct gains members, we'll also populate the function to clear the memory for these members.
In a later step, we'll introduce a
struct object_parser
, that will complement the object parsing in a repository struct:
- The raw object parser is the layer that will provide access to raw object content,
while the higher level object parser code will parse raw objects and keeps track of parenthood and other object relationships using '
struct object
'.For now only add the lower level to the repository struct.
You should update the web.config file in the server. When nuget install NewtonSoft update this file including this code
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
Run Xampp (apache) as administrator. In google chrome type:
localhost/<insert folder name here>/<insert file name>
i.e. if folder you created is "LearnPhp", file is "chapter1.php" then type
localhost/LearnPhp/chapter1.php
I created this folder in the xampp folder in the htdocs folder which gets created when you download xampp.
As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2)
as a simple alternative. Here's a more advanced mtext() example:
set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
yaxt="n", ylab="",
xlab="Regular boring x",
pch=16,
col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)
You may need to adjust the line=
option to get the optimal positioning of the text but apart from that it's really easy to use.
Here's another using the zip
function.
>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
for
loop, you're iterating through the elements of a list a
. But in the body of the loop, you're using those items to index that list, when you actually want indexes.a
would contain 5 items, a number 100 would be among them and the for loop would reach it. You will essentially attempt to retrieve the 100th element of the list a
, which obviously is not there. This will give you an IndexError
. We can fix this issue by iterating over a range of indexes instead:
for i in range(len(a))
and access the a
's items like that: a[i]
. This won't give any errors.
a[i]
, but also a[i+1]
. This is also a place for a potential error. If your list contains 5 items and you're iterating over it like I've shown in the point 1, you'll get an IndexError
. Why? Because range(5)
is essentially 0 1 2 3 4
, so when the loop reaches 4, you will attempt to get the a[5]
item. Since indexing in Python starts with 0 and your list contains 5 items, the last item would have an index 4, so getting the a[5]
would mean getting the sixth element which does not exist.To fix that, you should subtract 1 from len(a)
in order to get a range sequence 0 1 2 3
. Since you're using an index i+1
, you'll still get the last element, but this way you will avoid the error.
b = [a[i] + a[i+1] for i in range(len(a) - 1)]
This does the job in only one line.
Open the terminal and remove your entire Anaconda directory, which will have a name such as “anaconda2” or “anaconda3”, by entering the following command: rm -rf ~/anaconda3. Then remove conda with command "conda uninstall" https://conda.io/docs/commands/conda-uninstall.html.
Have you tried Server.MapPath
method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
A .pl is a single script.
In .pm (Perl Module) you have functions that you can use from other Perl scripts:
A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
I ran into the need to allow decimal values, so I used not Value like '%[^0-9.]%'
Here's an example (source):
SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
update your CSS to the following: this should fix
.page {
width: 280px;
border:solid 1px blue;
overflow-x: auto;
}
You could do something like this:
<body>
<textarea id="txtArea" onkeypress="onTestChange();"></textarea>
<script>
function onTestChange() {
var key = window.event.keyCode;
// If the user has pressed enter
if (key === 13) {
document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
return false;
}
else {
return true;
}
}
</script>
</body>
Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.
Answer from official website
https://datatables.net/reference/option/columns.width
$('#example').dataTable({
"columnDefs": [
{
"width": "20%",
"targets": 0
}
]
});
Use gettimeofday()
to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.
$content = '';
for($rowth=0; $rowth<=100; $rowth++){
$content .= $selenium->getTable("tblReports.{$rowth}.0") . "\n";
//$content .= $selenium->getTable("tblReports.{$rowth}.1") . "\n";
$content .= $selenium->getTable("tblReports.{$rowth}.2") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.3") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.4") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.5") . " ";
$content .= $selenium->getTable("tblReports.{$rowth}.6") . "\n";
}
I had the same error in Chrome. The Chrome console told me that the error was in the 1st line of the HTML file.
It was actually in the .js file. So watch out for setValidNou(1060, $(this).val(), 0')
error types.
Well, here is one solution I ended up with, but I hope there's a more elegant one...
StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
char tmpChar = name.charAt( i );
if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
result.append( tmpChar );
}
}
result
ends up with the desired result...
The difference between pointers and references is quite simple: a pointer can be null, a reference can not.
Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).
Here it looks like references are more appropriate.
Enum.valueOf()
only checks the constant name, so you need to pass it "COLUMN_HEADINGS"
instead of "columnHeadings". Your name
property has nothing to do with Enum internals.
To address the questions/concerns in the comments:
The enum's "builtin" (implicitly declared) valueOf(String name)
method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:
enum PropName { contents, columnHeadings, ...}
. This is obviously the most convenient.valueOf
, if you're really fond of naming conventions.valueOf
to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.The easiest way that I've seen to do encryption is through RSA
Check out the MSDN on it: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx
It does involve using bytes, but when it comes down to it you kind of do want encryption and decryption to be tough to figure out otherwise it will be easy to hack.
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
From sun docs:
\s A whitespace character: [ \t\n\x0B\f\r]
The simplest way is to use it with regex.
You can simply use the isinstance function to make sure that the input data is of format string or unicode. Below examples will help you to understand easily.
>>> isinstance('my string', str)
True
>>> isinstance(12, str)
False
>>> isinstance('my string', unicode)
False
>>> isinstance(u'my string', unicode)
True
While you are declaring onclick in XML then you must declair method and pass View v as parameter and make the method public...
Ex:
//in xml
android:onClick="onButtonClicked"
// in java file
public void onButtonClicked(View v)
{
//your code here
}
At least I haven't seen any of my collegues or higher ups saying that, that's just ridiculous considering the fact that there is no significant speed difference between for
and foreach
. The same applies if he is asking to use it in all cases!
Give your form an id only, and your input a name only:
<form id="myform">
<input type="text" name="foo">
Then the most standards-compliant and least problematic way to access your input element is via:
document.getElementById("myform").elements["foo"]
using .elements["foo"]
instead of just .foo
is preferable because the latter might return a property of the form named "foo" rather than a HTML element!
Are you sure it's not a Table-Valued Function
?
The reason I ask:
CREATE FUNCTION dbo.chk_mgr(@mgr VARCHAR(50))
RETURNS @mgr_table TABLE (mgr_name VARCHAR(50))
AS
BEGIN
INSERT @mgr_table (mgr_name) VALUES ('pointy haired boss')
RETURN
END
GO
SELECT dbo.chk_mgr('asdf')
GO
Result:
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function
or aggregate "dbo.chk_mgr", or the name is ambiguous.
However...
SELECT * FROM dbo.chk_mgr('asdf')
mgr_name
------------------
pointy haired boss
I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.
I think the library I am using is not managing connections properly because it happeend just few times.
First convert it to std::wstring:
std::wstring widestr = std::wstring(str.begin(), str.end());
Then get the C string:
const wchar_t* widecstr = widestr.c_str();
This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.
C/program files/
and user/sukhendra/AppData
then only Anaconda is remaining in my PC so opened Anaconda and then it's all working fine for me
As an addition. If you are using $(Jquery) in your .js file. Logically all libs or frameworks should be before that .js file.
<script type="text/javascript" src="jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="app.js"></script>
I edited homestead.yaml
and hosts
according to this laracast tutorial and restarted homestead using vagrant suspend
, vagrant halt
, etc. /vagrant up
; I tried to vagrant provision
as well, but no file specified
only went away after I restarted my computer (I'm on Windows 7 PC) after doing all of the above. It is certainly a time consuming and tricky error.
This is what my working homestead.yaml
looks like for two laravel projects:
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
- ~/.ssh/id_rsa
folders:
- map: D:\Projects
to: /home/vagrant/Projects
sites:
- map: projectone.app
to: /home/vagrant/Projects/ProjectOne/public
- map: projecttwo.app
to: /home/vagrant/Projects/ProjectTwo/public
databases:
- laraveldb
and here is my hosts
file:
...
127.0.0.1 localhost
192.168.10.10 projectone.app
192.168.10.10 projecttwo.app
Note, there are two separate installations of laravel in D:\Projects\ProjectOne
and D:\Projects\ProjectTwo
I then access the first project by typing projectone.app:8000
in the browser and projecttwo.app:8000
for the second project.
P.S. I tested this for Laravel 5.2 on Windows
Try this:
>>> f = open('goodlines.txt')
>>> mylist = f.readlines()
open()
function returns a file object. And for file object, there is no method like splitlines()
or split()
. You could use dir(f)
to see all the methods of file object.
in angular 7, you have to import "ReactiveFormsModule".
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
I solved this issue by this import.It would help you.
Old thread, but just only to say: to use the classic Left()
, Right()
, Mid()
right now you don't need to write the full path (Microsoft.VisualBasic.Strings
). You can use fast and easily like this:
Strings.Right(yourString, 5)
If you're trying to POST
Make sure to JSON.stringify
your form data and send as text/plain
.
<form id="my-form" onSubmit="return postMyFormData();">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email" required>
<input type="submit" value="Submit My Form">
</form>
function postMyFormData() {
var formData = $('#my-form').serializeArray();
formData = formData.reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
formData = JSON.stringify(formData);
$.ajax({
type: "POST",
url: "https://website.com/path",
data: formData,
success: function() { ... },
dataType: "text",
contentType : "text/plain"
});
}
From C# 6:
var dateTimeUtcAsString = $"{DateTime.UtcNow:o}";
The result will be: "2019-01-15T11:46:33.2752667Z"
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
Use:
bool(distutils.util.strtobool(some_string))
True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.
Be aware that distutils.util.strtobool()
returns integer representations and thus it needs to be wrapped with bool()
to get Boolean values.
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
This code mouse cursor “jtextfield” “Jcombobox” location focused
try {
Robot robot = new Robot();
int x = Jtextfield.getLocationOnScreen().x;
int y= Jtextfield.getLocationOnScreen().y;
JOptionPane.showMessageDialog(null, x+"x< - y>"+y);// for I location see
robot.mouseMove(x, y);
} catch (AWTException ex) {
ex.printStackTrace();
}
You can use the typeid operator:
#include <typeinfo>
...
cout << typeid(variable).name() << endl;
The window object in JavaScript on iOS devices has an orientation property that can be used to determine the rotation of the device. The following shows the values window.orientation for iOS devices (e.g. iPhone, iPad, iPod) at different orientations.
This solution also works for android devices as well. I checked in android native browser (Internet browser) and in the Chrome browser, even in the old versions of it.
function readDeviceOrientation() {
if (Math.abs(window.orientation) === 90) {
// Landscape
} else {
// Portrait
}
}
I had the problem, I had to replace "Not Available" with NA
and my solution goes like this
data <- sapply(data,function(x) {x <- gsub("Not Available",NA,x)})
Assuming you want to do it yourself and not rely upon other providers, IP2Nation provides a MySQL database of the mappings which are updated as the regional registries change things around.
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
.hover()
function accepts two function arguments, one for mouseenter
event and one for mouseleave
event.
Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.
Geocoder call procedure, can be located in a Helper class
public static void getAddressFromLocation(
final Location location, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", " + address.getLocality();
}
} catch (IOException e) {
Log.e(TAG, "Impossible to connect to Geocoder", e);
} finally {
Message msg = Message.obtain();
msg.setTarget(handler);
if (result != null) {
msg.what = 1;
Bundle bundle = new Bundle();
bundle.putString("address", result);
msg.setData(bundle);
} else
msg.what = 0;
msg.sendToTarget();
}
}
};
thread.start();
}
Here is the call to this Geocoder procedure in your UI Activity:
getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());
And the handler to show the results in your UI:
private class GeocoderHandler extends Handler {
@Override
public void handleMessage(Message message) {
String result;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
result = bundle.getString("address");
break;
default:
result = null;
}
// replace by what you need to do
myLabel.setText(result);
}
}
Don't forget to put the following permission in your Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
As far as I know its not possible with javascript.
What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)
If it's not a big/long array just mirror it:
for( int i = 0; i < arr.length/2; ++i )
{
temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
From the code that you have provided, not knowing the language that you are programming in. The variable capital
is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital
.
To Send bold,italic,fixed width code you can use this :
# Sending a HTML formatted message
bot.send_message(chat_id=@yourchannelname,
text="*boldtext* _italictext_ `fixed width font` [link] (http://google.com).",
parse_mode=telegram.ParseMode.MARKDOWN)
make sure you have enabled the bot as your admin .Then only it can send message
You can simply go Netbeans, in the design view, go to JFrame
property, choose icon image property, Choose Set Form's iconImage
property using: "Custom code" and then in the Form.SetIconImage()
function put the following code:
Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))
Do not forget to import:
import java.awt.Toolkit;
in the source code!
Cloning an input stream might not be a good idea, because this requires deep knowledge about the details of the input stream being cloned. A workaround for this is to create a new input stream that reads from the same source again.
So using some Java 8 features this would look like this:
public class Foo {
private Supplier<InputStream> inputStreamSupplier;
public void bar() {
procesDataThisWay(inputStreamSupplier.get());
procesDataTheOtherWay(inputStreamSupplier.get());
}
private void procesDataThisWay(InputStream) {
// ...
}
private void procesDataTheOtherWay(InputStream) {
// ...
}
}
This method has the positive effect that it will reuse code that is already in place - the creation of the input stream encapsulated in inputStreamSupplier
. And there is no need to maintain a second code path for the cloning of the stream.
On the other hand, if reading from the stream is expensive (because a it's done over a low bandwith connection), then this method will double the costs. This could be circumvented by using a specific supplier that will store the stream content locally first and provide an InputStream
for that now local resource.
Hmm, not quite sure what your question is.
In the title you ask about Databases (DB), whereas in the body of your text you ask about Database Management Systems (DBMS). The two are completely different and require different answers.
A DBMS is a tool that allows you to access a DB.
Other than the data itself, a DB is the concept of how that data is structured.
So just like you can program with Oriented Object methodology with a non-OO powered compiler, or vice-versa, so can you set-up a relational database without an RDBMS or use an RDBMS to store non-relational data.
I'll focus on what Relational Database (RDB) means and leave the discussion about what systems do to others.
A relational database (the concept) is a data structure that allows you to link information from different 'tables', or different types of data buckets. A data bucket must contain what is called a key or index (that allows to uniquely identify any atomic chunk of data within the bucket). Other data buckets may refer to that key so as to create a link between their data atoms and the atom pointed to by the key.
A non-relational database just stores data without explicit and structured mechanisms to link data from different buckets to one another.
As to implementing such a scheme, if you have a paper file with an index and in a different paper file you refer to the index to get at the relevant information, then you have implemented a relational database, albeit quite a simple one. So you see that you do not even need a computer (of course it can become tedious very quickly without one to help), similarly you do not need an RDBMS, though arguably an RDBMS is the right tool for the job. That said there are variations as to what the different tools out there can do so choosing the right tool for the job may not be all that straightforward.
I hope this is layman terms enough and is helpful to your understanding.
I faced the same problem, the following changes solved my problem.
$(document).ready(function() {
$('.datatable').dataTable( {
bSort: false,
aoColumns: [ { sWidth: "45%" }, { sWidth: "45%" }, { sWidth: "10%", bSearchable: false, bSortable: false } ],
"scrollY": "200px",
"scrollCollapse": true,
"info": true,
"paging": true
} );
} );
the aoColumns
array describes the width of each column and its sortable
properties.
Another thing to mention this error will also appear when you order by a column number that does not exist.
I needed to find the position of an element inside a ListView and used this snippet that works kind of like .offset
:
const UIManager = require('NativeModules').UIManager;
const handle = React.findNodeHandle(this.refs.myElement);
UIManager.measureLayoutRelativeToParent(
handle,
(e) => {console.error(e)},
(x, y, w, h) => {
console.log('offset', x, y, w, h);
});
This assumes I had a ref='myElement'
on my component.
Just as an addition: This way you can access properties with names that would be otherwise unusable
$x = new StdClass;$prop = 'a b'; $x->$prop = 1; $x->{'x y'} = 2; var_dump($x);
object(stdClass)#1 (2) { ["a b"]=> int(1) ["x y"]=> int(2) }(not that you should, but in case you have to).
Use screen: Start screen
, start your script, press Ctrl+A, D. Reattach with screen -r
.
Make a script that takes your "1" as a parameter, run nohup yourscript
:
#!/bin/bash
(time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
On Ubuntu, You can follow these steps to resolve the issue:
$HOME/.mozilla
, if it doesn't exist alreadyCreate a symlink to libnpjp2.so inside this directory using this command:
ln -s $JAVA_HOME/jre/lib/i386/libnpjp2.so $MOZILLA_HOME/plugins
-or-
ln -s $JAVA_HOME/jre/lib/amd64/libnpjp2.so $MOZILLA_HOME/plugins
depending on whether you're using a 32 or 64 bit JVM installation. Moreover, $JAVA_HOME is the location of your JVM installation.
More detailed instructions can be found here.
If you need Base64 over JSON, check out Jackson: it has explicit support for binary data read/write as Base64 at both the low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled.
And pretty efficiently too, should that matter.
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
From HandlerIntercepter
's javadoc:
HandlerInterceptor
is basically similar to a ServletFilter
, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured inweb.xml
, aHandlerInterceptor
in the application context.As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for
HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, aFilter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
With that being said:
So where is the difference between
Interceptor#postHandle()
andFilter#doFilter()
?
postHandle
will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse
since it's already committed.
doFilter
is much more versatile than the postHandle
. You can change the request or response and pass it to the chain or even block the request processing.
Also, in preHandle
and postHandle
methods, you have access to the HandlerMethod
that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.
What is the best practise in which use cases it should be used?
As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor
implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter
is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
I had this problem, but only in Visual Studio Code, not in ISE. Turns out I was using an x86 session in VSCode. I displayed the PowerShell Session Menu and switched to the x64 session, and all the modules began working without full paths. I am using Version 1.17.2, architecture x64 of VSCode. My modules were stored in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules directory.
FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:
private void foo()
{
try
{
bar(3);
bar(2);
bar(1);
bar(0);
}
catch(DivideByZeroException)
{
//log message and rethrow...
throw;
}
}
private void bar(int b)
{
int a = 1;
int c = a/b; // Generate divide by zero exception.
}
The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.
removing temp files, and did you restart the computer or stop the MySQL service? That's the error message you get when there isn't a MySQL server running.
Simplest Answer is "No Direct method of getting it because there is no pre-compiler"
But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class
There are some gotchas. Assignment in Javascript is from right to left so when you write:
var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
it effectively translates to:
var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));
which effectively translates to:
var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));
Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.
Note: My above example assumes you are running your code in the browser, hence window
. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global
which is the global context for that environment).
Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.
var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.
Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.
java.util.MissingResourceException: Can't find bundle for base name org.jfree.chart.LocalizationBundle, locale en_US
To the point, the exception message tells in detail that you need to have either of the following files in the classpath:
/org/jfree/chart/LocalizationBundle.properties
or
/org/jfree/chart/LocalizationBundle_en.properties
or
/org/jfree/chart/LocalizationBundle_en_US.properties
Also see the official Java tutorial about resourcebundles for more information.
But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.
When executing a JAR file, you can use the -cp
argument to specify the classpath. E.g.:
java -jar -cp c:/path/to/jfreechart.jar yourfile.jar
Alternatively you can specify the classpath as class-path
entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH%
environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe
without -cp
, -classpath
and -jar
arguments.
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
Use QString::arg()
for the same effect.
function getPercentUsed() {
$sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
return $val[0];
}
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Source: Reading and Writing Files
For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash
), and simply run it with sh
from Jenkinsfile:
sh 'chmod +x ./script.sh'
sh './script.sh'
You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.
Your best bet is to validate the input when the form is submitted to ensure that the length is six.
maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.
I'd suggest that it is better practice to use String.format()
. The main reason is that String.format()
can be more easily localised with text loaded from resource files whereas concatenation can't be localised without producing a new executable with different code for each language.
If you plan on your app being localisable you should also get into the habit of specifying argument positions for your format tokens as well:
"Hello %1$s the time is %2$t"
This can then be localised and have the name and time tokens swapped without requiring a recompile of the executable to account for the different ordering. With argument positions you can also re-use the same argument without passing it into the function twice:
String.format("Hello %1$s, your name is %1$s and the time is %2$t", name, time)
The latest JDBC MSSQL connectivity driver can be found on JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path --> Libraries --> Add External Jars
Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
declare @tab table(FirstName varchar(100))
insert into @tab values('John'),('Sarah'),('George')
SELECT *
FROM @tab
WHERE 'John' in (FirstName)
I created a global define with more information:
#include <iostream>
#include <ctime>
#include <iomanip>
#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) // only show filename and not it's path (less clutter)
#define INFO std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [INFO] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
#define ERROR std::cout << std::put_time(std::localtime(&time_now), "%y-%m-%d %OH:%OM:%OS") << " [ERROR] " << __FILENAME__ << "(" << __FUNCTION__ << ":" << __LINE__ << ") >> "
static std::time_t time_now = std::time(nullptr);
Use it like this:
INFO << "Hello world" << std::endl;
ERROR << "Goodbye world" << std::endl;
Sample output:
16-06-23 21:33:19 [INFO] main.cpp(main:6) >> Hello world
16-06-23 21:33:19 [ERROR] main.cpp(main:7) >> Goodbye world
Put these lines in your header file. I find this very useful for debugging, etc.
When you say
foo = 'bar'
baz(foo)
you are not passing foo
to the baz
function. foo
is just a name used to represent a value, in this case 'bar'
, and that value is passed to the baz
function.
There are two ways. One is to aggregate:
SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'
The other is to use an array constructor:
SELECT ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name = 'aean')
I'm presuming this is for plpgsql. In that case you can assign it like this:
colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);
NVM Installation & usage on Windows
Below are the steps for NVM Installation on Windows:
NVM stands for node version manager, which will help to switch the your node versions for specific use. It also allows the user to work with multiple npm and node versions.
Install nvm setup. Use command "nvm list" to check list ofinstalled node version. Type "nvm use version number[6.9.3]" to switch versions. For more info
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
$('#content').html('whatever');
I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.
var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));
use maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
or download commons-io.1.3.2.jar to your lib folder
If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:
Switch to branch "foo" and update it:
$ git checkout foo
$ git pull
You can see the branches you've got by issuing command:
$ git branch
Store it in a cookie that only lasts for the current browsing session
Static tStart As Single, tEnd As Single, myInterval As Integer
myInterval = 5 ' seconds
tStart = VB.Timer()
tEnd = myInterval + VB.Timer()
Do While tEnd > tStart
Application.DoEvents()
tStart = VB.Timer()
Loop
This is an old question, but it's still one of the first results on Google. The fastest way to do this is to link MySQL directly to Excel using ODBC queries or MySQL For Excel. The latter was mentioned in a comment to the OP, but I felt it really deserved its own answer because exporting to CSV is not the most efficient way to achieve this.
ODBC Queries - This is a little bit more complicated to setup, but it's a lot more flexible. For example, the MySQL For Excel add-in doesn't allow you to use WHERE
clauses in the query expressions. The flexibility of this method also allows you to use the data in more complex ways.
MySQL For Excel - Use this add-in if you don't need to do anything complex with the query or if you need to get something accomplished quickly and easily. You can make views in your database to workaround some of the query limitations.
This should help:
function getQueryParams(){
try{
url = window.location.href;
query_str = url.substr(url.indexOf('?')+1, url.length-1);
r_params = query_str.split('&');
params = {}
for( i in r_params){
param = r_params[i].split('=');
params[ param[0] ] = param[1];
}
return params;
}
catch(e){
return {};
}
}
InputStream is = new FileInputStream("c://filename");
return is;
sudo apt-get install qt5-default
works for me.
$ aptitude show qt5-default
tells that
This package sets Qt 5 to be the default Qt version to be used when using development binaries like qmake. It provides a default configuration for qtchooser, but does not prevent alternative Qt installations from being used.
Function can be used within a sql statement whereas procedure cannot be used within a sql statement.
Insert, Update and Create statements cannot be included in function but a procedure can have these statements.
Procedure supports transactions but functions do not support transactions.
Function has to return one and only one value (another can be returned by OUT variable) but procedure returns as many data sets and return values.
Execution plans of both functions and procedures are cached, so the performance is same in both the cases.
Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf
returns a view of the string as a List
.
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
Simple and best way for GeoLocation.
LocationManager lm = null;
boolean network_enabled;
if (lm == null)
lm = (LocationManager) Kikit.this.getSystemService(Context.LOCATION_SERVICE);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
dialog = ProgressDialog.show(Kikit.this, "", "Fetching location...", true);
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run()
{
Log.e("counter value","value "+counter);
if(counter<=8)
{
try
{
counter++;
if (network_enabled) {
lm = (LocationManager) Kikit.this.getSystemService(Context.LOCATION_SERVICE);
Log.e("in network_enabled..","in network_enabled");
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
if(attempt == false)
{
attempt = true;
Log.e("in location listener..","in location listener..");
longi = location.getLongitude();
lati = location.getLatitude();
Data.longi = "" + longi;
Data.lati = "" + lati;
Log.e("longitude : ",""+longi);
Log.e("latitude : ",""+lati);
if(faceboo_name.equals(""))
{
if(dialog!=null){
dialog.cancel();}
timer.cancel();
timer.purge();
Data.homepage_resume = true;
lm = null;
Intent intent = new Intent();
intent.setClass(Kikit.this,MainActivity.class);
startActivity(intent);
finish();
}
else
{
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
{
if(dialog!=null)
dialog.cancel();
Showdata();
}
else
{
error_view.setText(Data.internet_error_msg);
error_view.setVisibility(0);
error_gone();
}
}
}
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
//Toast.makeText(getApplicationContext(), "Location enabled", Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive
// location updates
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 10,locationListener);
} else{
//Toast.makeText(getApplicationContext(), "No Internet Connection.", 2000).show();
buildAlertMessageNoGps();
}
} catch (Exception e) {
// TODO
// Auto-generated
// catch
// block
}
}
else
{
timer.purge();
timer.cancel();
if(attempt == false)
{
attempt = true;
String locationProvider = LocationManager.NETWORK_PROVIDER;
// Or use LocationManager.GPS_PROVIDER
try {
Location lastKnownLocation = lm.getLastKnownLocation(locationProvider);
longi = lastKnownLocation.getLongitude();
lati = lastKnownLocation.getLatitude();
Data.longi = "" + longi;
Data.lati = "" + lati;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("exception in loc fetch", e.toString());
}
Log.e("longitude of last known location : ",""+longi);
Log.e("latitude of last known location : ",""+lati);
if(Data.fb_access_token == "")
{
if(dialog!=null){
dialog.cancel();}
timer.cancel();
timer.purge();
Data.homepage_resume = true;
Intent intent = new Intent();
intent.setClass(Kikit.this,MainActivity.class);
startActivity(intent);
finish();
}
else
{
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
{
if(dialog!=null){
dialog.cancel();}
Showdata();
}
else
{
error_view.setText(Data.internet_error_msg);
error_view.setVisibility(0);
error_gone();
}
}
}
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000);
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your WiFi & mobile network location is disabled , do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id)
{
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
setting_page = true;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
dialog.cancel();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
os.walk is the answer, this will find the first match:
import os
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
And this will find all matches:
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
And this will match a pattern:
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
find('*.txt', '/path/to/dir')
I continue to suspect that your customer/user has some kernel module or driver loaded which
is interfering with the clone()
system call (perhaps some obscure security enhancement,
something like LIDS but more obscure?) or is somehow filling up some of the kernel data
structures that are necessary for fork()
/clone()
to operate (process table, page
tables, file descriptor tables, etc).
Here's the relevant portion of the fork(2)
man page:
ERRORS EAGAIN fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child. EAGAIN It was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered. To exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability. ENOMEM fork() failed to allocate the necessary kernel structures because memory is tight.
I suggest having the user try this after booting into a stock, generic kernel and with only a minimal set of modules and drivers loaded (minimum necessary to run your application/script). From there, assuming it works in that configuration, they can perform a binary search between that and the configuration which exhibits the issue. This is standard sysadmin troubleshooting 101.
The relevant line in your strace
is:
clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)
... I know others have talked about swap and memory availability (and I would recommend that you set up at least a small swap partition, ironically even if it's on a RAM disk ... the code paths through the Linux kernel when it has even a tiny bit of swap available have been exercised far more extensively than those (exception handling paths) in which there is zero swap available.
However I suspect that this is still a red herring.
The fact that free
is reporting 0 (ZERO) memory in use by the cache and buffers is very disturbing. I suspect that the free
output ... and possibly your application issue here, are caused by some proprietary kernel module which is interfering with the memory allocation in some way.
According to the man pages for fork()/clone() the fork() system call should return EAGAIN if your call would cause a resource limit violation (RLIMIT_NPROC) ... however, it doesn't say if EAGAIN is to be returned by other RLIMIT* violations. In any event if your target/host has some sort of weird Vormetric or other security settings (or even if your process is running under some weird SELinux policy) then it might be causing this -ENOMEM failure.
It's pretty unlikely to be a normal run-of-the-mill Linux/UNIX issue. You've got something non-standard going on there.
Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:
if (j % 4 == 0) {
// j is an exact multiple of 4
}
The ?
is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.
You are correct in that it's not "right" to add files to the tags folder.
You've correctly guessed that copy
is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.
In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.
This part of "the book" shows how the command is typically used.
+ (NSString *) getUniqueUUID {
NSError * error;
NSString * uuid = [KeychainUtils getPasswordForUsername:kBuyassUser andServiceName:kIdOgBetilngService error:&error];
if (error) {
NSLog(@"Error geting unique UUID for this device! %@", [error localizedDescription]);
return nil;
}
if (!uuid) {
DLog(@"No UUID found. Creating a new one.");
uuid = [IDManager GetUUID];
uuid = [Util md5String:uuid];
[KeychainUtils storeUsername:USER_NAME andPassword:uuid forServiceName:SERVICE_NAME updateExisting:YES error:&error];
if (error) {
NSLog(@"Error getting unique UUID for this device! %@", [error localizedDescription]);
return nil;
}
}
return uuid;
}
I created the following JSFiddle to demonstrate my approach to your question.
(function() {_x000D_
// Sample arrays_x000D_
var //elements = ["0", "1", "2", "3", "4", "5", "6", "7"],_x000D_
elements = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43"];_x000D_
_x000D_
var splitElements = [],_x000D_
delimiter = 10; // Change this value as needed_x000D_
_x000D_
// parameters: array, number of elements to split the array by_x000D_
if(elements.length > delimiter){_x000D_
splitElements = splitArray(elements, delimiter);_x000D_
}_x000D_
else {_x000D_
// No need to do anything if the array's length is less than the delimiter_x000D_
splitElements = elements;_x000D_
}_x000D_
_x000D_
//Displaying result in console_x000D_
for(element in splitElements){_x000D_
if(splitElements.hasOwnProperty(element)){_x000D_
console.log(element + " | " + splitElements[element]);_x000D_
}_x000D_
}_x000D_
})();_x000D_
_x000D_
function splitArray(elements, delimiter) {_x000D_
var elements_length = elements.length;_x000D_
_x000D_
if (elements_length > delimiter) {_x000D_
var myArrays = [], // parent array, used to store each sub array_x000D_
first = 0, // used to capture the first element in each sub array_x000D_
index = 0; // used to set the index of each sub array_x000D_
_x000D_
for (var i = 0; i < elements_length; ++i) {_x000D_
if (i % delimiter === 0) {_x000D_
// Capture the first element of each sub array from the original array, when i is a modulus factor of the delimiter._x000D_
first = i;_x000D_
} else if (delimiter - (i % delimiter) === 1) {_x000D_
// Build each sub array, from the original array, sliced every time the i one minus the modulus factor of the delimiter._x000D_
index = (i + 1) / delimiter - 1;_x000D_
myArrays[index] = elements.slice(first, i + 1);_x000D_
}_x000D_
else if(i + 1 === elements_length){_x000D_
// Build the last sub array which contain delimiter number or less elements_x000D_
myArrays[index + 1] = elements.slice(first, i + 1);_x000D_
}_x000D_
}_x000D_
// Returned is an array of arrays_x000D_
return myArrays;_x000D_
}_x000D_
}
_x000D_
First of all, I have two examples: an array with less than eight elements, another with an array with more than eight elements (comment whichever one you do not want to use).
I then check for the size of the array, simple but essential to avoid extra computation. From here if the array meets the criteria (array size > delimiter
) we move into the splitArray
function.
The splitArray
function takes in the delimiter (meaning 8, since that is what you want to split by), and the array itself. Since we are re-using the array length a lot, I am caching it in a variable, as well as the first
and last
.
first
represents the position of the first element in an array. This array is an array made of 8 elements. So in order to determine the first element we use the modulus operator.
myArrays
is the array of arrays. In it we will store at each index, any sub array of size 8 or below. This is the key strategy in the algorithm below.
index
represents the index for the myArrays
variable. Every time a sub array of 8 elements or less is to be stored, it needs to be stored in the corresponding index. So if we have 27 elements, that means 4 arrays. The first, second and third array will have 8 elements each. The last will have 3 elements only. So index
will be 0, 1, 2, and 3 respectively.
The tricky part is simply figuring out the math and optimizing it as best as possible. For example else if (delimiter - (i % delimiter) === 1)
this is to find the last element that should go in the array, when an array will be full (example: contain 10 elements).
This code works for every single scenario, you can even change the delimiter
to match any array size you'd like to get. Pretty sweet right :-)
Any questions? Feel free to ask in the comments below.
Here is a full example with the date formatted in YYYY-MM-DD
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="//cdn.jsdelivr.net/webshim/1.14.5/polyfiller.js"></script>
<script>
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
$.webshims.formcfg = {
en: {
dFormat: '-',
dateSigns: '-',
patterns: {
d: "yy-mm-dd"
}
}
};
</script>
<input type="date" />
Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt");
to open a stream to this file.
MacOS just paste in the Terminal:
keytool -list -v -alias androiddebugkey -keystore ~/.android/debug.keystore -storepass android -keypass android
As others have noted, writelines
is a misnomer (it ridiculously does not add newlines to the end of each line).
To do that, explicitly add it to each line:
with open(dst_filename, 'w') as f:
f.writelines(s + '\n' for s in lines)
The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Segment:
def __init__(self, a, b):
self.a = a
self.b = b
def is_between(self, c):
# Check if slope of a to c is the same as a to b ;
# that is, when moving from a.x to c.x, c.y must be proportionally
# increased than it takes to get from a.x to b.x .
# Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
# => c is after a and before b, or the opposite
# that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
# or 1 ( c == a or c == b)
a, b = self.a, self.b
return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and
abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)
Some random example of usage :
a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)
print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)
Html.DropDownList("Types", Model.Types, new { @disabled = "disabled" }) @Html.Hidden(Model.Types) and for save and recover the data, use a hidden control
Updated 10-second countdown using class Clock extends Component
import React, { Component } from 'react';
class Clock extends Component {
constructor(props){
super(props);
this.state = {currentCount: 10}
}
timer() {
this.setState({
currentCount: this.state.currentCount - 1
})
if(this.state.currentCount < 1) {
clearInterval(this.intervalId);
}
}
componentDidMount() {
this.intervalId = setInterval(this.timer.bind(this), 1000);
}
componentWillUnmount(){
clearInterval(this.intervalId);
}
render() {
return(
<div>{this.state.currentCount}</div>
);
}
}
module.exports = Clock;
Use MaxBy
from the morelinq project:
items.MaxBy(i => i.ID);
You could saveAs xlsx. Then you will loose the macros and generate a new workbook with a little less work.
ThisWorkbook.saveas Filename:=NewFileNameWithPath, Format:=xlOpenXMLWorkbook
You need to escape it. (Using Python 3 print function):
>>> print("The boy said \"Hello!\" to the girl")
The boy said "Hello!" to the girl
>>> print('Her name\'s Jenny.')
Her name's Jenny.
See the python page for string literals.
This was a feature request that got fixed in Django 1.3.
Here's the bug: https://code.djangoproject.com/ticket/10427
Basically, if you're running something after 1.3, in Django templates you can do:
{{ form.field.value|default_if_none:"" }}
Or in Jinja2:
{{ form.field.value()|default("") }}
Note that field.value()
is a method, but in Django templates ()
's are omitted, while in Jinja2 method calls are explicit.
If you want to know what version of Django you're running, it will tell you when you do the runserver command.
If you are on something prior to 1.3, you can probably use the fix posted in the above bug: https://code.djangoproject.com/ticket/10427#comment:24
The -Wl,xxx
option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So
gcc -Wl,aaa,bbb,ccc
eventually becomes a linker call
ld aaa bbb ccc
In your case, you want to say "ld -rpath .
", so you pass this to gcc as -Wl,-rpath,.
Alternatively, you can specify repeat instances of -Wl
:
gcc -Wl,aaa -Wl,bbb -Wl,ccc
Note that there is no comma between aaa
and the second -Wl
.
Or, in your case, -Wl,-rpath -Wl,.
.
It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.
node{
def exists = fileExists 'foo'
if (!exists){
new File('foo').mkdir()
}
dir ('foo') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'bar'
if (!exists){
new File('bar').mkdir()
}
dir ('bar') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'baz'
if (!exists){
new File('baz').mkdir()
}
dir ('baz') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
}
You can access the code values for the characters in your string using the ord()
built-in function. If you then need to format this in binary, the string.format()
method will do the job.
a = "test"
print(' '.join(format(ord(x), 'b') for x in a))
(Thanks to Ashwini Chaudhary for posting that code snippet.)
While the above code works in Python 3, this matter gets more complicated if you're assuming any encoding other than UTF-8. In Python 2, strings are byte sequences, and ASCII encoding is assumed by default. In Python 3, strings are assumed to be Unicode, and there's a separate bytes
type that acts more like a Python 2 string. If you wish to assume any encoding other than UTF-8, you'll need to specify the encoding.
In Python 3, then, you can do something like this:
a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))
The differences between UTF-8 and ascii encoding won't be obvious for simple alphanumeric strings, but will become important if you're processing text that includes characters not in the ascii character set.
I think you mean SqlServer but on Oracle you have a hard limit how many IN elements you can specify: 1000.
You can use :
const intersection = array1.filter(element => array2.includes(element));
The entity type 'DisplayFormatAttribute' requires a primary key to be defined.
In my case I figured out the problem was that I used properties like this:
public string LastName { get; set; } //OK
public string Address { get; set; } //OK
public string State { get; set; } //OK
public int? Zip { get; set; } //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; } // NOT OK
Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.
Data Storage:
Specify the utf8mb4
character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4
encoding if a utf8mb4_*
collation is specified (without any explicit character set).
In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8
, which only supports a subset of Unicode characters. I wish I were kidding.
Data Access:
In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4
. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.
Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:
If you're using the PDO abstraction layer with PHP = 5.3.6, you can specify charset
in the DSN:
$dbh = new PDO('mysql:charset=utf8mb4');
If you're using mysqli, you can call set_charset()
:
$mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
If you're stuck with plain mysql but happen to be running PHP = 5.2.3, you can call mysql_set_charset
.
If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'
.
The same consideration regarding utf8mb4
/utf8
applies as above.
Output:
If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).
In PHP, you can use the default_charset
php.ini option, or manually issue the Content-Type
MIME header yourself, which is just more work but has the same effect.
When encoding the output using json_encode()
, add JSON_UNESCAPED_UNICODE
as a second parameter.
Input:
Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding()
does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.
From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:
accept-charset
attribute to all your <form>
tags: <form ... accept-charset="UTF-8">
.<form>
tag.Other Code Considerations:
Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.
You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring
extension.
PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring
function.
To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
The best thing that you can do is to set a function to be called on a given amount of time and this function to check the contents of your textarea.
self.setInterval('checkTextAreaValue()', 50);
Try this for Windows:
npm uninstall -g cordova
Try this for MAC:
sudo npm uninstall -g cordova
You can also add Cordova like this:
If You Want To install the previous version of Cordova through the Node Package Manager (npm):
npm install -g [email protected]
If You Want To install the latest version of Cordova:
npm install -g cordova
Enjoy!
There is no need to remove any .iml
files. Follow this:
File
->
Open...
and choose your newly created build.gradle
Open Existing Project
Delete Existing Project and Import
boolean titleTextfield = driver.findElement(By.id("widget_polarisCommunityInput_113_title")).isDisplayed();
assertFalse(titleTextfield, "Title text field present which is not expected");
Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id
and date
.
ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);
Then when inserting a record add the condition when a conflict is encountered:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value
This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.
You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.
All modern browsers support document.elementFromPoint
and HTMLElement.prototype.click()
, since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:
document.elementFromPoint(x, y).click();
https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
Use a delegated event handler bound to the container:
$('#pg_menu_content').on('click', '#btn_a', function(){
console.log(this.value);
});
That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content
exists when the page loads), and supply a selector in the second parameter to .on()
. When a click occurs on #pg_menu_content
element jQuery checks whether it applied to a child of that element which matches the #btn_a
selector.
Either that or bind a standard (non-delegated) click handler after creating the button.
Either way, within the click handler this
will refer to the button in question, so this.value
will give you its value.
You can use the below code on your string and you will get the complete string without html part.
string title = "<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )".Replace(" ",string.Empty);
string s = Regex.Replace(title, "<.*?>", String.Empty);
The cut command is designed for this exact situation. It will "cut" on any delimiter and then you can specify which chunks should be output.
For instance:
echo "foo bar <foo> bla 1 2 3.4" | cut -d " " -f 6-7
Will result in output of:
2 3.4
-d sets the delimiter
-f selects the range of 'fields' to output, in this case, it's the 6th through 7th chunks of the original string. You can also specify the range as a list, such as 6,7
.
This will also work..
cd ~
source .bashrc
per the docs
Configure and ConfigureServices support environment specific versions of the form Configure{EnvironmentName} and Configure{EnvironmentName}Services:
You can do something like this...
public void ConfigureProductionServices(IServiceCollection services)
{
ConfigureCommonServices(services);
//Services only for production
services.Configure();
}
public void ConfigureDevelopmentServices(IServiceCollection services)
{
ConfigureCommonServices(services);
//Services only for development
services.Configure();
}
public void ConfigureStagingServices(IServiceCollection services)
{
ConfigureCommonServices(services);
//Services only for staging
services.Configure();
}
private void ConfigureCommonServices(IServiceCollection services)
{
//Services common to each environment
}
In android-N, this feature is included in it. check Number-blocking update for android N
Android N now supports number-blocking in the platform and provides a framework API to let service providers maintain a blocked-number list. The default SMS app, the default phone app, and provider apps can read from and write to the blocked-number list. The list is not accessible to other app.
advantage of are:
For more information, see android.provider.BlockedNumberContract
Update an existing project.
To compile your app against the Android N platform, you need to use the Java 8 Developer Kit (JDK 8), and in order to use some tools with Android Studio 2.1, you need to install the Java 8 Runtime Environment (JRE 8).
Open the build.gradle file for your module and update the values as follows:
android {
compileSdkVersion 'android-N'
buildToolsVersion 24.0.0 rc1
...
defaultConfig {
minSdkVersion 'N'
targetSdkVersion 'N'
...
}
...
}
I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used.
The method with count(*)
is unsafe. If another session deletes the row that met the condition after the line with the count(*)
, and before the line with the select ... into
, the code will throw an exception that will not get handled.
The second version from the original post does not have this problem, and it is generally preferred.
That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the count(*)
, but I recommend against it.
I ran these benchmarks on Oracle 10.2.0.1 on 32 bit Windows. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).
SQL>create table t (NEEDED_FIELD number, COND number);
Table created.
SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);
1 row created.
declare
otherVar number;
cnt number;
begin
for i in 1 .. 50000 loop
select count(*) into cnt from t where cond = 1;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 1;
else
otherVar := 0;
end if;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.70
declare
otherVar number;
begin
for i in 1 .. 50000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 1;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:03.06
First Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create a pointer that points to random memory address
*ptr = 20; //Dereference that pointer,
// and assign a value to random memory address.
//Depending on external (not inside your program) state
// this will either crash or SILENTLY CORRUPT another
// data structure in your program.
printf("%d", *ptr); //Print contents of same random memory address
// May or may not crash, depending on who owns this address
return 0;
}
Second Program with comments
#include <stdio.h>
int main(){
int *ptr; //Create pointer to random memory address
int q = 50; //Create local variable with contents int 50
ptr = &q; //Update address targeted by above created pointer to point
// to local variable your program properly created
printf("%d", *ptr); //Happily print the contents of said local variable (q)
return 0;
}
The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.
Using it before is creating code that depends on uninitialized memory which will at best crash but at worst work sometimes, because the random memory address happens to be inside the memory space your program already owns. God help you if it overwrites a data structure you are using elsewhere in your program.
CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:
img {_x000D_
-webkit-filter: invert(1);_x000D_
filter: invert(1);_x000D_
}
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
You can also use join:
yourstring = ''.join(('L','yourstring','LL'))
Result:
>>> yourstring
'LyourstringLL'
This is Exactly you must type on terminal to run your project without DEBUG = TRUE and then you see all assets (static) file is loading correctly On local server .
python manage.py runserver --insecure
--insecure
: it means you can run server without security mode
Same thing.. makes no difference at all... htm was used in the days where only 3 letter extensions were common.
On modern browsers you can try with the pointer-events css property (but it leads to the impossibility to detect mouse events on the parent node):
p {
position: relative;
background-color: blue;
color:#ffffff;
padding:0px 10px;
pointer-events:none;
}
p::before {
content: attr(data-before);
margin-left:-10px;
margin-right:10px;
position: relative;
background-color: red;
padding:0px 10px;
pointer-events:auto;
}
When the event target is your "p" element, you know it is your "p:before".
If you still need to detect mouse events on the main p, you may consider the possibility to modify your HTML structure. You can add a span tag and the following style:
p span {
background:#393;
padding:0px 10px;
pointer-events:auto;
}
The event targets are now both the "span" and the "p:before" elements.
Example without jquery: http://jsfiddle.net/2nsptvcu/
Example with jquery: http://jsfiddle.net/0vygmnnb/
Here is the list of browsers supporting pointer-events: http://caniuse.com/#feat=pointer-events
Any() returns true if any of the elements in a collection meet your predicate's criteria.
Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.
Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7