From Official Docs
Correctly configuring your shell on Windows is a matter of locating the right executable and updating the setting. Below is a list of common shell executables and their default locations.
There is also the convenience command Select Default Shell that can be accessed through the command palette which can detect and set this for you.
So you can open a command palette using ctrl+shift+p
, use the command Select Default Shell, then it displays all the available command line interfaces, select whatever you want, VS code sets that as default integrated terminal for you automatically.
If you want to set it manually find the location of executable of your cli and open user settings of vscode(ctrl+,
) then set
"terminal.integrated.shell.windows":"path/to/executable.exe"
Example for gitbash on windows7:
"terminal.integrated.shell.windows":"C:\\Users\\stldev03\\AppData\\Local\\Programs\\Git\\bin\\bash.exe",
In my situation, I did not have an export at the bottom of my webpack.config.js file. Simply adding
export default Config;
solved it.
<module name="Checker">
<module name="SuppressionCommentFilter"/>
<module name="TreeWalker">
<module name="FileContentsHolder"/>
</module>
</module>
To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:
<module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
<property name="onCommentFormat" value="END GENERATED CODE"/>
</module>
//BEGIN GENERATED CODE
@Override
public boolean equals(Object obj) { ... } // No violation events will be reported
@Override
public int hashCode() { ... } // No violation events will be reported
//END GENERATED CODE
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe
(the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe
you'll get output in your console window.
Here is very good visual representation about continue and break statements
If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)
yes it can have same value....the reason for giving numbers to load-on-startup is to define a sequence for server to load all the servlet. servlet with 0 load-on-startup value will load first and servlet with value 1 will load after that.
if two servlets will have the same value for load-on-startup than it will be loaded how they are declared in the web.xml from top to bottom. the servlet which comes first in the web.xml will be loaded first and the other will be loaded after that.
The problem is that you're targeting the button, but it's the A Tag that causes the text-decoration: underline. So if you target the A tag then it should work.
a:hover, a:focus { text-decoration: none;}
Now this become even simpler and more flexible by using CSS GRID.You just have to overlap the blured background(imgbg) with the text(h2)
<div class="container">
<div class="imgbg"></div>
<h2>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Facilis enim
aut rerum mollitia quas voluptas delectus facere magni cum unde?:)
</h2>
</div>
and the css:
.container {
display: grid;
width: 30em;
}
.imgbg {
background: url(bg3.jpg) no-repeat center;
background-size: cover;
grid-column: 1/-1;
grid-row: 1/-1;
filter: blur(4px);
}
.container h2 {
text-transform: uppercase;
grid-column: 1/-1;
grid-row: 1/-1;
z-index: 2;
}
To formalize what someone else used setNames for:
add_row <- function(original_data, new_vals_list){
# appends row to dataset while assuming new vals are ordered and classed appropriately.
# new_vals must be a list not a single vector.
rbind(
original_data,
setNames(data.frame(new_vals_list), colnames(original_data))
)
}
It preserves class when legal and passes errors elsewhere.
m <- mtcars[ ,1:3]
m$cyl <- as.factor(m$cyl)
str(m)
#'data.frame': 32 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Factor preserved when adding 4, even though it was passed as a numeric.
str(add_row(m, list(20,4,160)))
#'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Attempting to pass a non- 4,6,8 would return an error that factor level is invalid.
str(add_row(m, list(20,3,160)))
# 'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 3) :
invalid factor level, NA generated
<style type="text/css">
#warning-message { display: none; }
@media only screen and (orientation:portrait){
#wrapper { display:none; }
#warning-message { display:block; }
}
@media only screen and (orientation:landscape){
#warning-message { display:none; }
}
</style>
....
<div id="wrapper">
<!-- your html for your website -->
</div>
<div id="warning-message">
this website is only viewable in landscape mode
</div>
You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.
I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.
Update
I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.
Another Update
So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.
ps -eo pid,etime,cmd|sort -n -k2
I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:
DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");
using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.
I think no one actually has answered to the first question:
Why did they create those variables?
Those variables aren't strictly necessary. It's true. You can perfectly do something like this:
MONTH_CHOICES = (
("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
# ....
("DECEMBER", "December"),
)
month = models.CharField(max_length=9,
choices=MONTH_CHOICES,
default="JANUARY")
Why using variables is better? Error prevention and logic separation.
JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)
MONTH_CHOICES = (
(JAN, "January"),
(FEB, "February"),
(MAR, "March"),
# ....
(DEC, "December"),
)
Now, imagine you have a view where you create a new Model instance. Instead of doing this:
new_instance = MyModel(month='JANUARY')
You'll do this:
new_instance = MyModel(month=MyModel.JAN)
In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.
Also you can use 'os.popen'. Example:
import os
command = os.popen('ls -al')
print(command.read())
print(command.close())
Output:
total 16
drwxr-xr-x 2 root root 4096 ago 13 21:53 .
drwxr-xr-x 4 root root 4096 ago 13 01:50 ..
-rw-r--r-- 1 root root 1278 ago 13 21:12 bot.py
-rw-r--r-- 1 root root 77 ago 13 21:53 test.py
None
I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)
Thanks!
with JQuery .toggle()
you can accomplish it easily
$( ".target" ).toggle();
Like this http://jsfiddle.net/8ha9e/1/
Add colspan="2"
to the 3rd <th>
and then have 4 <td>
's in your second row.
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th scope="col" colspan="2">Header</th>
</tr>
<tr>
<th scope="row"> </th>
<td> </td>
<!-- The following two cells will appear under the same header -->
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
I asked a 4-year-old to solve this problem. He sorted the numbers and then counted along. This has a space requirement of O(kitchen floor), and it works just as easy however many balls are missing.
Everyone is correct here but writing same query twice is not a good way of programming ... so I have another way to do the full join in mysql which is as follows
SELECT
user_id , user_name, user_department
FROM
(SELECT
user_id , user_name , NULL as user_department
FROM
tb_users
UNION
SELECT
user_id ,NULL as user_name , user_department
FROM
tb_departments
) as t group by user_id
As other answers note, the correct way to find the Java home directory is to use /usr/libexec/java_home
.
The official documentation for this is in Apple's Technical Q&A QA1170: Important Java Directories on OS X: https://developer.apple.com/library/mac/qa/qa1170/_index.html
The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.
plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) ) )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
}
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))
if you are getting this exception again and again then download my-sql connector and paste in tomcat/WEB-INF/lib folder...note that some times WEB-INF folder does not contains lib folder, at that time manually create lib folder and paste mysql connector in that folder..definitely this will work.if still you got problem then check that your jdk must match your system. i.e if your system is 64 bit then jdk must be 64 bit
You need to wait until the image is loaded before you draw it. Try this instead:
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}
i.e. draw the image in the onload callback of the image.
For Ubuntu 14.04
Check core dump enabled:
ulimit -a
One of the lines should be :
core file size (blocks, -c) unlimited
If not :
gedit ~/.bashrc
and add ulimit -c unlimited
to end of file and save, re-run terminal.
Build your application with debug information :
In Makefile -O0 -g
Run application that create core dump (core dump file with name ‘core’ should be created near application_name file):
./application_name
Run under gdb:
gdb application_name core
Here is another simple method using del
in one liner:
for key in e_keys: del your_dict[key]
e_keys
is the list of the keys to be excluded. It will update your dict rather than giving you a new one.
If you want a new output dict, then make a copy of the dict before deleting:
new_dict = your_dict.copy() #Making copy of dict
for key in e_keys: del new_dict[key]
I had the same problem, and I felt on your post.
I think the easiest way to solve this issue is by using redis Hashtable.
It allows you to save a Hash, with different fields and values associated with every field.
To get all the fiels and values client.HGETALLL
does the trick. It returns an array of
all the fields followed by their values.
More informations here https://redis.io/commands/hgetall
If you've arrived at this because you have cloned a git project into the existing workspace and now you want to promote that workspace to a full fledged project then you should use the 'Git Repositories' view -> select 'Working Directory' -> Import Projects -> Existing projects.
It is Safari specific, at least at time of writing, being introduced in Safari 9.0. From the "What's new in Safari?" documentation for Safari 9.0:
Viewport Changes
Viewport meta tags using
"width=device-width"
cause the page to scale down to fit content that overflows the viewport bounds. You can override this behavior by adding"shrink-to-fit=no"
to your meta tag as shown below. The added value will prevent the page from scaling to fit the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
In short, adding this to the viewport meta tag restores pre-Safari 9.0 behaviour.
Here's a worked visual example which shows the difference upon loading the page in the two configurations.
The red section is the width of the viewport and the blue section is positioned outside the initial viewport (eg left: 100vw
). Note how in the first example the page is zoomed to fit when shrink-to-fit=no
is omitted (thus showing the out-of-viewport content) and the blue content remains off screen in the latter example.
The code for this example can be found at https://codepen.io/davidjb/pen/ENGqpv.
In my project I did it like this:
@register.simple_tag()
def format_string(string: str, *args: str) -> str:
"""
Adds [args] values to [string]
String format [string]: "Drew %s dad's %s dead."
Function call in template: {% format_string string "Dodd's" "dog's" %}
Result: "Drew Dodd's dad's dog's dead."
"""
return string % args
Here, the string you want concatenate and the args can come from the view, for example.
In template and using your case:
{% format_string 'shop/%s/base.html' shop_name as template %}
{% include template %}
The nice part is that format_string can be reused for any type of string formatting in templates
I ended up here after attempting to follow Ryan Bate's tutorial on deploying to AWS EC2 with rubber. Here is what happened for me: We created a new app using "
rails new blog -d postgresql
Obviosuly this creates a new app with pg as the database, but the database was not made yet. With sqlite, you just run rake db:migrate, however with pg you need to create the pg database first. Ryan did not do this step. The command is rake db:create:all
, then we can run rake db:migrate
The second part is changing the database.yml file. The default for the username when the file is generated is 'appname'. However, chances are your role for postgresql admin is something different (at least it was for me). I changed it to my name (see above advice about creating a role name) and I was good to go.
Hope this helps.
If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P
I would also recommend using the Perl debugger.
However, since you asked about something like shell's -x
have a look at the Devel::Trace module which does something similar.
The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:
$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test
It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:
$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz
However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut
alone. In order to effectively use cut
to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.
If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk
instead. E.g., to use awk
to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:
$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d
It is a broken/very hard to use replacement for the "center" tag. It comes in handy when you need broken tables and non-working centering for blocks and text.
When you make a call to using namespace <some_namespace>;
all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.
E.g. if you add using namespace std;
you can write just cout
instead of std::cout
when calling the operator cout
defined in the namespace std
.
This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace
you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:
#include <iostream>
using std::cout;
int main() {
cout << "Hello world!";
return 0;
}
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538
as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:
css:
a.disabled {
opacity: 0.5;
pointer-events: none;
cursor: default;
}
jQuery:
$('.disableAfterClick').click(function (e) {
$(this).addClass('disabled');
});
Long time no Perl
while(<STDIN>) {
next unless /:\s*(\S+)\s+\(([^\)]+)\)\s*(\*?)/;
print "|$1|$2|$3|\n";
}
SELECT TOP (@count) * FROM SomeTable
This will only work with SQL 2005+
this question shows up pretty high on a Google search and worked for the most part! I did find that Salman Zaidi's answer was partially correct for iOS 7.
You need to make a modification to the "reverting" code. I found that the following for reverting worked perfectly:
textField.layer.cornerRadius = 0.0f;
textField.layer.masksToBounds = YES;
textField.layer.borderColor = [[UIColor blackColor] CGColor];
textField.layer.borderWidth = 0.0f;
I understand that this is most likely due to changes in iOS 7.
Use suppressWarnings()
:
suppressWarnings(as.numeric(c("1", "2", "X")))
[1] 1 2 NA
This suppresses warnings.
It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:
ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;
You would do that by providing a fully qualified name, e.g.:
SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id
Which would give you the id of tbl_names
Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })
In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
//xmlhttp.data and shtuff
// ...our code here...
}
else
{
alert("Problem retrieving data");
}
}
}
You can enable whitespace trimming at file save time from settings:
"files.trimTrailingWhitespace": true
setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).
Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf
You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:
FormBorderStyle FixedToolWindow
ShowInTaskBar False
StartPosition CenterScreen
To show it use myNewMessageBoxInstance.ShowDialog();
. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox
and call it btnOK
. Set the DialogResult
property in the property window to DialogResult.OK
. When that button is pressed it would return the OK result:
MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
// etc
}
It would be advisable to add your own Show method that takes the text and other options you require:
public DialogResult Show(string text, Color foreColour)
{
lblText.Text = text;
lblText.ForeColor = foreColour;
return this.ShowDialog();
}
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
This might not work for everyone, but I updated node and it fixed the issue for me when none of the above did
grep -n "YOUR SEARCH STRING" * > output-file
The -n
will print the line number and the >
will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe |
for example:
grep -n "test" * | grep -v "mytest" > output-file
will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v
) - and will redirect the result to an output file.
A few good grep-tips can be found on this post
function inside a function or so called nested functions are very usable if you need to do some recursion processes such as looping true multiple layer of array or a file tree without multiple loops or sometimes i use it to avoid creating classes for small jobs which require dividing and isolating functionality among multiple functions. but before you go for nested functions you have to understand that
so is this mean you cant use nested functions? No, you can with the below workarounds
first method is to block the child function being re declaring into global function stack by using conditional block with function exists, this will prevent the function being declared multiple times into global function stack.
function myfunc($a,$b=5){
if(!function_exists("child")){
function child($x,$c){
return $c+$x;
}
}
try{
return child($a,$b);
}catch(Exception $e){
throw $e;
}
}
//once you have invoke the main function you will be able to call the child function
echo myfunc(10,20)+child(10,10);
and the second method will be limiting the function scope of child to local instead of global, to do that you have to define the function as a Anonymous function and assign it to a local variable, then the function will only be available in local scope and will re declared and invokes every time you call the main function.
function myfunc($a,$b=5){
$child = function ($x,$c){
return $c+$x;
};
try{
return $child($a,$b);
}catch(Exception $e){
throw $e;
}
}
echo myfunc(10,20);
remember the child will not be available outside the main function or global function stack
If anyone looking with time and timezone, this is for you
{{data.ct | date :'dd-MMM-yy h:mm:ss a '}}
add z for time zone at the end of date and time format
{{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}
I might be wrong, but a solution picking up bits and pieces. Perhaps, as I still learning, is that the functions does many things in the same one. Do not hesitate to correct me, please.
const totalSum = (num) => [...num + ' '].map(Number).reduce((a, b) => a + b);
So we take the parameter and convert it to and arr, adding empty spaces. We do such operation in every single element and push it into a new array with the map method. Once splited, we use reduce to sum all the elements and get the total.
As I said, don't hesitate to correct me or improve the function if you see something that I don't.
Almost forgot, just in case:
const totalSum = (num) => ( num === 0 || num < 0) ? 'I need a positive number' : [...num + ' '].map(Number).reduce((a, b) => a + b);
If negatives numbers or just plain zero go down as parameters. Happy coding to us all.
I was searching for something like this, because I've got to check which of all my selects are disabled.
So I use this:
let select= $("select");
for (let i = 0; i < select.length; i++) {
const element = select[i];
if(element.disabled == true ){
console.log(element)
}
}
The top answer is much better in terms of breadth and depth of information given, but it seems like if you wanted your problem fixed almost immediately, and don't mind trodding on some of the basic principles of version control, you could ...
Switch to master
$ git checkout upstream master
Delete your unwanted branch. (Note: it must be have the -D, instead of the normal -d flag because your branch is many commits ahead of the master.)
$ git branch -d <branch_name>
Create a new branch
$ git checkout -b <new_branch_name>
You can also do the following:
txt = "Hello World!"
print (*txt, sep='\n')
This does not use loops but internally print statement takes care of it.
*
unpacks the string into a list and sends it to the print statement
sep='\n'
will ensure that the next char is printed on a new line
The output will be:
H
e
l
l
o
W
o
r
l
d
!
If you do need a loop statement, then as others have mentioned, you can use a for loop like this:
for x in txt: print (x)
Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.
var title = title || 'Error';
var msg = msg || 'Error on Request';
Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:
- false.
- 0 (zero)
- "" (empty string)
- null.
- undefined.
- NaN (a special Number value meaning Not-a-Number!)
So in the line
var title = title || 'Error';
If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).
If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.
It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.
i.e.
return ("" || undefined)
returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running
var foo = undefined
foo = foo || ""
foo would be set to ""
With an updated VS Code you can do it in the following manner:
Hit (Ctrl+P) and type:
ext install cpptools
Open a folder (Ctrl+K & Ctrl+O) and create a new file inside the folder with the extension .cpp (ex: hello.cpp):
Type in your code and hit save.
Hit (Ctrl+Shift+P and type, Configure task runner
and then select other
at the bottom of the list.
Create a batch file in the same folder with the name build.bat and include the following code to the body of the file:
@echo off
call "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x64
set compilerflags=/Od /Zi /EHsc
set linkerflags=/OUT:hello.exe
cl.exe %compilerflags% hello.cpp /link %linkerflags%
Edit the task.json file as follows and save it:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "build.bat",
"isShellCommand": true,
//"args": ["Hello World"],
"showOutput": "always"
}
Hit (Ctrl+Shift+B to run Build task. This will create the .obj and .exe files for the project.
For debugging the project, Hit F5 and select C++(Windows).
In launch.json file, edit the following line and save the file:
"program": "${workspaceRoot}/hello.exe",
Hit F5.
with open("filename.txt", "w+") as file:
for line in file:
print line
This with
statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for
loop
From: http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the nitty gritty.
Expression. print()
behaves like a function in that you can do:
$ret = print "Hello World"
; And $ret
will be 1
. That means that print
can be used as part of a more complex expression where echo cannot. An
example from the PHP Manual:
$b ? print "true" : print "false";
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though. Only ,
AND
OR
XOR
are lower.
echo expression [, expression[,
expression] ... ]
But echo ( expression, expression )
is not valid.
This would be valid: echo ("howdy"),("partner")
; the same as: echo
"howdy","partner"
; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)So, echo without parentheses can take multiple parameters, which get concatenated:
echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
print()
can only take one parameter:
print ("and a 123");
print "and a 123";
A few things happening here:
This should work:
var http = require('http')
, fs = require('fs')
, options
options = {
host: 'www.google.com'
, port: 80
, path: '/images/logos/ps_logo2.png'
}
var request = http.get(options, function(res){
var imagedata = ''
res.setEncoding('binary')
res.on('data', function(chunk){
imagedata += chunk
})
res.on('end', function(){
fs.writeFile('logo.png', imagedata, 'binary', function(err){
if (err) throw err
console.log('File saved.')
})
})
})
I had the same issue caused by importing the internal version of 'takeUntil' instead of the operators Change
import { takeUntil } from 'rxjs/internal/operators/takeUntil';
to
import { takeUntil } from 'rxjs/operators';
This happen also for other operators
It's between the Z and the C on your keyboard.
You can use this as a generic solution:
import os
def getParentDir(path, level=1):
return os.path.normpath( os.path.join(path, *([".."] * level)) )
You can use
ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);
that's work for me
To add to the above post^^:
If either of the services are not running, it might simply just be because they need to be installed/configured. This is easy to do straight from the WampManager Icon.
WampManager Icon -> Apache -> Service -> Install Service
You should get a command prompt pop-up if port 80 is free (if not, see above post):
'Your port 80 is available. Install will proceed.
Press Enter to continue...'
WampManager Icon -> MySQL -> Service -> Install Service
WampManager Icon -> Restart All Services
The icon should now turn green :)
Be careful, reset --hard
will remove your local (uncommitted) modifications, too.
git reset --hard HEAD^
note: if you're on windows you'll need to quote the HEAD^ so
git reset --hard "HEAD^"
If you want to revert the commit WITHOUT throwing away work, use the --soft flag instead of --hard
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Temporarily changing dirs works well for importing:
cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)
My favourite is to extend jQuery with this tiny convenience:
$.fn.exists = function () {
return this.length !== 0;
}
Used like:
$("#notAnElement").exists();
More explicit than using length.
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct
and will work with either factors or characters.
Most of Time, it was occured due to AppPool Setting.
Check the following to resolve this
The following Images show these setting in IIS
My solution:
First create "<style>" tags with an ID.
<style id="YourID">
.YourClass {background-color:red}
</style>
Then, I create a function in JavaScript like this:
document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'
Worked like a charm for me.
import UIKit
class ViewController: UIViewController {
var getdata = NSMutableData()
@IBOutlet weak var password_txt: UITextField!
@IBOutlet weak var mobile_txt: UITextField!
@IBOutlet weak var email_txt: UITextField!
@IBOutlet weak var name_txt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func RegAction(_ sender: UIButton) {
let url = URL(string: "https//.....")
var requrl = URLRequest(url: url!)
requrl.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content_type")
requrl.httpMethod = "post"
let postString = "name=\(name_txt.text!)&email=\(email_txt.text!)&mobile=\(mobile_txt.text!)&password=\(password_txt.text!)"
print("poststring-->>",postString)
requrl.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: requrl){(data,response,error) in
let mydata = data
do{
print("mydata",mydata!)
do{
self.getdata.append(mydata!)
let jsondata = try JSONSerialization.jsonObject(with: self.getdata as Data, options: [])
print("jsondata-->",jsondata)
}
}
catch
{
print("error-->",error.localizedDescription)
}
};
task.resume()
}
}
`GET METHOD`
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var dataarray = [[String: Any]]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataarray.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 450.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let item = dataarray[indexPath.row]
cell.name_txt.text = item["name"]as? String ?? ""
cell.pname_txt.text = item["realname"]as? String ?? ""
cell.team_txt.text = item["team"]as? String ?? ""
cell.firstapp_txt.text = item["firstappearance"]as? String ?? ""
cell.Createdby_txt.text = item["createdby"]as? String ?? ""
cell.Publisher_txt.text = item["publisher"]as? String ?? ""
if item["imageurl"]as? String ?? "" != ""{
let url = URL(string: item["imageurl"]as? String ?? "")
if url != nil{
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
cell.imgvw.image = UIImage(data: data!)
}
}
return cell
}
@IBOutlet weak var apiTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
guard let url = URL(string: "https://www.simplifiedcoding.net/demos/marvel/")
else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: []) as? [[String:Any]] ?? [[:]]
print("jsonResponse---->",jsonResponse) //Response result
self.dataarray = jsonResponse
DispatchQueue.main.async {
self.apiTable.reloadData()
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
}
There are many reasons to discourage including a .cpp file, but it isn't strictly disallowed. Your example should compile fine.
The problem is probably that you're compiling both main.cpp and foop.cpp, which means two copies of foop.cpp are being linked together. The linker is complaining about the duplication.
In order to make a pull request you need to do the following steps:
It took me a while to figure this, hope this will help someone.
If you are using active directory login u need to check password and username.
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.
def foo():
print(self.bar)
>NameError: name 'self' is not defined
def foo(self):
print(self.bar)
Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.
You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.
Just download the jar and import it into your classpath, or add it as a maven dependency:
<dependency>
<groupId>com.jtattoo</groupId>
<artifactId>JTattoo</artifactId>
<version>1.6.11</version>
</dependency>
Here is a list of some of the cool themes they have available:
Regards
Double quotes around the filename in the header is the standard per MDN web docs. Omitting the quotes creates multiple opportunities for problems arising from characters in the filename.
Set in package.json
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
And link react-native link
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
DISTINCT
to remove duplicate GROUPING SETS
from the GROUP BY
clauseIn a completely silly example using GROUPING SETS()
in general (or the special grouping sets ROLLUP()
or CUBE()
in particular), you could use DISTINCT
in order to remove the duplicate values produced by the grouping sets again:
SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)
With DISTINCT
:
actors
------
NULL
a
b
Without DISTINCT
:
actors
------
a
b
NULL
a
b
a
b
But why, apart from making an academic point, would you do that?
DISTINCT
to find unique aggregate function valuesIn a less far-fetched example, you might be interested in the DISTINCT
aggregated values, such as, how many different duplicate numbers of actors are there?
SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors
Answer:
count
-----
2
DISTINCT
to remove duplicates with more than one GROUP BY
columnAnother case, of course, is this one:
SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id
With DISTINCT
:
actors count
-------------
a 2
b 1
Without DISTINCT
:
actors count
-------------
a 2
b 1
b 1
For more details, I've written some blog posts, e.g. about GROUPING SETS
and how they influence the GROUP BY
operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).
Difference between "return" and "print" can also be found in the following example:
RETURN:
def bigger(a, b):
if a > b:
return a
elif a <b:
return b
else:
return a
The above code will give correct results for all inputs.
PRINT:
def bigger(a, b):
if a > b:
print a
elif a <b:
print b
else:
print a
NOTE: This will fail for many test cases.
ERROR:
----
FAILURE
: Test case input: 3, 8.
Expected result: 8
FAILURE
: Test case input: 4, 3.
Expected result: 4
FAILURE
: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases
You want to use regexp_substr()
for this. This should work for your example:
select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
Here, by the way, is the SQL Fiddle.
Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace()
for the first part:
select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
And here is this corresponding SQL Fiddle.
I think there are more solutions!
You can start the app, and here are 3 things you can do:
Settings
> Manage License...
> Remove License
, and that removes for all Jetbrains products*.File
> Close Project
, and follow the first step.Help
> Register...
> Remove license
.*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.
Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.
This is called fire and forget, and there is an extension for that.
Consumes a task and doesn't do anything with it. Useful for fire-and-forget calls to async methods within async methods.
Install nuget package.
Use:
MyAsyncMethod().Forget();
You can easily use imcache. A sample code is below.
void example(){
Cache<Integer,Integer> cache = CacheBuilder.heapCache().
cacheLoader(new CacheLoader<Integer, Integer>() {
public Integer load(Integer key) {
return null;
}
}).capacity(10000).build();
}
For this, I use FLAG_ACTIVITY_CLEAR_TOP
flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK
)
and launchMode = "singleTask"
in manifest for launched activity.
Seems like it works as I need - activity does not restart and all other activities are closed.
Every solution posted here assumes that you know the dimensions of your img
, which is not a common scenario. Also, planting the dimensions into the solution is painful.
Simply set:
/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;
or
/* for the img inside your div */
display: block;
margin: 0 auto;
That's all.
Note, that you'll also have to set an initial min-width
for your outer div
.
If you have access to PHP 5.3, the intl extension is very nice for doing things like this.
Here's an example from the manual:
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
$fmt->format(0); //0 for current time/date
In your case, you can do:
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/New_York');
$fmt->format($datetime); //where $datetime may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime().
As you can set a Timezone such as America/New_York
, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.
Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.
The use of fork
and exec
exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.
The fork
call basically makes a duplicate of the current process, identical in almost every way. Not everything is copied over (for example, resource limits in some implementations) but the idea is to create as close a copy as possible.
The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork
- the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork
call works - if not, no child is created and the parent gets an error code.
The exec
call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.
So, fork
and exec
are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find
- the shell forks, then the child loads the find
program into memory, setting up all command line arguments, standard I/O and so forth.
But they're not required to be used together. It's perfectly acceptable for a program to fork
itself without exec
ing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork
a copy of themselves to process a specific request while the parent goes back to listening.
Similarly, programs that know they're finished and just want to run another program don't need to fork
, exec
and then wait
for the child. They can just load the child directly into their process space.
Some UNIX implementations have an optimized fork
which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork
until the program attempts to change something in that space. This is useful for those programs using only fork
and not exec
in that they don't have to copy an entire process space.
If the exec
is called following fork
(and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.
Note that there is a whole family of exec
calls (execl
, execle
, execve
and so on) but exec
in context here means any of them.
The following diagram illustrates the typical fork/exec
operation where the bash
shell is used to list a directory with the ls
command:
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | ls |
V +--------+
+--------+ |
| pid=7 | | exits
| ppid=4 | <---------------+
| bash |
+--------+
|
| continues
V
I looked for a solution to this problem, and came across the present page. I implemented the above solution:
$("#testdiv",opener.document) //doesn't work
But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.
I found this working solution on another stackoverflow page: how to access parent window object using jquery?
From which I got this working solution:
window.opener.$("#testdiv") //This works.
if path.exists(Score_file):
try :
with open(Score_file , "rb") as prev_Scr:
return Unpickler(prev_Scr).load()
except EOFError :
return dict()
You can use the CYCLE option, shown below:
CREATE SEQUENCE test_seq
MINVALUE 0
MAXVALUE 100
START WITH 0
INCREMENT BY 1
CYCLE;
In this case, when the sequence reaches MAXVALUE (100), it will recycle to the MINVALUE (0).
In the case of a decremented sequence, the sequence would recycle to the MAXVALUE.
Lets say we have a variable called x, as below:
var x;
following statement is valid,
x = 10;
x = "a";
x = 0;
x = undefined;
x = null;
1. Number:
x = 10;
if(x){
//True
}
and for x = undefined
or x = 0
(be careful here)
if(x){
//False
}
2. String x = null
, x = undefined
or x = ""
if(x){
//False
}
3 Boolean x = false
and x = undefined
,
if(x){
//False
}
By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.
Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:
>>> mydict["Apple"]
{'American': '16', 'Mexican': 10, 'Chinese': 5}
And getting how many of them are American (16), do like this:
>>> mydict["Apple"]["American"]
'16'
Tom's solution works great, but only works with TextView and EditText.
If you want to cover most of the views (RadioGroup, TextView, Checkbox...), I created a method doing that :
protected void changeChildrenFont(ViewGroup v, Typeface font){
for(int i = 0; i < v.getChildCount(); i++){
// For the ViewGroup, we'll have to use recursivity
if(v.getChildAt(i) instanceof ViewGroup){
changeChildrenFont((ViewGroup) v.getChildAt(i), font);
}
else{
try {
Object[] nullArgs = null;
//Test wether setTypeface and getTypeface methods exists
Method methodTypeFace = v.getChildAt(i).getClass().getMethod("setTypeface", new Class[] {Typeface.class, Integer.TYPE});
//With getTypefaca we'll get back the style (Bold, Italic...) set in XML
Method methodGetTypeFace = v.getChildAt(i).getClass().getMethod("getTypeface", new Class[] {});
Typeface typeFace = ((Typeface)methodGetTypeFace.invoke(v.getChildAt(i), nullArgs));
//Invoke the method and apply the new font with the defined style to the view if the method exists (textview,...)
methodTypeFace.invoke(v.getChildAt(i), new Object[] {font, typeFace == null ? 0 : typeFace.getStyle()});
}
//Will catch the view with no such methods (listview...)
catch (Exception e) {
e.printStackTrace();
}
}
}
}
This method will get back the style of the view set in XML (bold, italic...) and apply them if they exists.
For the ListView, I always create an adapter, and I set the font inside getView.
If using the fasterxml then,
these changes might be needed
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.node.ObjectNode;
in main method--
use
SimpleModule module =
new SimpleModule("PolymorphicAnimalDeserializerModule");
instead of
new SimpleModule("PolymorphicAnimalDeserializerModule",
new Version(1, 0, 0, null));
and in Animal deserialize() function, make below changes
//Iterator<Entry<String, JsonNode>> elementsIterator = root.getFields();
Iterator<Entry<String, JsonNode>> elementsIterator = root.fields();
//return mapper.readValue(root, animalClass);
return mapper.convertValue(root, animalClass);
This works for fasterxml.jackson. If it still complains of the class fields. Use the same format as in the json for the field names (with "_" -underscore). as this
//mapper.setPropertyNamingStrategy(new CamelCaseNamingStrategy());
might not be supported.
abstract class Animal
{
public String name;
}
class Dog extends Animal
{
public String breed;
public String leash_color;
}
class Cat extends Animal
{
public String favorite_toy;
}
class Bird extends Animal
{
public String wing_span;
public String preferred_food;
}
Depending on the AWK
implementation are you using ==
is ok or not.
Have you tried ~
?. For example, if you want $1 to be "hello":
awk '$1 ~ /^hello$/{ print $3; }' <infile>
^
means $1 start, and $
is $1 end.
With the solutions already discussed above the most reliable one is using Browsermob-Proxy
But while working with the remote grid machine, Browsermob-proxy isn't really helpful.
This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.
How to download the Modheader? Link
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File(C://Downloads//modheader//modheader.crx));
// Set the Desired capabilities
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
// Instantiate the chrome driver with capabilities
WebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
.
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");
Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
Javascript
.
((Javascript)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ title: 'Selenium', hideComment: true, appendMode: '',
headers: [
{enabled: true, name: 'token-1', value: 'value-1', comment: ''},
{enabled: true, name: 'token-2', value: 'value-2', comment: ''}
],
respHeaders: [],
filters: []
}]));");
Where token-1
, value-1
, token-2
, value-2
are the request headers and values that are to be added.
Now navigate to the required web-application.
driver.get("your-desired-website");
The problem seems that your python version and the library yoiu want to install is not matching versionally. Ex: If Django is Django3 and your python version is 2.7, you may get this error.
"After installing is running 'python' still ran Python 2.6 and PATH was not updated."
1- Install latest version of Python 2- Change your PATH manually as python38 and compare them. 3- Try to reinstall.
I solved this problem as replacing PATH manually with the latest version of Python. As for Windows: ;C:\python38\Scripts
The following is an instantiation of the various "just print it" suggestions. I found it instructive.
#include "stdio.h"
int main() {
static int x = 5;
static int *p = &x;
printf("(int) p => %d\n",(int) p);
printf("(int) p++ => %d\n",(int) p++);
x = 5; p = &x;
printf("(int) ++p => %d\n",(int) ++p);
x = 5; p = &x;
printf("++*p => %d\n",++*p);
x = 5; p = &x;
printf("++(*p) => %d\n",++(*p));
x = 5; p = &x;
printf("++*(p) => %d\n",++*(p));
x = 5; p = &x;
printf("*p++ => %d\n",*p++);
x = 5; p = &x;
printf("(*p)++ => %d\n",(*p)++);
x = 5; p = &x;
printf("*(p)++ => %d\n",*(p)++);
x = 5; p = &x;
printf("*++p => %d\n",*++p);
x = 5; p = &x;
printf("*(++p) => %d\n",*(++p));
return 0;
}
It returns
(int) p => 256688152
(int) p++ => 256688152
(int) ++p => 256688156
++*p => 6
++(*p) => 6
++*(p) => 6
*p++ => 5
(*p)++ => 5
*(p)++ => 5
*++p => 0
*(++p) => 0
I cast the pointer addresses to int
s so they could be easily compared.
I compiled it with GCC.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
Empty just check is the refered variable/array has an value if you check the php doc(empty) you'll see this things are considered emtpy
* "" (an empty string) * 0 (0 as an integer) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class)
while isset check if the variable isset and not null which can also be found in the php doc(isset)
A simple Approach can be if your Columns are of Simple Type like String
public static IEnumerable<MyObject> WhereQuery(IEnumerable<MyObject> source, string columnName, string propertyValue)
{
return source.Where(m => { return m.GetType().GetProperty(columnName).GetValue(m, null).ToString().StartsWith(propertyValue); });
}
I made some tests to compare database performance between UTF-8 and UTF-16 in MySQL.
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
This will do the job:
<div style="position:absolute; right:0;">Hello world</div>
_x000D_
I assume you don't want to rebind the event, but call the handler.
You can use trigger()
to trigger events:
$('#billing_state_id').trigger('change');
If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:
function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
Also note that live()
is deprecated, on()
is the new hotness.
As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.
That's right. Remember that you're writing the condition in terms of what you want to keep, not in terms of what you want to drop. For df1
:
df1 = df[(df.a != -1) & (df.b != -1)]
You're saying "keep the rows in which df.a
isn't -1 and df.b
isn't -1", which is the same as dropping every row in which at least one value is -1.
For df2
:
df2 = df[(df.a != -1) | (df.b != -1)]
You're saying "keep the rows in which either df.a
or df.b
is not -1", which is the same as dropping rows where both values are -1.
PS: chained access like df['a'][1] = -1
can get you into trouble. It's better to get into the habit of using .loc
and .iloc
.
1 - Set CSS on parent div to display: flex;
2 - Set CSS on parent div to flex-direction: column;
Note that this will make all content within that div line up top to bottom. This will work best if the parent div only contains the child and nothing else.
3 - Set CSS on parent div to justify-content: center;
Here is an example of what the CSS will look like:
.parentDivClass {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
}
_x000D_
CSTR({number_field}, 0, '')
The second placeholder is for decimals.
The last placeholder is for thousands separator.
fmin
and fmax
are specifically for use with floating point numbers (hence the "f"). If you use it for ints, you may suffer performance or precision losses due to conversion, function call overhead, etc. depending on your compiler/platform.
std::min
and std::max
are template functions (defined in header <algorithm>
) which work on any type with a less-than (<
) operator, so they can operate on any data type that allows such a comparison. You can also provide your own comparison function if you don't want it to work off <
.
This is safer since you have to explicitly convert arguments to match when they have different types. The compiler won't let you accidentally convert a 64-bit int into a 64-bit float, for example. This reason alone should make the templates your default choice. (Credit to Matthieu M & bk1e)
Even when used with floats the template may win in performance. A compiler always has the option of inlining calls to template functions since the source code is part of the compilation unit. Sometimes it's impossible to inline a call to a library function, on the other hand (shared libraries, absence of link-time optimization, etc.).
When you create a StreamWriter
it always create a file from scratch, you will have to create a third file and copy from target and replace what you need, and then replace the old one.
But as I can see what you need is XML manipulation, you might want to use XmlDocument
and modify your file using Xpath.
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="number" />
I have tried every thing now try this one it shows other characters but you cant enter in the editText
edit.setRawInputType(Configuration.KEYBOARD_12KEY);
Is Perl easily available to you?
$ perl -n -e 'if ($. == 7) { print; exit(0); }'
Obviously substitute whatever number you want for 7.
Another way to get to the deleted commit is with the git fsck
command.
git fsck --lost-found
This will output something like at the last line:
dangling commit xyz
We can check that it is the same commit using reflog
as suggested in other answers. Now we can do a git merge
git merge xyz
Note:
We cannot get the commit back with fsck
if we have already run a git gc
command which will remove the reference to the dangling commit.
A simple possibility (if you'd rather avoid REs) is
' '.join(mystring.split())
The split and join perform the task you're explicitly asking about -- plus, they also do the extra one that you don't talk about but is seen in your example, removing trailing spaces;-).
I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look
#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}
then in html...
<div id="enclose">
<div id="problem">
<!--this is where the text/markup would go-->
</div>
</div>
There ya go!
-Hypertextie
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below
dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")
for filename in os.listdir(dir_src):
if filename.endswith('.txt'):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
INSERT doesn't allow WHERE
in the syntax.
What you can do: create a UNIQUE INDEX
on the field which should be unique (name
), then use either:
INSERT
(and handle the error if the name already exists)INSERT IGNORE
(which will INSERT ... ON DUPLICATE KEY UPDATE
(which will execute the UPDATE
at the end if name already exists, see documentation)First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter
to your simple format and convert it back to a String.
Swift 3
let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")
The printed result is: Dateobj: 10-22-2015
The one I found very useful is the following:
<xsl:choose>
<xsl:when test="not(number(myNode))">
<!-- myNode is a not a number or empty(NaN) or zero -->
</xsl:when>
<xsl:otherwise>
<!-- myNode is a number (!= zero) -->
</xsl:otherwise>
</xsl:choose>
Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).
var offset = $('#whatever').offset();
offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
Since in Javascript a string is a char array, you can access the last character by the length of the string.
var lastChar = myString[myString.length -1];
I'd say BinaryReader
is fine, but can be refactored to this, instead of all those lines of code for getting the length of the buffer:
public byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
using (BinaryReader binaryReader = new BinaryReader(fs))
{
fileData = binaryReader.ReadBytes((int)fs.Length);
}
}
return fileData;
}
Should be better than using .ReadAllBytes()
, since I saw in the comments on the top response that includes .ReadAllBytes()
that one of the commenters had problems with files > 600 MB, since a BinaryReader
is meant for this sort of thing. Also, putting it in a using
statement ensures the FileStream
and BinaryReader
are closed and disposed.
I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq
to return a list of the keys.
var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());
For Ubuntu users: First You need to install mailutils
sudo apt-get install mailutils
Setup an email server, if you are using gmail or smtp. follow this link. then use this command to send email.
echo "this is a test mail" | mail -s "Subject of mail" [email protected]
In case you are using gmail and still you are getting some authentication error then you need to change setting of gmail:
Turn on Access for less secure apps from here
It works :
For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :
<script>
click=function(element){
if(element!=null){
try {element.click();}
catch(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);
}
}
};
</script>
<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">
first select the table you you would like to make the relation with >> then go to operation , for each table there is difference operation setting, >> inside operation "storage engine" choose innoDB option
innoDB will allow you to view the "relation view" which will help you make the foreign key
From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):
1.First you need to declare a converter:
Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };
2.Then you use a conditional operator:
var r = data1.Count > data2.Count ?
data2.ConvertAll<int>(del).Intersect(data1) :
data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);
You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)
As you want to have a result as List, in a last line you convert the result (only result) back to int.
I had this issue, I was scratching my head for the best part of two days.
Turns out I completely forgot I had CloudFlare setup on the domain I was live testing on.
CloudFlare caches your JavaScript and CSS. Turned on development mode and BAM!
Seriously... two whole days.
just to be pythonic :-)
>>> x = ['a1sd','23df','aaa','ccc','rrrr', 'ssss', 'e', '']
>>> [x[i] + x[i+1] for i in range(0,len(x),2)]
['a1sd23df', 'aaaccc', 'rrrrssss', 'e']
in case the you want to be alarmed if the list length is odd you can try:
[x[i] + x[i+1] if not len(x) %2 else 'odd index' for i in range(0,len(x),2)]
Best of Luck
Easiest way to do this:
# First you need to sort this DF as Column A as ascending and column B as descending
# Then you can drop the duplicate values in A column
# Optional - you can reset the index and get the nice data frame again
# I'm going to show you all in one step.
d = {'A': [1,1,2,3,1,2,3,1], 'B': [30, 40,50,42,38,30,25,32]}
df = pd.DataFrame(data=d)
df
A B
0 1 30
1 1 40
2 2 50
3 3 42
4 1 38
5 2 30
6 3 25
7 1 32
df = df.sort_values(['A','B'], ascending =[True,False]).drop_duplicates(['A']).reset_index(drop=True)
df
A B
0 1 40
1 2 50
2 3 42
Here is what I follow on My system.
All Projects: There is a projects directory in my home folder i.e. ~/projects
. All the projects rest inside it.
Individual Project: I follow a standardized structure template used by many developers called django-skel for individual projects. It basically takes care of all your static file and media files and all.
Virtual environment: I have a virtualenvs folder inside my home to store all virtual environments in the system i.e. ~/virtualenvs
. This gives me flexibility that I know what all virtual environments I have and can look use easily
The above 3 are the main partitions of My working environment.
All the other parts you mentioned are mostly dependent on project to project basis (i.e. you might use different databases for different projects). So they should reside in their individual projects.
I needed to move data from a sql server compact database to sqlite, so using sql server 2008 you can right click on the table and select 'Script Table To' and then 'Data to Inserts'. Copy the insert statements remove the 'GO' statements and it executed successfully when applied to the sqlite database using the 'DB Browser for Sqlite' app.
<Ctrl> + W, V to split the screen vertically
<Ctrl> + W, W to shift between the windows
!python % [args] to run the script I am editing in this window
ZF in visual mode to fold arbitrary lines
An easy way to get the first or last segment, in case you are unsure of the path length.
$segments = request()->segments();
$last = end($segments);
$first = reset($segments);
Local classes have already been mentioned, but here is a way to let them appear even more as local functions, using an operator() overload and an anonymous class:
int main() {
struct {
unsigned int operator() (unsigned int val) const {
return val<=1 ? 1 : val*(*this)(val-1);
}
} fac;
std::cout << fac(5) << '\n';
}
I don't advise on using this, it's just a funny trick (can do, but imho shouldn't).
With the rise of C++11 a while back, you can now have local functions whose syntax is a little reminiscient of JavaScript:
auto fac = [] (unsigned int val) {
return val*42;
};
Simple answer:
Use getReader() to read the body of the request
More info:
There are two methods for reading the data in the body:
getReader()
returns a BufferedReader that will allow you to read the body of the request.
getInputStream()
returns a ServletInputStream if you need to read binary data.
Note from the docs: "[Either method] may be called to read the body, not both."
Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]
Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.
So, to summarize:
Transfer on established connection:
First connection establishment:
Subsequent connection establishments:
As suggested in this answer to a related question, "edge" mode can be set in the Web.Config file. This will make it apply to all HTML returned from the application without the need to insert it into individual pages:
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
This same step can also be accomplished by modifying the "HTTP Response Headers" using IIS Manager for the IIS server, entire website, or specific applications.
Here's a typical simple example in the Unity milieu
using UnityEngine;
public class Launch : MonoBehaviour
{
void Start()
{
Debug.Log("today " + System.DateTime.Now.ToString("MM/dd/yyyy"));
// don't allow the app to be run after June 10th
System.DateTime lastDay = new System.DateTime(2020, 6, 10);
System.DateTime today = System.DateTime.Now;
if (lastDay < today) {
Debug.Log("quit the app");
Application.Quit();
}
UnityEngine.SceneManagement.SceneManager.LoadScene("Welcome");
}
}
Use Math.floor()
:
var f = 20.536;
var i = Math.floor(f); // 20
To select elements having a certain attribute, see the answers above.
To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true
if the first element in ajQuery collection has this attribute:
/** hasAttr
** helper plugin returning boolean if the first element of the collection has a certain attribute
**/
$.fn.hasAttr = function(attr) {
return 0 < this.length
&& 'undefined' !== typeof attr
&& undefined !== attr
&& this[0].hasAttribute(attr)
}
You can try this:
const wait_until_element_appear = setInterval(() => {
if ($(element).length !== 0) {
// some code
clearInterval(wait_until_element_appear);
}
}, 0);
This solution works very good for me
If by string you mean std::string
you can do it with this method:
QString QString::fromStdString(const std::string & str)
std::string str = "Hello world";
QString qstr = QString::fromStdString(str);
If by string you mean Ascii encoded const char *
then you can use this method:
QString QString::fromAscii(const char * str, int size = -1)
const char* str = "Hello world";
QString qstr = QString::fromAscii(str);
If you have const char *
encoded with system encoding that can be read with QTextCodec::codecForLocale() then you should use this method:
QString QString::fromLocal8Bit(const char * str, int size = -1)
const char* str = "zazólc gesla jazn"; // latin2 source file and system encoding
QString qstr = QString::fromLocal8Bit(str);
If you have const char *
that's UTF8 encoded then you'll need to use this method:
QString QString::fromUtf8(const char * str, int size = -1)
const char* str = read_raw("hello.txt"); // assuming hello.txt is UTF8 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const char*
QString qstr = QString::fromUtf8(str);
There's also method for const ushort *
containing UTF16 encoded string:
QString QString::fromUtf16(const ushort * unicode, int size = -1)
const ushort* str = read_raw("hello.txt"); // assuming hello.txt is UTF16 encoded, and read_raw() reads bytes from file into memory and returns pointer to the first byte as const ushort*
QString qstr = QString::fromUtf16(str);
Marc Gravell's answer should work for you. myDictionary.Keys
returns an object that implements ICollection<TKey>
, IEnumerable<TKey>
and their non-generic counterparts.
I just wanted to add that if you plan on accessing the value as well, you could loop through the dictionary like this (modified example):
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (KeyValuePair<string, int> item in data)
{
Console.WriteLine(item.Key + ": " + item.Value);
}
Quote (read [here][1])-
When you use CAST to convert a CLOB value into a character datatype or a BLOB value into the RAW datatype, the database implicitly converts the LOB value to character or raw data and then explicitly casts the resulting value into the target datatype.
So, something like this should work-
report := CAST(report_clob AS VARCHAR2(100));
Or better yet use it as CAST(report_clob AS VARCHAR2(100))
where ever you are trying to use the BLOB
as VARCHAR
[1]: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions016.htm
find
command.In GNU find
, you can use -execdir
parameter:
find . -type d -execdir realpath "{}" ';'
or by using -exec
parameter:
find . -type d -exec sh -c 'cd -P "$0" && pwd -P' {} \;
or with xargs
command:
find . -type d -print0 | xargs -0 -L1 sh -c 'cd "$0" && pwd && echo Do stuff'
Or using for loop:
for d in */; { echo "$d"; }
For recursivity try extended globbing (**/
) instead (enable by: shopt -s extglob
).
For more examples, see: How to go to each directory and execute a command? at SO
If you are looking for a one-size-fits-all, I'd suggest DECIMAL(19, 4)
is a popular choice (a quick Google bears this out). I think this originates from the old VBA/Access/Jet Currency data type, being the first fixed point decimal type in the language; Decimal
only came in 'version 1.0' style (i.e. not fully implemented) in VB6/VBA6/Jet 4.0.
The rule of thumb for storage of fixed point decimal values is to store at least one more decimal place than you actually require to allow for rounding. One of the reasons for mapping the old Currency
type in the front end to DECIMAL(19, 4)
type in the back end was that Currency
exhibited bankers' rounding by nature, whereas DECIMAL(p, s)
rounded by truncation.
An extra decimal place in storage for DECIMAL
allows a custom rounding algorithm to be implemented rather than taking the vendor's default (and bankers' rounding is alarming, to say the least, for a designer expecting all values ending in .5 to round away from zero).
Yes, DECIMAL(24, 8)
sounds like overkill to me. Most currencies are quoted to four or five decimal places. I know of situations where a decimal scale of 8 (or more) is required but this is where a 'normal' monetary amount (say four decimal places) has been pro rata'd, implying the decimal precision should be reduced accordingly (also consider a floating point type in such circumstances). And no one has that much money nowadays to require a decimal precision of 24 :)
However, rather than a one-size-fits-all approach, some research may be in order. Ask your designer or domain expert about accounting rules which may be applicable: GAAP, EU, etc. I vaguely recall some EU intra-state transfers with explicit rules for rounding to five decimal places, therefore using DECIMAL(p, 6)
for storage. Accountants generally seem to favour four decimal places.
PS Avoid SQL Server's MONEY
data type because it has serious issues with accuracy when rounding, among other considerations such as portability etc. See Aaron Bertrand's blog.
Microsoft and language designers chose banker's rounding because hardware designers chose it [citation?]. It is enshrined in the Institute of Electrical and Electronics Engineers (IEEE) standards, for example. And hardware designers chose it because mathematicians prefer it. See Wikipedia; to paraphrase: The 1906 edition of Probability and Theory of Errors called this 'the computer's rule' ("computers" meaning humans who perform computations).
You can try using the following code:
$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;
$mailto = '[email protected]';
$subject = 'Subject';
$message = 'My message';
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers = "From: name <[email protected]>" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $message . $eol;
// attachment
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}
Edit 14-June-2018
for more readability in some of email provider use
$body .= $eol . $message . $eol . $eol;
and
$body .= $eol . $content . $eol . $eol;
This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;
public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
// PKCS#8 format
final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";
// PKCS#1 format
final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";
Path path = Paths.get(pemFileName.getAbsolutePath());
String privateKeyPem = new String(Files.readAllBytes(path));
if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));
} else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) { // PKCS#1 format
privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));
DerValue[] seq = derReader.getSequence(0);
if (seq.length < 9) {
throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
}
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
}
throw new GeneralSecurityException("Not supported format of a private key");
}
Use the property table-layout:fixed;
on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.
<table style='table-layout:fixed;'>
<tbody>
<tr>
<td>gobble de gook</td>
<td>mibs</td>
</tr>
</tbody>
</table>
Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>
, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
I found a more straight forward solution from @DK comment in this question, the solution is written by Alex and described here with source, To make customized window:
You can stop a query which is being processed by this
Find the Id of the query process by => show processlist;
Then => kill id;
There is no difference until you compile to same target architecture. I suppose you are compiling for 32
bit architecture in both cases.
It's worth mentioning that OutOfMemoryException
can also be raised if you get 2GB
of memory allocated by a single collection in CLR (say List<T>
) on both architectures 32
and 64
bit.
To be able to benefit from memory goodness on 64
bit architecture, you have to compile your code targeting 64
bit architecture. After that, naturally, your binary will run only on 64
bit, but will benefit from possibility having more space available in RAM.
Might sound stupid, But Params doesn't allow multidimensional array. Whereas you can pass a multidimensional array to a function.
In management studio, set query options to output to file, and in options->query results set output to file to output using comma as delimiter.
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
Working with just one selector:
select {
width: 268px;
padding: 5px;
font-size: 16px;
line-height: 1;
border: 0;
border-radius: 5px;
height: 34px;
background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
-webkit-appearance: none;
background-position-x: 244px;
}
How about this? Just give it a thought-
import java.util.ArrayList;
class Solution
{
public static void main (String[] args){
ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");
int i[] = {1,3,5};
for (int j = 0; j < i.length; j++) {
List_Of_Array.remove(i[j]-j);
}
System.out.println(List_Of_Array);
}
}
And the output was-
[A, C, E, G, H]
A little bit of validation with:
/<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(htmlStringHere)
This searches for empty tags (some predefined) and /
terminated XHTML empty tags and validates as HTML because of the empty tag OR will capture the tag name and attempt to find it's closing tag somewhere in the string to validate as HTML.
Explained demo: http://regex101.com/r/cX0eP2
Update:
Complete validation with:
/<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(htmlStringHere)
This does proper validation as it contains ALL HTML tags, empty ones first followed by the rest which need a closing tag.
Explained demo here: http://regex101.com/r/pE1mT5
ImmutableMap does not accept null
values whereas Collections.unmodifiableMap()
does. In addition it will never change after construction, while UnmodifiableMap
may. From the JavaDoc:
An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.
I got this fixed by doing the below steps,
The eclipse finds the JAVA executables from 'C:\ProgramData\Oracle\Java\javapath'
2.The folder structure will contain shortcuts to the below executables,
i. java.exe
ii. javaw.exe
iii. javaws.exe
3.For me the executable paths were pointing to my (ProgramFiles(x84)) folder location
I corrected it to Program Files path(64 bit) and the issue got resolved
Please find the screenshot for the same.
spring.data.mongodb.host
and spring.data.mongodb.port
are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri
should be used to provide all of the configuration, like this:
spring.data.mongodb.uri=mongodb://user:[email protected]:12345
Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.
You can also disable it through the menu "Project / Build automatically
".
But I would recommend first to check:
Preferences / Validations
, or Preferences / XML / ...
if you have WTP installed)Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:
There is an important difference between build interrupt and cancel.
When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.
Use the below.
background-image: url("././images/image.png");
This shall work.
{!a}
applies ascii()
and hence escapes non-ASCII characters like quotes and even emoticons.
Here is an example
cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))
based on other answers and comment of @phk, using fd #3:
(which still allows to use stdin inside the loop)
while IFS= read -r f <&3; do
echo "$f"
done 3< <(find . -iname "*filename*")
You can check this code, pod UIViewController+ODStatusBar
Here is how you can solve this using a single WHERE
clause:
WHERE (@myParm = value1 AND MyColumn IS NULL)
OR (@myParm = value2 AND MyColumn IS NOT NULL)
OR (@myParm = value3)
A naïve usage of the CASE statement does not work, by this I mean the following:
SELECT Field1, Field2 FROM MyTable
WHERE CASE @myParam
WHEN value1 THEN MyColumn IS NULL
WHEN value2 THEN MyColumn IS NOT NULL
WHEN value3 THEN TRUE
END
It is possible to solve this using a case statement, see onedaywhen's answer
As pointed out (and hopefully unsurprisingly), using if+else
is indeed the idiomatic way to do conditionals in Go.
In addition to the full blown var+if+else
block of code, though, this spelling is also used often:
index := val
if val <= 0 {
index = -val
}
and if you have a block of code that is repetitive enough, such as the equivalent of int value = a <= b ? a : b
, you can create a function to hold it:
func min(a, b int) int {
if a <= b {
return a
}
return b
}
...
value := min(a, b)
The compiler will inline such simple functions, so it's fast, more clear, and shorter.
Use this as your WHERE condition
WHERE CHARINDEX('Apples', column) = 0
Use Comparator
interface with methods introduced in JDK1.8: comparing
and thenComparing
, or more concrete methods: comparingXXX
and thenComparingXXX
.
For example, if we wanna sort a list of persons by their id firstly, then age, then name:
Comparator<Person> comparator = Comparator.comparingLong(Person::getId)
.thenComparingInt(Person::getAge)
.thenComparing(Person::getName);
personList.sort(comparator);
Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.
mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep '^INSERT' > 5406.sql
i founded here, its ok with me for linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-code so my code with with linkedin login here:
ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()
This is the real proxy redirection to the intended server.
server {
listen 80;
server_name localhost;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://xx.xxx.xxx.xxx/;
proxy_redirect off;
proxy_set_header Host $host;
}
}
I encountered a similar problem only with a nested img in my anchor:
<a href="some/link">
<img src="some/src">
</a>
When I applied
@media print {
a[href]:after {
content: none !important;
}
}
I lost my img and the entire anchor width for some reason, so instead I used:
@media print {
a[href]:after {
visibility: hidden;
}
}
which worked perfectly.
Bonus tip: inspect print preview
I'm trying to learn how to do this myself, and it seems you can install the library like this:
cmake_minimum_required(VERSION 2.4.0)
project(mycustomlib)
# Find source files
file(GLOB SOURCES src/*.cpp)
# Include header files
include_directories(include)
# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})
# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})
# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})
This answers did not help me, my php adminer showed me "No input file specified" error anyway. But I knew I changed php-version before. So, I found the reason: it is not nginx, it is php.ini doc_root parameter! I found
doc_root =
in php.ini and changed it to
;doc_root =
After this patch my adminer work good.
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
}
header("Location: http://localhost:8080/meet2eat/index.php");
change to
// Register user's name and ID
if ((!isset($_SESSION['name'])) && (!isset($_SESSION['user_id']))) {
$row = mysql_fetch_assoc($login_result);
$_SESSION['name'] = $row['name'];
$_SESSION['user_id'] = $row['user_id'];
header("Location: http://localhost:8080/meet2eat/index.php");
}
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
use this code to convert your string to wstring
std::wstring string2wString(const std::string& s){
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
int main(){
std::wstring str="your string";
std::wstring wStr=string2wString(str);
return 0;
}
As Johannes says -- not enough rep to comment directly on his answer -- you can indeed do this as long as all elements' "dimensions are specified as a multiple of the font's size. Meaning, everything where you used %, em or ex units". Although I think % are based on containing element, not font-size.
And you wouldn't normally use these relative units for images, given they are composed of pixels, but there's a trick which makes this a lot more practical.
If you define body{font-size: 62.5%};
then 1em will be equivalent to 10px. As far as I know this works across all main browsers.
Then you can specify your (e.g.) 100px square images with width: 10em; height: 10em;
and assuming Firefox's scaling is set to default, the images will be their natural size.
Make body{font-size: 125%};
and everything - including images - wil be double original size.
var decPlaces = (int)(((decimal)number % 1) * 100);
This presumes your number only has two decimal places.
The most effective way:
if (array.indexOf(element) > -1) {
alert('Bingooo')
}
I started getting this error (different stack trace though) after making a trivial update to my GraphQL API application that is operated inside a docker container. For whatever reason, the container was having difficulty resolving a back-end service being used by the API.
After poking around to see if some change had been made in the docker base image I was building from (node:13-alpine, incidentally), I decided to try the oldest computer science trick of rebooting... I stopped and started the docker container and all went back to normal.
Clearly, this isn't a meaningful solution to the underlying problem - I am merely posting this since it did clear up the issue for me without going too deep down rabbit holes.
This is just a warning and it will probably be fixed before 2019 with plugin updates so don't worry about it. I would recommend you to use compatible versions of your plugins and gradle.
You can check your plugin version and gradle version here for better experience and performance.
https://developer.android.com/studio/releases/gradle-plugin
Try using the stable versions for a smooth and warning/error free code.