In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W]
to match all characters.
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
You can use Array.prototype.reduce().
Code:
const fruits = ['Banana', 'Orange', 'Apple', 'Mango'],_x000D_
result = fruits.reduce((a, c, i, array) => 0 === i || array.length - 1 === i ? a : [...a, c], []);_x000D_
_x000D_
console.log(result);
_x000D_
I needed to remove all files in child dirs except for some files. The following worked for me (three patterns specified):
find . -depth -type f -not -name *.itp -and -not -name *ane.gro -and -not -name *.top -exec rm '{}' +
Look at the antivirus or firewall... Does any of that block you from access... In k7 antivirus I turned off system monitor, and it does works for me...
If you are planning to use JSONP
you can use getJSON
which made for that. jQuery has helper methods for JSONP
.
$.getJSON( 'http://someotherdomain.com/service.svc&callback=?', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job
Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).
Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.
Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.
I just type following keywords in the opened terminal;
See details in the below image. (VSCode version 1.19.1 - windows 10 OS)
It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)
If you are working with core java, create your file(.properties
) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error
This code is from Processing.org an open source Java based IDE. You can find it Processing.org. The Arduino IDE also uses this extension, although they run on a hardware board.
EDIT - And yes it is C syntax, used mostly for art or live media presentations.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.
Also, explorer will stop if there is a particular problem with a file,
I usually do this and works always.
/try this/
for (i = res; i < *size-1; i++) {
arrb[i] = arrb[i + 1];
}
*size = *size - 1; /*in some ides size -- could give problems*/
If you have jQuery defined twice, then you could get this error. For example, if you are working with Primefaces (it already includes jQuery) and you define it in other place.
I had a batch of files that looked like this: be90-01.png and needed to change the dash to underscore. I used this, which worked well:
for f in *; do mv "$f" "`echo $f | tr '-' '_'`"; done
one way is to write an abstract test case that corresponds to your abstract class, then write concrete test cases that subclass your abstract test case. do this for each concrete subclass of your original abstract class (i.e. your test case hierarchy mirrors your class hierarchy). see Test an interface in the junit recipies book: http://safari.informit.com/9781932394238/ch02lev1sec6. https://www.manning.com/books/junit-recipes or https://www.amazon.com/JUnit-Recipes-Practical-Methods-Programmer/dp/1932394230 if you don't have a safari account.
also see Testcase Superclass in xUnit patterns: http://xunitpatterns.com/Testcase%20Superclass.html
Define state attributes. Add universal handleChange event handler. Add name param to input tag for mapping.
this.state = { stateAttrName:"" }
handleChange=(event)=>{
this.setState({[event.target.name]:event.target.value });
}
<input className="form-control" name="stateAttrName" value=
{this.state.stateAttrName} onChange={this.handleChange}/>
The simplest solution is to apply Python str
function to the column you are trying to loop through.
If you are using pandas
, this can be implemented as:
dataframe['column_name']=dataframe['column_name'].apply(str)
import sys
sys.exit(1)
I had the same error on a page, and I added these lines:
<!--[if lte IE 9]>
<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js'></script>
<![endif]-->
and it finally works for me ;) no more error in IE9.
You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.
I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:
result=loop.run_until_complete(asyncio.wait([
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
]))
Whereas grouping in gather() is done by just specifying multiple coroutines:
result=loop.run_until_complete(asyncio.gather(
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
))
import java.lang.Runtime;
Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");
This will work for you and is easy to use.
What you could also do is put a .htaccess file containing
RewriteEngine Off
In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.
Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&
, >
, <
, '
, "
) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter  
in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.
If your instance is called SQLEXPRESS
, then you need to use .\SQLEXPRESS
or (local)\SQLEXPRESS
or yourMachineName\SQLEXPRESS
as your server name - if you have a named instance, you need to specify that name of the instance in your server name.
Alternatively one can use the setExtremes method also,
yAxis.setExtremes(0, 100);
Or if only one value is needed to be set, just leave other as null
yAxis.setExtremes(null, 100);
In case of :
<?xml version="1.0" encoding="iso-8859-1"?>
<info xmlns="http://namespaces.default" xmlns:ns2="http://namespaces.ns2" >
<id> 954 </id>
<idboss> 954 </idboss>
<name> Fausto </name>
<sorname> Anonimo </sorname>
<phone> 040000000 </phone>
<fax> 040000001 </fax>
</info>
Query :
Select *
from xmltable(xmlnamespaces(default 'http://namespaces.default'
'http://namespaces.ns2' as "ns",
),
'/info'
passing xmltype.createxml(xml)
columns id varchar2(10) path '/id',
idboss varchar2(500) path '/idboss',
etc....
) nice_xml_table
Use the CSS3 Viewport-percentage feature.
Viewport-Percentage Explanation
Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Styles</title>_x000D_
_x000D_
<style>_x000D_
@media screen and (min-width: 480px) {_x000D_
body {_x000D_
background-color: skyblue;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
border: groove black;_x000D_
}_x000D_
_x000D_
div#main {_x000D_
font-size: 3vw;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div id="main">_x000D_
Viewport-Percentage Test_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.
If you have a checkbox in your html something like:
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});
Here is what I came up with ( and like all Date Time conundrums it is probably going to be disproved based on some weird timezone-leapyear-daylight adjustment :D )
Date
<<->> LocalDateTime
Given: Date date = [some date]
(1) LocalDateTime
<< Instant
<< Date
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
(2) Date
<< Instant
<< LocalDateTime
Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Example:
Date date = new Date();
System.out.println(date + " long: " + date.getTime());
LocalDateTime
<< Instant
<< Date
:Create Instant
from Date
:
Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("Instant from Date:\n" + instant);
Create Date
from Instant
(not necessary,but for illustration):
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
Create LocalDateTime
from Instant
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println("LocalDateTime from Instant:\n" + ldt);
Date
<< Instant
<< LocalDateTime
Create Instant
from LocalDateTime
:
instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println("Instant from LocalDateTime:\n" + instant);
Create Date
from Instant
:
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
Instant from Date:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
LocalDateTime from Instant:
2013-11-01T14:13:04.574
Instant from LocalDateTime:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
If what you're saying is that you want to get all inputs inside a form that have a value without worrying about the input type, try this:
Example: http://jsfiddle.net/nfLfa/
var $inputs = $('form').find(':checked,:selected,:text,textarea').filter(function() {
return $.trim( this.value ) != '';
});
Now you should have a set of input elements that have some value.
You can put the values in an array:
var array = $inputs.map(function(){
return this.value;
}).get();
Or you could serialize them:
var serialized = $inputs.serialize();
Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top!
Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.
import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)
I tried Alexanders answer but got this error in Python3:
TypeError: 'float' object cannot be interpreted as an integer
This is because the division operator in Python3 is returning a float. This works for me:
>>> x = "qwertyui"
>>> chunks, chunk_size = len(x), len(x)//4
>>> [ x[i:i+chunk_size] for i in range(0, chunks, chunk_size) ]
['qw', 'er', 'ty', 'ui']
Notice the //
at the end of line 2, to ensure truncation to an integer.
Faster option:
The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.
Create an engine based on your DB specifications.
Create a table in your postgres DB that has equal number of columns as the Dataframe (df).
Data in DF will get inserted in your postgres table.
from sqlalchemy import create_engine
import psycopg2
import io
if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
Improving on João's and satru's code, I suggest creating a cursor mixin that can be used to build a cursor with an execute that accepts nested iterables and handles them correctly. A better name would be nice, though... For Python3, use str
instead of basestring
.
from MySQLdb.cursors import Cursor
class BetterExecuteMixin(object):
"""
This mixin class provides an implementation of the execute method
that properly handles sequence arguments for use with IN tests.
Examples:
execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
# Notice that when the sequence is the only argument, you still need
# a surrounding tuple:
execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
"""
def execute(self, query, args=None):
if args is not None:
try:
iter(args)
except TypeError:
args = (args,)
else:
if isinstance(args, basestring):
args = (args,)
real_params = []
placeholders = []
for arg in args:
# sequences that we treat as a single argument
if isinstance(arg, basestring):
real_params.append(arg)
placeholders.append('%s')
continue
try:
real_params.extend(arg)
placeholders.append(','.join(['%s']*len(arg)))
except TypeError:
real_params.append(arg)
placeholders.append('%s')
args = real_params
query = query % tuple(placeholders)
return super(BetterExecuteMixin, self).execute(query, args)
class BetterCursor(BetterExecuteMixin, Cursor):
pass
This can then be used as follows (and it's still backwards compatible!):
import MySQLdb
conn = MySQLdb.connect(user='user', passwd='pass', db='dbname', host='host',
cursorclass=BetterCursor)
cursor = conn.cursor()
cursor.execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
cursor.execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
cursor.execute('SELECT * FROM foo WHERE type IN (%s)', (['bar', 'moo'],))
cursor.execute('SELECT * FROM foo WHERE type=%s', 'bar')
cursor.execute('SELECT * FROM foo WHERE type=%s', ('bar',))
Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.
read from assets html file
ViewGroup webGroup;
String content = readContent("content/ganji.html");
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
webGroup.addView(webView);
You will need to use semicolon as delimiter while specifying the jar and class file path in windows. This solved the issue.
Assuming the class file is under C:.
java -cp ".;C:\testng.jar" org.testng.TestNG testing.xml
Assuming that you know the table name, and want the names of the data columns you can use the listed code will do it in a simple and elegant way to my taste:
import sqlite3
def get_col_names():
#this works beautifully given that you know the table name
conn = sqlite3.connect("t.db")
c = conn.cursor()
c.execute("select * from tablename")
return [member[0] for member in c.description]
invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1: " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2: " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3: " ,bin3interval, fill = TRUE))
produces output without NULL at the end of the line or on the next line
Dataset: 17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width: 15.33333
Bin1: 17 32.33333
Bin2: 32.33333 47.66667
Bin3: 47.66667 63
Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.
Possible drawbacks:
this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.
using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.
package p01;
import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;
public class Main {
String words[];
int currentIndex=0;
public static String readFileAsString()throws Exception
{
String data = "";
File file = new File("the_comedy_of_errors");
//System.out.println(file.exists());
data = new String(Files.readAllBytes(Paths.get(file.getName())));
return data;
}
public void init() throws Exception
{
String data = readFileAsString();
words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
}
public String getNextWord() throws Exception
{
if(currentIndex>words.length-1)
throw new Exception("out of words; reached end of file");
String currentWord = words[currentIndex];
currentIndex++;
while(currentWord.isEmpty())
{
currentWord = words[currentIndex];
currentIndex++;
}
return currentWord;
}
public boolean getNextRandom() throws Exception
{
String nextWord = getNextWord();
int asciiSum = 0;
for (int i = 0; i < nextWord.length(); i++){
char c = nextWord.charAt(i);
asciiSum = asciiSum + (int) c;
}
System.out.println(nextWord+"-"+asciiSum);
return (asciiSum%2==1) ;
}
public static void main(String args[]) throws Exception
{
Main m = new Main();
m.init();
while(true)
{
System.out.println(m.getNextRandom());
Thread.sleep(100);
}
}
}
In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html
I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.
.labels {
color: red;
background-color: white;
font-family: "Lucida Grande", "Arial", sans-serif;
font-size: 10px;
font-weight: bold;
text-align: center;
width: 60px;
border: 2px solid black;
white-space: nowrap;
}
JavaScript:
var marker = new MarkerWithLabel({
position: homeLatLng,
draggable: true,
map: map,
labelContent: "$425K",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50)
.
In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|
[Offering a somewhat more descriptive answer than the answer provided by @Ajni.]
This can also be achieved using LINQ fluent syntax:
var list = ctn.Items
.Where(t=> t.DeliverySelection == true && t.Delivery.SentForDelivery == null)
.OrderBy(t => t.Delivery.SubmissionDate)
.Take(5);
Note that each method (Where
, OrderBy
, Take
) that appears in this LINQ statement takes a lambda expression as an argument. Also note that the documentation for Enumerable.Take
begins with:
Returns a specified number of contiguous elements from the start of a sequence.
I had the same error message (in my case : "Argument 'languageSelectorCtrl' is not a function, got undefined").
After some tedious comparison with Angular seed's code, I found out that I had previously removed a reference to the controllers module in app.js. (spot it at https://github.com/angular/angular-seed/blob/master/app/js/app.js)
So I had this:
angular.module('MyApp', ['MyApp.filters', 'MyApp.services', 'MyApp.directives'])
This failed.
And when I added the missing reference:
angular.module('MyApp', ['MyApp.filters', 'MyApp.services', 'MyApp.controllers', 'MyApp.directives'])
The error message disappeared and Angular could instanciate the controllers again.
You can think of a MySQL "database" as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS
view to see the list of schemas:
SELECT * FROM DBA_USERS;
UIButton *btnNotification=[UIButton buttonWithType:UIButtonTypeCustom];
btnNotification.frame=CGRectMake(130,80,120,40);
btnNotification.backgroundColor=[UIColor greenColor];
[btnNotification setTitle:@"create Notification" forState:UIControlStateNormal];
[btnNotification addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnNotification];
}
-(void)btnClicked
{
// Here You can write functionality
}
var arrayCount = [1,2,3,2,5,6,2,8];_x000D_
var co = 0;_x000D_
function findElement(){_x000D_
arrayCount.find(function(value, index) {_x000D_
if(value == 2)_x000D_
co++;_x000D_
});_x000D_
console.log( 'found' + ' ' + co + ' element with value 2');_x000D_
}
_x000D_
I would do something like that:
var arrayCount = [1,2,3,4,5,6,7,8];_x000D_
_x000D_
function countarr(){_x000D_
var dd = 0;_x000D_
arrayCount.forEach( function(s){_x000D_
dd++;_x000D_
});_x000D_
_x000D_
console.log(dd);_x000D_
}
_x000D_
using javascript
<form id="frm1" action="file.php"></form>
<script>document.getElementById('frm1').submit();</script>
The following way you can access all the information from logged user.
$customer_data=Mage::getSingleton('customer/session')->getCustomer();
echo "<pre>" print_r($customer_data);
It is not certain that any global ECMAScript variables have been exported and html/css does not necessarily indicate React. So look in the .js.
Method 1: Look in ECMAScript:
The version number is exported by both modules react-dom and react but those names are often removed by bundling and the version hidden inside an execution context that cannot be accessed. A clever break point may reveal the value directly, or you can search the ECMAScript:
Method 2: Use a DOM breakpoint:
Inspect Element
Elements
paneBreak On… - subtree modifications
Sources
paneCall Stack
sub-panerender
entry, this is ReactDOM.render
render
, ie. the code that invokes renderreact-dom
module exports object
version: "15.6.2"
, ie. all values exported by react-dom
The version is also injected into React dev tools, but as far as I know not displayed anywhere.
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
With plain JPA, assuming that you have a PersistenceProvider
implementation (e.g. Hibernate), you can use the PersistenceProvider#createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) method to bootstrap an EntityManagerFactory
without needing a persistence.xml
.
However, it's annoying that you have to implement the PersistenceUnitInfo
interface, so you are better off using Spring or Hibernate which both support bootstrapping JPA without a persistence.xml
file:
this.nativeEntityManagerFactory = provider.createContainerEntityManagerFactory(
this.persistenceUnitInfo,
getJpaPropertyMap()
);
Where the PersistenceUnitInfo is implemented by the Spring-specific MutablePersistenceUnitInfo class.
On DataTable 1.9.x:
$('.dataTable').dataTable({
'aoColumnDefs': [{
'bSortable': false,
'aTargets': [-1], /* 1st colomn, starting from the right */
}]
});
While on 1.10.x
$('.dataTable').dataTable({
columnDefs: [{ orderable: false, "targets": -1 }] /* -1 = 1st colomn, starting from the right */
});
You can also use:
@Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", "~/bundles/mybundle")
To specify the format of your output in a scenario where you need to use Charset, Type, etc.
There was a proposal for it in Java 7, but it was rejected:
If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt
file in the root directory of your project. (and not in the folder where your .class
files are built or anywhere else)
If not, you should specify the absolute path to that file.
Edit:
You would put the .txt
file in the same place with the .class
(usually also the .java
file because you compile in the same folder) compiled files if you compile it by hand with javac
. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.
If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.
Quickest (drops and creates all tables including data):
./manage.py reset appname | ./manage.py dbshell
Caution:
how about this?
fun <- function(x, ...){
y=NULL
parms=list(...)
for (name in names(parms) ) {
assign(name, parms[[name]])
}
print(is.null(y))
}
Then try:
> fun(1,y=4)
[1] FALSE
> fun(1)
[1] TRUE
Ubuntu 16.04 comes with PHP7 as the standard, so there are no PHP5 packages
However if you like you can add a PPA to get those packages anyways:
Remove all the stock php packages
List installed php packages with dpkg -l | grep php| awk '{print $2}' |tr "\n" " "
then remove unneeded packages with sudo aptitude purge your_packages_here or if you want to directly remove them all use :
sudo aptitude purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`
Add the PPA
sudo add-apt-repository ppa:ondrej/php
Install your PHP Version
sudo apt-get update
sudo apt-get install php5.6
You can install php5.6 modules too ..
Verify your version
sudo php -v
Based on https://askubuntu.com/a/756186/532957 (thanks @AhmedJerbi)
sudo apt-get install php5-cli php5-dev make
sudo apt-get install libsqlite3-0 libsqlite3-dev
sudo apt-get install php5-sqlite3
sudo apt-get remove php5-sqlite3
cd ~
wget http://pecl.php.net/get/sqlite3-0.6.tgz
tar -zxf sqlite3-0.6.tgz
cd sqlite3-0.6/
sudo phpize
sudo ./configure
That worked for me.
As the way to remove invalid XML characters I suggest you to use XmlConvert.IsXmlChar method. It was added since .NET Framework 4 and is presented in Silverlight too. Here is the small sample:
void Main() {
string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
content = RemoveInvalidXmlChars(content);
Console.WriteLine(IsValidXmlString(content)); // True
}
static string RemoveInvalidXmlChars(string text) {
var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();
return new string(validXmlChars);
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
And as the way to escape invalid XML characters I suggest you to use XmlConvert.EncodeName method. Here is the small sample:
void Main() {
const string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
string encoded = XmlConvert.EncodeName(content);
Console.WriteLine(IsValidXmlString(encoded)); // True
string decoded = XmlConvert.DecodeName(encoded);
Console.WriteLine(content == decoded); // True
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
Update: It should be mentioned that the encoding operation produces a string with a length which is greater or equal than a length of a source string. It might be important when you store a encoded string in a database in a string column with length limitation and validate source string length in your app to fit data column limitation.
When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:
GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: <cookie data removed>
Pragma: no-cache
Cache-Control: no-cache
These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.
In PHP, all this information is stored in the $_SERVER
array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.
<pre><?php print_r($_SERVER); ?></pre>
This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT']
to get the operating system and browser.
Try this code my friend...
#include<stdio.h>
int main(){
char *s1, *s2;
char str[10];
printf("type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1
printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1
return 0;
}
i got [ReflectionException] Class Seeder does not exist
too and when i use composer dump-autoload
, i got an error preg_match(): JIT compilation failed: no more memory
when i run it.
What i did is that i change ;pcre.jit=1
to pcre.jit=Off
in php.ini!
You can find the path by using php --ini
in your terminal!
I am using mac with php 7.3! Hope that help any of you guys out there!
I think it's better to use importlib.import_module('.c', __name__)
since you don't need to know about a
and b
.
I'm also wondering that, if you have to use importlib.import_module('a.b.c')
, why not just use import a.b.c
?
well, you can very quickly test the click dispatch via jQuery like so
$('#link-id').click();
If you're still having problem with click respecting the target, you can always do this
$('#link-id').click( function( event, anchor )
{
window.open( anchor.href, anchor.target, '' );
event.preventDefault();
return false;
});
Using a button tag instead of the input, resetting it and put a span inside, you'll then just have to style both the link and the span in the same way. It involve extra markup, but it worked for me.
the markup:
<button type="submit">
<span>submit</span>
</button>
<a>cancel</a>
the css:
button[type="submit"] {
display: inline;
border: none;
padding: 0;
background: none;
}
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
else if(Decision >= 3)
{
exit(0);
}
if($('#testElement').is(':visible')){
//what you want to do when is visible
}
The default border-style
is none
, so you must specify that as well as the width and the colour.
You can use the border
shorthand property to set all three values in one go.
Also, the border attribute describes the border for the table and the cells. CSS is much more flexible so it only describes the border of the elements you are selecting. You need to select the cells too in order to get the same effect.
table, th, td {
border: solid black 1px;
}
See also border properties and tables in CSS.
I've searched a lot and the best way I've found so far is on this article:
Class to serialize
package net.sghill.example;
import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;
@JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
Deserializer class
package net.sghill.example;
import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
public class UserDeserializer extends JsonDeserializer<User> {
@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
}
}
Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.
const config = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters = {
key: "value"
};
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyParameters,
config
).then(console.log).catch(console.log);
The first parameter is the URL.
The second is the JSON body that will be sent along your request.
The third parameter are the headers (among other things). Which is JSON as well.
from Chrome 60, they removed the facility of blue text color while writing console.info and does many much changes in console API.
if you write a string literal in the es6 pattern, using the backticks `` as the identifier (called as template string ) in console.log() then below way can colorize the console output.
console.log(`%cToday date=>%c${new Date()}`,`color:#F74C2F`, `color:green`);
// output :Today date (in red color) => Date (in green color)
Use the "REPLACE" string function on the column in question:
UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)
Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.
Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.
Marc
I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.
Question for Microsoft: Why does this work:
? lst.SelectedValue
But this doesn't?
? lst.Items[80].Value
I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:
? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]
Now that's just ridiculous.
$sumArray = array();
foreach ($myArray as $k => $subArray) {
foreach ($subArray as $id => $value) {
if (!isset($sumArray[$id])) {
$sumArray[$id] = 0;
}
$sumArray[$id]+=$value;
}
}
Use the annotation @Deprecated
for your method, and you should also mention it in your javadocs.
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
Redirect the page on itself and display the counter value on button click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write(Request.RawUrl.ToString()); // redirect on itself
Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
}
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:
Use raw_input
in Python 2.x, and input
in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)
For example:
user_input = raw_input("Some input please: ")
More details can be found here.
So, for example, you might have a script that looks like this
# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)
# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3
# Now do something with the above
print(user_input)
If you saved this in foo.py
, you could just call the script from the command line, it would print out tok tiktok
, then ask you for input. You could enter bar baz
(followed by the enter key) and it would print bar baz
. Here's what that would look like:
$ python foo.py
tok tiktok
Some input please: bar baz
bar baz
Here, $
represents the command-line prompt (so you don't actually type that), and I hit Enter
after typing bar baz
when it asked for input.
Suppose you have a script named foo.py
and want to call it with arguments bar
and baz
from the command line like
$ foo.py bar baz
(Again, $
represents the command-line prompt.) Then, you can do that with the following in your script:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
Here, the variable arg1
will contain the string 'bar'
, and arg2
will contain 'baz'
. The object sys.argv
is just a list containing everything from the command line. Note that sys.argv[0]
is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:]
.
I had the same problem and the issue was that my child component had an @input
named formControl
.
So I just needed to change from:
<my-component [formControl]="formControl"><my-component/>
to:
<my-component [control]="control"><my-component/>
ts:
@Input()
control:FormControl;
I have tried this for my case and it'll work fine.
var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);
Sample output:
9.007
if you are using android.support.v7.app.AppCompatActivity
public class HomeActivity extends AppCompatActivity {
Then you should be using android.support.v7.app.ActionBar
ActionBar ab = getSupportActionBar();
If you are using android.support.v4.app.FragmentActivity
public class HomeActivity extends FragmentActivity {
then you should be using android.app.ActionBar
ActionBar ab = getActionBar();
If you are using android.support.v7.app.ActionBarActivity
public class HomeActivity extends ActionBarActivity {
you should be using android.support.v7.app.ActionBar
ActionBar ab = getSupportActionBar();
If you try set a value in datetime-local
date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));
//output : 2010-12-30T23:21
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("form").submit();
}
});
I had the same problem as you.
Here's what I did (dynamically generated GET form with action set to location.href, hidden input with fresh value), and it seems to work in all browsers:
var elForm=document.createElement("form");
elForm.setAttribute("method", "get");
elForm.setAttribute("action", window.location.href);
var elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", "r");
elInputHidden.setAttribute("value", new Date().getTime());
elForm.appendChild(elInputHidden);
if(window.location.href.indexOf("?")>=0)
{
var _arrNameValue;
var strRequestVars=window.location.href.substr(window.location.href.indexOf("?")+1);
var _arrRequestVariablePairs=strRequestVars.split("&");
for(var i=0; i<_arrRequestVariablePairs.length; i++)
{
_arrNameValue=_arrRequestVariablePairs[i].split("=");
elInputHidden=document.createElement("input");
elInputHidden.setAttribute("type", "hidden");
elInputHidden.setAttribute("name", decodeURIComponent(_arrNameValue.shift()));
elInputHidden.setAttribute("value", decodeURIComponent(_arrNameValue.join("=")));
elForm.appendChild(elInputHidden);
}
}
document.body.appendChild(elForm);
elForm.submit();
The ScrollTo()
function doesn't work anymore. This is what I used and it worked fine.
driver.execute_script("document.getElementById('mydiv').scrollIntoView();")
It stands for Dimension, but is generally read as "Create Variable," or "Allocate Space for This."
If you pass only vectors to cbind()
it creates a matrix, not a dataframe. Read ?data.frame
.
Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.
.myTable td:nth-child(1),.myTable th:nth-child(1) {
width: 20px;
}
if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there
You can view which modules (compiled in) are available via terminal through php -m
Maybe not the most elegant solution, but here's a solution using nested while loops:
def transpose(lst):
newlist = []
i = 0
while i < len(lst):
j = 0
colvec = []
while j < len(lst):
colvec.append(lst[j][i])
j = j + 1
newlist.append(colvec)
i = i + 1
return newlist
What you need to know in one place:
ASPNETCORE_
. :
as a separater. If the platform doesn't allow colons in environment variable keys, use __
instead.ApplicationHost.config
. Using the IIS Configuration Editor will cause your inputs to be written to the application's Web.config
-- and will be overwritten with the next deployment!For modifying ApplicationHost.config
, you want to use appcmd.exe
to make sure your modifications are consistent. Example: %systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /+"environmentVariables.[name='ASPNETCORE_AWS:Region',value='eu-central-1']" /commit:site
Characters that are not URL-safe can be escaped as Unicode, like %u007b
for left curly bracket.
%systemroot%\system32\inetsrv\appcmd.exe list config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore
%systemroot%\system32\inetsrv\appcmd.exe set config "Default Web Site/MyVirtualDir" -section:system.webServer/aspNetCore /-"environmentVariables.[name='ASPNETCORE_MyKey',value='value-to-be-removed']" /commit:site
.Answering this in October 2018. The working code is the one using the pageID. I just tested it and it is functional.
public static void openUrl(Context ctx, String url){
Uri uri = Uri.parse(url);
if (url.contains(("facebook"))){
try {
ApplicationInfo applicationInfo = ctx.getPackageManager().getApplicationInfo("com.facebook.katana", 0);
if (applicationInfo.enabled) {
uri = Uri.parse("fb://page/<page_id>");
openURI(ctx, uri);
return;
}
} catch (PackageManager.NameNotFoundException ignored) {
openURI(ctx, uri);
return;
}
}
pip install numpy scipy scikit-learn
if you don't have pip, install it using
python get-pip.py
Download get-pip.py from the following link. or use curl to download it.
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Hi this is odd way but try it once
XMLDocument.LoadXML(xmlstring)
I try with your code and same XML without adding any XML declaration it works for me
XmlDocument doc = new XmlDocument();
doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
XmlNodeList nodes = doc.GetElementsByTagName("Product");
XmlNode node = null;
foreach (XmlNode n in nodes)
{
Console.WriteLine("HI");
}
when you create a job in nohup it will tell you the process ID !
nohup sh test.sh &
the output will show you the process ID like
25013
you can kill it then :
kill 25013
IIS version 8.5 +
To enable Event Tracing for Windows for your website/application
Custom Views > ServerRoles > Web Server
Windows Logs > System
If value
is a string
in that format and you'd like to convert it into a DateTime
object, you can use DateTime.ParseExact
static method:
DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);
Example:
string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(myDate.ToShortDateString());
Result:
2012-12-01
//Mysql sum of multiple rows Hi Here is the simple way to do sum of columns
SELECT sum(IF(day_1 = 1,1,0)+IF(day_3 = 1,1,0)++IF(day_4 = 1,1,0)) from attendence WHERE class_period_id='1' and student_id='1'
If someone looks for this…
I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files
With rsync-files:
my-dir/
my-file.txt
- /*
Use the analytic function :
select case when
max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1
else 0 end as flag
from MYTABLE;
Here is a vanilla Java answer:
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(targetUrl)
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(requestBody))
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();
Just an update of Christopher answer.
Since the version 2.6.0
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.0</version>
</dependency>
Use the JavaTimeModule instead of JSR310Module (deprecated).
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper MAPPER;
public ObjectMapperContextResolver() {
MAPPER = new ObjectMapper();
MAPPER.registerModule(new JavaTimeModule());
MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return MAPPER;
}
}
According to the documentation, the new JavaTimeModule uses same standard settings to default to serialization that does NOT use Timezone Ids, and instead only uses ISO-8601 compliant Timezone offsets.
Behavior may be changed using SerializationFeature.WRITE_DATES_WITH_ZONE_ID
You may use Cultures to parse and format your string, eg
var cultureSource = new CultureInfo("en-US", false);
var cultureDest = new CultureInfo("de-DE", false);
var source = "01:00 pm";
var dt = DateTime.Parse(source, cultureSource);
Console.WriteLine(dt.ToString("t", cultureDest));
This prints 13:00
You can flush hosts local MySQL using following command:
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
Though Amazon RDS database server is on network then use the following command as like as flush network MySQL server:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
In additional suggestion you can permanently solve blocked of many connections error problem by editing my.ini file[Mysql configuration file]
change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)
modify list of host names for your system:
C:\Windows\System32\drivers\etc\hosts
Make sure that you have the following entry:
127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem
(you may need to change modify permission to modify this file)
This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.
Just Tried that:
return(
<>
{
main-condition-1 &&
main-condition-2 &&
(sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
}
</>
)
Let me know what you guys think!!!
Why do you need -Xms768 (small heap must be at least 768...)?
That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.
Try -Xms16 -Xmx2048m, for instance.
The Java way to do what you want is to use the ServiceLoader mechanism.
Also many people roll their own by having a file in a well known classpath location (i.e. /META-INF/services/myplugin.properties) and then using ClassLoader.getResources() to enumerate all files with this name from all jars. This allows each jar to export its own providers and you can instantiate them by reflection using Class.forName()
If you want only those commits which are done by you in a particular branch, use the below command.
git log branch_name --author='Dyaniyal'
Just use CSS transitions instead of animations.
A {
color: #999;
transition: color 1s ease-in-out;
}
A:hover {
color: #000;
}
Try something like this
select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT
I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.
For .NET 4.5 and higher, you should use:
var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
The "IIS APPPOOL\AppPoolName" will work, but as mentioned previously, it does not appear to be a valid AD name so when you search for it in the "Select User or Group" dialog box, it won't show up (actually, it will find it, but it will think its an actual system account, and it will try to treat it as such...which won't work, and will give you the error message about it not being found).
How I've gotten it to work is:
As long as the AppPool name actually exists, the login should now be created.
I just solved this kind of a problem. What I've learned is:
my.cnf
and set the bind-address = your.mysql.server.address
under [mysqld]
check if it's running
mysql -u root -h your.mysql.server.address –p
create a user (usr or anything) with % as domain and grant her access to the database in question.
mysql> CREATE USER 'usr'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON testDb.* TO 'monty'@'%' WITH GRANT OPTION;
open firewall for port 3306 (you can use iptables. make sure to open port for eithe reveryone, or if you're in tight securety, then only allow the client address)
you should be able to now connect mysql server form your client server php script.
If you can overlook the height of TextBlock, it's better for you to use this:
<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>
Recently, I faced similar problem and I solved it using following approach
def round(value: Either[Double, Float], places: Int) = {
if (places < 0) 0
else {
val factor = Math.pow(10, places)
value match {
case Left(d) => (Math.round(d * factor) / factor)
case Right(f) => (Math.round(f * factor) / factor)
}
}
}
def round(value: Double): Double = round(Left(value), 0)
def round(value: Double, places: Int): Double = round(Left(value), places)
def round(value: Float): Double = round(Right(value), 0)
def round(value: Float, places: Int): Double = round(Right(value), places)
I used this SO issue. I have couple of overloaded functions for both Float\Double and implicit\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.
Simplest way to add borders to inset the borders using InsetDrawable
,following will show top border only :
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetBottom="-2dp"
android:insetLeft="-2dp"
android:insetRight="-2dp">
<shape android:shape="rectangle">
<solid android:color="@color/light_gray" />
<stroke
android:width=".5dp"
android:color="@color/dark_gray" />
</shape>
</inset>
If you are trying to "Submit and Reset" the the "form" with one Button click, Try this!
Here I have used jQuery function, it can be done by simple JavaScript also...
<form id="form_data">
<input type="anything" name="anything" />
<input type="anything" name="anything" />
<!-- Save and Reset button -->
<button type="button" id="btn_submit">Save</button>
<button type="reset" id="btn_reset" style="display: none;"></button>
</form>
<script type="text/javascript">
$(function(){
$('#btn_submit').click(function(){
// Do what ever you want
$('#btn_reset').click(); // Clicking reset button
});
});
</script>
If you are using sass you can simply set below mentioned variables to use icons provided by other fonts,
$slick-font-family:FontAwesome;
$slick-prev-character: "\f053";
$slick-next-character: "\f054";
These will change the font family used by slick's theme css and also the unicode for prev and next button. This example will use FontAwesome's chevron-left and chevron-right icons.
Other sass variables which can be configured are given in Slick Github page
You could alter the figsize
by passing a tuple
showing the width, height
parameters you would like to keep.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
EDIT
I remember answering a similar question of yours where you had to set the index as TIMESTAMP
. So, you could then do something like below:
df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
For the head
of the dataframe you posted, the plot would look like:
Transmission Delay:
This is the amount of time required to transmit all of the packet's bits into the link. Transmission delays are typically on the order of microseconds or less in practice.
L: packet length (bits)
R: link bandwidth (bps)
so transmission delay is = L/R
Propagation Delay:
Is the time it takes a bit to propagate over the transmission medium from the source router to the destination router; it is a function of the distance between the two routers, but has nothing to do with the packet's length or the transmission rate of the link.
d: length of physical link
S: propagation speed in medium (~2x108m/sec, for copper wires & ~3x108m/sec, for wireless media)
so propagation delay is = d/s
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...
As of version : 1.26.1 (linux), the shortcut is not set by default. To set the shortcut
For editor focus is already set by default.
Which SDKs? If you mean the SDK for Cocoa development, you can check in /Developer/SDKs/
to see which ones you have installed.
If you're looking for the Java SDK version, then open up /Applications/Utilities/Java Preferences
. The versions of Java that you have installed are listed there.
On Mac OS X 10.6, though, the only Java version is 1.6.
It was suggested by Mark Mishyn to use slice but there is no reason to create array with make
and use in for
returned slice of it when array created via literal can be used and it's shorter
for i := range [5]int{} {
fmt.Println(i)
}
The best way to do this is take backup of required database and reconfigure the server.
Creating A Backup
The mysqldump command is used to create textfile “dumps” of databases managed by MySQL. These dumps are just files with all the SQL commands needed to recreate the database from scratch. The process is quick and easy.
If you want to back up a single database, you merely create the dump and send the output into a file, like so:
mysqldump database_name > database_name.sql
Multiple databases can be backed up at the same time:
mysqldump --databases database_one database_two > two_databases.sql
In the code above, database_one is the name of the first database to be backed up, and database_two is the name of the second.
It is also simple to back up all of the databases on a server:
mysqldump --all-databases > all_databases.sql
After taking the backup, remove mysql and reinstall it. After reinstalling with the desired port number.
Restoring a Backup
Since the dump files are just SQL commands, you can restore the database backup by telling mysql to run the commands in it and put the data into the proper database.
mysql database_name < database_name.sql
In the code above, database_name is the name of the database you want to restore, and database_name.sql is the name of the backup file to be restored..
If you are trying to restore a single database from dump of all the databases, you have to let mysql know like this:
mysql --one-database database_name < all_databases.sql
This is quite an old question, but I'm going to provide a modern solution that's been available since ES6 - export and import:
In first.js
:
let colorcodes = <whatever>;
export default colorcodes //or a different export statement
In second.js
:
import colorcodes from <path-to-first.js> //or a matching import statement
One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:
SELECT a.ID,
a.AText,
(SELECT Count(ID)
FROM table1 b WHERE b.ID <= a.ID
AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;
git bash is a shell where:
sh.exe
(packaged with msysgit, as share/WinGit/Git Bash.vbs
)$HOME
is definedSee "Fix msysGit Portable $HOME
location":
On a Windows 64:
C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"
This differs from git-cmd.bat
, which provides git commands in a plain DOS command prompt.
A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)
Update April 2015:
Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:
GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.
But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2
comes with its own installer too.
The git bash is now (with the new Git For Windows):
GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.
Original answer (June 2013) More precisely, from msygit wiki:
Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.To make the milky 'soup' of project names more clear, we say like this:
- msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
- MinGW - is a minimalist development environment for native Microsoft Windows applications.
It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as afork()
call- MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
- Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit
So, your two lines description about "git bash" are:
"Git bash
" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.
Reminder:
msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.
msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.
See more in "Difference between msysgit and Cygwin + git?".
// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;
int main()
{
pt::ptime current_date_microseconds = pt::microsec_clock::local_time();
long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();
pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);
pt::ptime current_date_milliseconds(current_date_microseconds.date(),
current_time_milliseconds);
std::cout << "Microseconds: " << current_date_microseconds
<< " Milliseconds: " << current_date_milliseconds << std::endl;
// Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
I just want to put my view
So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.
public interface GenericReturnType{
public static RETURN_TYPE enum{
MACHINE, PERSON;
}
public RETURN_TYPE getReturnType();
}
public class PersonReturnType implements GenericReturnType{
// CONSTRUCTORS //
// GETTRE AND SETTER //
public RETURN_TYPE getReturnType(){
return PERSON;
}
public String getAddress(){
return something;
}
}
public class MachineReturnType implements GenericReturnType{
// CONSTRUCTORS //
// GETTRE AND SETTER //
public RETURN_TYPE getReturnType(){
return MACHINE;
}
public String getManufatureName(){
return something;
}
}
public class TestService{
public GenericReturnType getObject(// some input //){
GenericReturnType obj ;
if(// some code //){
obj = new PersonReturnType();
// some code //
}
if(// some code //){
obj = new MachineReturnType();
// some code //
}
return obj;
}
}
public class TestDriver{
TestService service = new TestService();
GenericReturnType genObj = TestService.getObject(// some input //);
if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
// SOME CODE //
}
if(genObj.getReturnType() == RETURN_TYPE.PERSON){
// SOME CODE //
}
}
I had a similar problem today and found refactoring the conditional logic into a separate function to help.
I find it more readable than the labels and people are more comfortable with return
than break
. Inline functions are similar but the indentation can get a bit confusing.
In your case it would look like this.
function doThing() {
checkConditions();
// Rest of the code here
}
function checkConditions() {
if (c1) {
if (c2) {
return do1();
else {
return;
}
} else {
return do3();
}
}
As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.
df[cat]=df[cat].astype('category')
And then check df.dtypes and perform label encoding.
Yup. :) You can use Hipify to convert CUDA code very easily to HIP code which can be compiled run on both AMD and nVidia hardware pretty good. Here are some links
I found that the following code, when inserted into the site's footer, worked well enough:
<script type="text/javascript">
$("#nav-ask").remove();
</script>
This may or may not require jquery. The site I'm editing has jquery, but unfortunately I'm no javascripter, so I only have a limited knowledge of what's going on here, and the requirements of this code snippet...
If you are a student and new to Java there might be some issue going on with your web.xml file.
- Try removing the web.xml file.
- Secondly check that your path variables are properly set or not.
- Restart tomcat server Or your PC.
Your problem will be surely solved.
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
Here is a simple way without stragg or creating a function.
create table countries ( country_name varchar2 (100));
insert into countries values ('Albania');
insert into countries values ('Andorra');
insert into countries values ('Antigua');
SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
COUNT (*) OVER () cnt
FROM countries)
WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;
CSV
--------------------------
Albania,Andorra,Antigua
1 row selected.
As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.
select listagg(country_name,', ') within group(order by country_name) csv
from countries;
CSV
--------------------------
Albania, Andorra, Antigua
1 row selected.
You can get current time in milliseconds since January 1st, 1970 using an NSDate:
- (double)currentTimeInMilliseconds {
NSDate *date = [NSDate date];
return [date timeIntervalSince1970]*1000;
}
I like to think of the general difference as being:
A small static custom method in a Util
class would help:
public static int getIndex(Set<? extends Object> set, Object value) {
int result = 0;
for (Object entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
If you need/want one class that is a Set
and offers a getIndex()
method, I strongly suggest to implement a new Set
and use the decorator pattern:
public class IndexAwareSet<T> implements Set {
private Set<T> set;
public IndexAwareSet(Set<T> set) {
this.set = set;
}
// ... implement all methods from Set and delegate to the internal Set
public int getIndex(T entry) {
int result = 0;
for (T entry:set) {
if (entry.equals(value)) return result;
result++;
}
return -1;
}
}
To move up a directory, the quickest way would be to add an alias to ~/.bash_profile
alias ..='cd ..'
and then one would need only to type '..[return]'.
This will work but the element will still in the DOM.
.hidden {
display: none;
}
<div [class.hidden]="!show" *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
The concise version:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
Add a try/catch block for a ParseException to ensure the format is a valid date.
I was really confused by this for a while but finally figured it out. We made updates to our site and had some numbers converting to a link and some weren't. Turns out that numbers won't be converted to a link if they're in a <fieldset>. Obviously not the right solution for most circumstances, but in some it will be the right one.
Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.
I think you should use AJAX with that,
There are plenty PHP AJAX Frameworks to choose from
http://www.phplivex.com/example/submitting-html-forms-with-ajax
http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/
ETC.
Or the classic way
http://www.w3schools.com/php/php_ajax_php.asp
I hope these links help
I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.
if / else
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
if / else if
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
Infinity, NaN and subnormals
These are important caveats that no other answer has mentioned so far.
First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?
Then, for single precision floats (32-bit):
IEEE 754 says that if the exponent is all ones (0xFF == 255
), then it represents either NaN or Infinity.
This is why the largest non-infinite number has exponent 0xFE == 254
and not 0xFF
.
Then with the bias, it becomes:
254 - 127 == 127
FLT_MIN
is the smallest normal number. But there are smaller subnormal ones! Those take up the -127
exponent slot.
All asserts of the following program pass on Ubuntu 18.04 amd64:
#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
float float_from_bytes(
uint32_t sign,
uint32_t exponent,
uint32_t fraction
) {
uint32_t bytes;
bytes = 0;
bytes |= sign;
bytes <<= 8;
bytes |= exponent;
bytes <<= 23;
bytes |= fraction;
return *(float*)&bytes;
}
int main(void) {
/* All 1 exponent and non-0 fraction means NaN.
* There are of course many possible representations,
* and some have special semantics such as signalling vs not.
*/
assert(isnan(float_from_bytes(0, 0xFF, 1)));
assert(isnan(NAN));
printf("nan = %e\n", NAN);
/* All 1 exponent and 0 fraction means infinity. */
assert(INFINITY == float_from_bytes(0, 0xFF, 0));
assert(isinf(INFINITY));
printf("infinity = %e\n", INFINITY);
/* ANSI C defines FLT_MAX as the largest non-infinite number. */
assert(FLT_MAX == 0x1.FFFFFEp127f);
/* Not 0xFF because that is infinite. */
assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
assert(!isinf(FLT_MAX));
assert(FLT_MAX < INFINITY);
printf("largest non infinite = %e\n", FLT_MAX);
/* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
assert(FLT_MIN == 0x1.0p-126f);
assert(FLT_MIN == float_from_bytes(0, 1, 0));
assert(isnormal(FLT_MIN));
printf("smallest normal = %e\n", FLT_MIN);
/* The smallest non-zero subnormal number. */
float smallest_subnormal = float_from_bytes(0, 0, 1);
assert(smallest_subnormal == 0x0.000002p-126f);
assert(0.0f < smallest_subnormal);
assert(!isnormal(smallest_subnormal));
printf("smallest subnormal = %e\n", smallest_subnormal);
return EXIT_SUCCESS;
}
Compile and run with:
gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out
Output:
nan = nan
infinity = inf
largest non infinite = 3.402823e+38
smallest normal = 1.175494e-38
smallest subnormal = 1.401298e-45
I got the same problem and resolve it by deleting node module
package and then again install yarn. Simply on some changes we need to clear our.
If you want to set options temporarily to display one large DataFrame, you can use option_context:
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
print (df)
Option values are restored automatically when you exit the with
block.
If you want to set environment variables permanently in Git-Bash, you have two options:
Set a regular Windows environment variable. Git-bash gets all existing Windows environment variables at startupp.
Set up env variables in .bash_profile
file.
.bash_profile
is by default located in a user home folder, like C:\users\userName\git-home\.bash_profile
. You can change the path to the bash home folder by setting HOME
Windows environment variable.
.bash_profile
file uses the regular Bash syntax and commands
# Export a variable in .bash_profile
export DIR=c:\dir
# Nix path style works too
export DIR=/c/dir
# And don't forget to add quotes if a variable contains whitespaces
export ANOTHER_DIR="c:\some dir"
Read more information about Bash configurations files.
Does nobody use pointers anymore?
void inplace_rev( char * s ) {
char t, *e = s + strlen(s);
while ( --e > s ) { t = *s;*s++=*e;*e=t; }
}
EDIT: Sorry, just noticed the above XOR example...
If you facing grant permission access denied problem, you can try mysql_upgrade to fix the problem:
/usr/bin/mysql_upgrade -u root -p
Login as root:
mysql -u root -p
Run this commands:
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
mysql> FLUSH PRIVILEGES;
A new byte array will automatically be initialized with all zeroes. You don't have to do anything.
The more general approach to initializing with other values, is to use the Arrays
class.
import java.util.Arrays;
byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );
Here is a list of formatters used with String.format()
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
I'm just using a predefined directory on the host to persist data for PostgreSQL. Also, this way it is possible to easily migrate existing PostgreSQL installations to Docker containers: https://crondev.com/persistent-postgresql-inside-docker/
Using the principle of the idea user2620505 got result with implementation of addClass:
...
open: function(){
$('.ui-dialog-titlebar-close').addClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only');
$('.ui-dialog-titlebar-close').append('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
},
...
If English is bad forgive me, I am using Google Translate.
Here is the Javascript Code: (index.php)
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
Here is the PHP Code: (sqldb.php)
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
I hope that you know how to get the $userid from the Session, and for that you need an Database with the Table called users, and an Table inside users called screen ;=) Regards KSP
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
The above answers require you to malloc a new stream object.
public <T>
boolean containsByLambda(Collection<? extends T> c, Predicate<? super T> p) {
for (final T z : c) {
if (p.test(z)) {
return true;
}
}
return false;
}
public boolean containsTabById(TabPane tabPane, String id) {
return containsByLambda(tabPane.getTabs(), z -> z.getId().equals(id));
}
...
if (containsTabById(tabPane, idToCheck))) {
...
}
Try this
var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;
if (mainURL == URL) {
mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
console.log(mainURL)
}
To avoid try catch, use:
String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
System.out.println(b.length);
Use "include" for reusable PHP templates. Use "require" for required libraries.
"*_once" is nice, because it checks whether the file is already loaded or not, but it only makes sense for me in "require_once".
If it is a selection, you can do it as:
SELECT id, value, (value/2) AS calculated FROM mytable
Else, you can also first alter the table to add the missing column and then do an UPDATE query to compute the values for the new column as:
UPDATE mytable SET calculated = value/2;
If it must be automatic, and your MySQL version allows it, you can try with triggers
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
string[] lines = Regex.Split(value, ".{5}");
string out = "";
foreach (string line in lines)
{
out += "-" + line;
}
out = out.Substring(1);
pro swing:
But at the bottom line I wouldn't suggest to use 'pure' swing or swt ;-) There are several application frameworks for swing/swt out. Look here. The biggest players are netbeans (swing) and eclipse (swt). Another nice framework could be griffon and a nice 'set of components' is pivot (swing). Griffon is very interesting because it integrates a lot of libraries and not only swing; also pivot, swt, etc
Basing on this answer if you need history object only in order to navigate to other component:
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
I don't know about the runtime disadvantages about the following but you could run a regexp match on your string to make sure it is a number before trying to parse it, thus
cost.matches("-?\\d+\\.?\\d+")
for a float
and
cost.matches("-?\\d+")
for an integer
EDIT
please notices @Voo's comment about max int
Correct rounding is likely desired.
Therefore math.Round() is your quick(!) friend. Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.
package main
import (
"fmt"
"math"
)
func main() {
var x float64 = 5.51
var y float64 = 5.50
var z float64 = 5.49
fmt.Println(int(math.Round(x))) // outputs "6"
fmt.Println(int(math.Round(y))) // outputs "6"
fmt.Println(int(math.Round(z))) // outputs "5"
}
math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.
The main difference between Thread and Runnable is: - Thread is like: Worker (execute Runnable) - Runnable is like: Job (to be executed by Thread)
import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
print 'matched'
Using text-indent on li works best.
text-indent: -x px; will move the bullet closer to li and vice-versa.
Using relative on span the negative left might not work properly with older versions for IE. P.S- avoid giving positions as much as you can.
In the <tomcat-home>\conf\catalina.properties
file, add this new line:
spring.profiles.active=dev
The .NET framework uses banker's rounding in Math.Round
by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0
use
document.getElementsByTagName(" * ");
to get all XML elements from within an XML file, this does however return repeating attributes
example:
NodeList list = doc.getElementsByTagName("*");
System.out.println("XML Elements: ");
for (int i=0; i<list.getLength(); i++) {
Element element = (Element)list.item(i);
System.out.println(element.getNodeName());
}
Users\ your user name \
It's almost always advisable to not use scriptlets in your JSP. They're considered bad form. Instead, try using JSTL (JSP Standard Tag Library) combined with EL (Expression Language) to run the conditional logic you're trying to do. As an added benefit, JSTL also includes other important features like looping.
Instead of:
<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
out.print("I see! You don't have a name.. well.. Hello no name");
}
else {%>
<%@ include file="response.jsp" %>
<% } %>
Use:
<c:choose>
<c:when test="${empty user}">
I see! You don't have a name.. well.. Hello no name
</c:when>
<c:otherwise>
<%@ include file="response.jsp" %>
</c:otherwise>
</c:choose>
Also, unless you plan on using response.jsp somewhere else in your code, it might be easier to just include the html in your otherwise statement:
<c:otherwise>
<h1>Hello</h1>
${user}
</c:otherwise>
Also of note. To use the core tag, you must import it as follows:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
You want to make it so the user will receive a message when the user submits a username. The easiest way to do this is to not print a message at all when the "user" param is null
. You can do some validation to give an error message when the user submits null
. This is a more standard approach to your problem. To accomplish this:
In scriptlet:
<% String user = request.getParameter("user");
if( user != null && user.length() > 0 ) {
<%@ include file="response.jsp" %>
}
%>
In jstl:
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>
<meta http-equiv="Refresh" content="n;url">
That's It. Easy, Right?
<meta http-equiv="Refresh" content="n;url">
_x000D_
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
Set the main div
CSS to somthing like:
<style>
.wrapper{
display:flex;
flex-direction: column;
}
</style>
<div id="wrapper">
<div id="inner1">This is inner div 1</div>
<div id="inner2">This is inner div 2</div>
</div>
For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Use setWebViewClient() and override onPageFinished()
Catching the user id as path variable (recommended):
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected]" http://mysuperserver/media/1234/upload/
Catching the user id as part of the form:
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected];userid=1234" http://mysuperserver/media/upload/
or:
curl -i -X POST -H "Content-Type: multipart/form-data"
-F "[email protected]" -F "userid=1234" http://mysuperserver/media/upload/
To display the item number on the repeater you can use the Container.ItemIndex
property.
<asp:repeater id="rptRepeater" runat="server">
<itemtemplate>
Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
</itemtemplate>
<separatortemplate>
<br />
</separatortemplate>
</asp:repeater>
Three problems here:
String.matches()
- if the API is there, use itI recommend you use code like this:
public boolean matches(String regex) {
regex = "^.*" + regex + ".*$"; // pad with regex to allow partial matching
System.out.println("abcABC ".matches(regex));
return "abcABC ".matches(regex);
}
public static void main(String[] args) {
HowEasy words = new HowEasy();
words.matches("[a-zA-Z]+"); // added "+" (ie 1-to-n of) to character class
}
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject
, then first get a String
from the result
:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject
:
JSONObject jsonObject = new JSONObject(jsonString);