There is one more solution to set column Full text to true.
These solution for example didn't work for me
ALTER TABLE news ADD FULLTEXT(headline, story);
My solution.
NEXT STEPS
Refresh
Version of mssql 2014
I have two methods to detect WIFI connection receiving the application context:
public boolean isConnectedWifi1(Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
NetworkInfo[] netInfo = connectivityManager.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ((ni.getTypeName().equalsIgnoreCase("WIFI"))
&& ni.isConnected()) {
return true;
}
}
}
return false;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return false;
}
public boolean isConnectedWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return networkInfo.isConnected();
}
When displaying, you can use (for example)
>> '%.2f' % 2.3465
=> "2.35"
If you want to store it rounded, you can use
>> (2.3465*100).round / 100.0
=> 2.35
I believe you can only initialize the dialog one time. The example above is trying to initialize the dialog every time #terms is clicked. This will cause problems. Instead, the initialization should occur outside of the click event. Your example should probably look something like this:
$(document).ready(function() {
// dialog init
$('#terms').dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 400,
height: 450,
overlay: { backgroundColor: "#000", opacity: 0.5 },
buttons: { "Close": function() { $(this).dialog('close'); } },
close: function(ev, ui) { $(this).close(); }
});
// click event
$('#showTerms').click(function(){
$('#terms').dialog('open').css('display','inline');
});
// date picker
$('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
});
I'm thinking that once you clear that up, it should fix the 'open from link' issue you described.
maybe this can help..
SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";
Have a look at this jQuery plugin from OvalPixels.
It may do the trick.
Change the type
to submit
and give it a name
(and remove the useless onclick
and flat out the 90's style uppercased tags/attributes).
<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />
...
The value will be available by $_POST['foo']
(if the parent <form>
has a method="post"
).
Use str = ""+a+b+c;
Here the first +
is String
concat, so the result will be a String
. Note where the ""
lies is important.
Or (maybe) better, use a StringBuilder
.
you must use the following properties for a button
element to make it transparent.
button {
background: transparent;
border: none !important;
font-size:0;
}
button {
background: transparent;
border: none !important;
}?
and use absolute position
to position the element.
you have the button element under a div. Use position
: relative on div and position
: absolute on the button to position it within the div.
here is a working JSFiddle
here is an updated JSFiddle that displays only text from the button.
Without component or external Library in Tomcat 6 o 7
Enabling Upload in the web.xml file:
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
AS YOU CAN SEE:
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
Uploading Files using JSP. Files:
In the html file
<form method="post" enctype="multipart/form-data" name="Form" >
<input type="file" name="fFoto" id="fFoto" value="" /></td>
<input type="file" name="fResumen" id="fResumen" value=""/>
In the JSP File or Servlet
InputStream isFoto = request.getPart("fFoto").getInputStream();
InputStream isResu = request.getPart("fResumen").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int qt = 0;
while ((qt = isResu.read(buf)) != -1) {
baos.write(buf, 0, qt);
}
String sResumen = baos.toString();
Edit your code to servlet requirements, like max-file-size, max-request-size and other options that you can to set...
You can always press CTRL-B + SHIFT-D to choose which client you want to detach from the session.
tmux will list all sessions with their current dimension. Then you simply detach from all the smaller sized sessions.
I do it like this and it's work for me, I hope this will help :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>
very simple just add this to your bound field DataFormatString="{0: yyyy/MM/dd}"
I face same problem on chrome with ckeditor 4.7.1. Just disable pasteFilter on ckeditor instanceReady.This property disable all filter options of Advance Content Filter(ACF).
CKEDITOR.on('instanceReady', function (ev) {
ev.editor.pasteFilter.disabled = true;
});
The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:
scp [email protected]:/somedir/table /home/me/Desktop/.
The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.
INSERT...ON DUPLICATE KEY UPDATE
is prefered to prevent unexpected Exceptions management.
In my case I know that col1
and col2
make a unique composite index.
It keeps track of the error, but does not throw an exception on duplicate. Regarding the performance, the update by the same value is efficient as MySQL notices this and does not update it
INSERT INTO table
(col1, col2, col3, col4)
VALUES
(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
col1 = VALUES(col1),
col2 = VALUES(col2)
The idea to use this approach came from the comments at phpdelusions.net/pdo.
Step 1:
select object_name, s.sid, s.serial#, p.spid
from v$locked_object l, dba_objects o, v$session s, v$process p
where l.object_id = o.object_id and l.session_id = s.sid and s.paddr = p.addr;
Step 2:
alter system kill session 'sid,serial#'; --`sid` and `serial#` get from step 1
More info: http://www.oracle-base.com/articles/misc/killing-oracle-sessions.php
The query below will result in dd/mm/yy
format.
select LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)
or sometimes it's very easy just type Process.Start("http://www.example.com/")
then change the http://www.example.com/")
This is the full list of commands I used (Many thanks to the posters above):
sudo rm -rf /usr/local/lib/node /usr/local/lib/node_modules /var/db/receipts/org.nodejs.*
sudo rm -rf /usr/local/include/node /Users/$USER/.npm
sudo rm /usr/local/bin/node
sudo rm /usr/local/share/man/man1/node.1
brew install node
It is hard to make a good timing, because the performance.dominteractive is miscalulated (anyway an interesting link for timing developers).
When dom is parsed it still may load and execute deferred scripts. And inline scripts waiting for css (css blocking dom) has to be loaded also until DOMContentloaded. So it is not yet parsed?
And we have readystatechange event where we can look at readyState that unfortunately is missing "dom is parsed" that happens somewhere between "loaded" and "interactive".
Everything becomes problematic when even not the Timing API gives us a time when dom stoped parsing HTML and starting The End process. This standard say the first point has to be that "interactive" fires precisely after dom parsed! Both Chrome and FF has implemented it when document has finished loading sometime after it has parsed. They seem to (mis)interpret the standars as parsing continues beyond deferred scripts executed while people misinterpret DOMContentLoaded as something hapen before defered executing and not after. Anyway...
My recommendation for you is to read about? Navigation Timing API. Or go the easy way and choose a oneliner of these, or run all three and look in your browsers console ...
document.addEventListener('readystatechange', function() { console.log("Fiered '" + document.readyState + "' after " + performance.now() + " ms"); });
document.addEventListener('DOMContentLoaded', function() { console.log("Fiered DOMContentLoaded after " + performance.now() + " ms"); }, false);
window.addEventListener('load', function() { console.log("Fiered load after " + performance.now() + " ms"); }, false);
The time is in milliseconds after document started. I have verified with Navigation? Timing API.
To get seconds for exampe from the time you did var ti = performance.now()
you can do parseInt(performance.now() - ti) / 1000
Instead of that kind of performance.now() subtractions the code get little shorter by User Timing API where you set marks in your code and measure between marks.
which <command>
if [ $? == 1 ]; then
<pkg-manager> -y install <command>
fi
This solution seems to be working well for me. It builds on @pavok's solution by preserving ctrl key commands.
document.querySelector("input").addEventListener("keypress", function (e) {
if (
e.key.length === 1 && e.key !== '.' && isNaN(e.key) && !e.ctrlKey ||
e.key === '.' && e.target.value.toString().indexOf('.') > -1
) {
e.preventDefault();
}
});
There are two differences between static inner and non static inner classes.
In case of declaring member fields and methods, non static inner class cannot have static fields and methods. But, in case of static inner class, can have static and non static fields and method.
The instance of non static inner class is created with the reference of object of outer class, in which it has defined, this means it has enclosing instance. But the instance of static inner class is created without the reference of Outer class, which means it does not have enclosing instance.
See this example
class A
{
class B
{
// static int x; not allowed here
}
static class C
{
static int x; // allowed here
}
}
class Test
{
public static void main(String… str)
{
A a = new A();
// Non-Static Inner Class
// Requires enclosing instance
A.B obj1 = a.new B();
// Static Inner Class
// No need for reference of object to the outer class
A.C obj2 = new A.C();
}
}
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
The same thing is happening for me.
The reason is: I have used a list view with margin Top so the data is starting from the bottom of the image, but the actual list view is overlapping on the image which is not visible. So even if we click on the image, the action is not performed. To fix this, I have made the list view start from the below the image so that it is not overlapping on the image itself.
I created a godmode folder on the desktop. just create a new folder on the desktop and call it GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} it will name the folder as godmode and populate the content with various config options, you can then just type in ENVIRO in the search to find the relevant config option, open it and it opens sysdm.cpl in the advanced tab, you can change the environment variables from there.
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
This works for me. It should be in your onOptionsItemSelected(MenuItem item)
method item.setIcon(R.drawable.your_icon);
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
I have had to use a multiple IIF statement to create a similar result in ACCESS SQL.
IIf([refi type] Like "FHA ST*","F",IIf([refi type]="VA IRRL","V"))
All remaining will stay Null.
Which version of Firefox on which platform is your client using?
The are people having the same problem as documented here in the Support Forum for Firefox. I hope you can find a solution there. Good luck!
Update:
Let your client check the settings in Firefox: On "Advanced" - "Encryption" there is a button "View Certificates". Look for "Comodo CA Limited" in the list. I saw that Comodo is the issuer of the certificate of that domain name/server. On two of my machines (FF 3.0.3 on Vista and Mac) the entry is in the list (by default/Mozilla).
childView.bringToFront() didn't work for me, so I set the Z translation of the least recently added item (the one that was overlaying all other children) to a negative value like so:
lastView.setTranslationZ(-10);
see https://developer.android.com/reference/android/view/View.html#setTranslationZ(float) for more
All you need to do is, get the element of the input field you want to grow as you type and in CSS, set the width of the input to auto and set a min-width to say 50px.
Another succinct way of doing this is pandas.DataFrame.clip.
For example:
import pandas as pd
In [20]: df = pd.DataFrame({'a': [-1, 100, -2]})
In [21]: df
Out[21]:
a
0 -1
1 100
2 -2
In [22]: df.clip(lower=0)
Out[22]:
a
0 0
1 100
2 0
There's also df.clip_lower(0)
.
Since Django 2.0 the ForeignKey field requires two positional arguments:
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)
Here are some methods can used in on_delete
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.
Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.
you can find more about on_delete by reading the documentation.
You have configured the auth.php
and used members
table for authentication but there is no user_email
field in the members
table so, Laravel says
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))
Because, it tries to match the user_email
in the members
table and it's not there. According to your auth
configuration, laravel
is using members
table for authentication not users
table.
//%%%%%%%%%%%%%%%%%%%%%% HEX to ASCII %%%%%%%%%%%%%%%%%%%%%%
public String convertHexToString(String hex){
String ascii="";
String str;
// Convert hex string to "even" length
int rmd,length;
length=hex.length();
rmd =length % 2;
if(rmd==1)
hex = "0"+hex;
// split into two characters
for( int i=0; i<hex.length()-1; i+=2 ){
//split the hex into pairs
String pair = hex.substring(i, (i + 2));
//convert hex to decimal
int dec = Integer.parseInt(pair, 16);
str=CheckCode(dec);
ascii=ascii+" "+str;
}
return ascii;
}
public String CheckCode(int dec){
String str;
//convert the decimal to character
str = Character.toString((char) dec);
if(dec<32 || dec>126 && dec<161)
str="n/a";
return str;
}
C:\ <path to android sdk> \tools\source.properties (open with notepad)
There you will find it.
The listFiles
method, with or without a filter does not guarantee any order.
It does, however, return an array, which you can sort with Arrays.sort()
.
File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
This works because File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.
If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
Replace the System.out::println
with whatever you want to do with the file names. If you want only filenames that end with "xml"
just do:
Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
Again, replace the printing with whichever processing operation you would like.
I had some strings in the MongoDB Stored wich had to be reformated to a proper and valid dateTime field in the mongodb.
here is my code for the special date format: "2014-03-12T09:14:19.5303017+01:00"
but you can easyly take this idea and write your own regex to parse the date formats:
// format: "2014-03-12T09:14:19.5303017+01:00"
var myregexp = /(....)-(..)-(..)T(..):(..):(..)\.(.+)([\+-])(..)/;
db.Product.find().forEach(function(doc) {
var matches = myregexp.exec(doc.metadata.insertTime);
if myregexp.test(doc.metadata.insertTime)) {
var offset = matches[9] * (matches[8] == "+" ? 1 : -1);
var hours = matches[4]-(-offset)+1
var date = new Date(matches[1], matches[2]-1, matches[3],hours, matches[5], matches[6], matches[7] / 10000.0)
db.Product.update({_id : doc._id}, {$set : {"metadata.insertTime" : date}})
print("succsessfully updated");
} else {
print("not updated");
}
})
select to_char(date,'Mon') as mon,
extract(year from date) as yyyy,
sum("Sales") as "Sales"
from yourtable
group by 1,2
At the request of Radu, I will explain that query:
to_char(date,'Mon') as mon,
: converts the "date" attribute into the defined format of the short form of month.
extract(year from date) as yyyy
: Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.
sum("Sales") as "Sales"
: The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.
group by 1,2
: The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.
Turn on grep
's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)
tail -f file | grep --line-buffered my_pattern
It looks like a while ago --line-buffered
didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered
is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).
You can use the command line cc.rnl ', '
of ConyEdit (a plugin) to replace new lines with the contents you want.
Replace N with your Highest Number
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
Explanation
The query above can be quite confusing if you have not seen anything like it before – the inner query is what’s called a correlated sub-query because the inner query (the subquery) uses a value from the outer query (in this case the Emp1 table) in it’s WHERE clause.
And Source
By the way I am flagging this Question as Duplicate.
I think this uses more native capabilities
//printing the links to a file
$ echo "https://stackoverflow.com/questions/3110444/
https://stackoverflow.com/questions/8445445/
https://stackoverflow.com/questions/4875446/" > links_file.txt
$ xargs curl < links_file.txt
Enjoy!
The detach/copy/attach method will take down the database. That's not something you'd want in production.
The backup/restore will only work if you have write permissions to the production server. I work with Amazon RDS and I don't.
The import/export method doesn't really work because of foreign keys - unless you do tables one by one in the order they reference one another. You can do an import/export to a new database. That will copy all the tables and data, but not the foreign keys.
This sounds like a common operation one needs to do with database. Why isn't SQL Server handling this properly? Every time I had to do this it was frustrating.
That being said, the only painless solution I've encountered was Sql Azure Migration Tool which is maintained by the community. It works with SQL Server too.
Add this code somewhere, this will do the trick.
var originalVal = $.fn.val;
$.fn.val = function(){
var result =originalVal.apply(this,arguments);
if(arguments.length>0)
$(this).change(); // OR with custom event $(this).trigger('value-changed');
return result;
};
Found this solution at val() doesn't trigger change() in jQuery
To add some text, what I did some time ago , if the link you are sharing its a page you can modify. You can add some meta-tags to the shared page:
<meta name="title" content="The title you want" />
<meta name="description" content="The text you want to insert " />
<link rel="image_src" href="A thumbnail you can show" / >
It's a small hack. Although the old share button has been replaced by the "like"/"recommend" button where you can add a comment if you use the XFBML version. More info her:
I was stuck with ast.literal_eval()
. I was trying it in IntelliJ IDEA debugger, and it kept returning None
on debugger output.
But later when I assigned its output to a variable and printed it in code. It worked fine. Sharing code example:
import ast
sample_string = '[{"id":"XYZ_GTTC_TYR", "name":"Suction"}]'
output_value = ast.literal_eval(sample_string)
print(output_value)
Its python version 3.6.
I need to save the phone's timezone in the format [+/-]hh:mm
No, you don't. Offset on its own is not enough, you need to store the whole time zone name/id. For example I live in Oslo where my current offset is +02:00 but in winter (due to dst) it is +01:00. The exact switch between standard and summer time depends on factors you don't want to explore.
So instead of storing + 02:00
(or should it be + 01:00
?) I store "Europe/Oslo"
in my database. Now I can restore full configuration using:
TimeZone tz = TimeZone.getTimeZone("Europe/Oslo")
Want to know what is my time zone offset today?
tz.getOffset(new Date().getTime()) / 1000 / 60 //yields +120 minutes
However the same in December:
Calendar christmas = new GregorianCalendar(2012, DECEMBER, 25);
tz.getOffset(christmas.getTimeInMillis()) / 1000 / 60 //yields +60 minutes
Enough to say: store time zone name or id and every time you want to display a date, check what is the current offset (today) rather than storing fixed value. You can use TimeZone.getAvailableIDs()
to enumerate all supported timezone IDs.
In onResume() change this line
items = dbHelper.getItems(); //reload the items from database
to
items.addAll(dbHelper.getItems()); //reload the items from database
The problem is that you're never telling your adapter about the new items list. If you don't want to pass a new list to your adapter (as it seems you don't), then just use items.addAll
after your clear()
. This will ensure you are modifying the same list that the adapter has a reference to.
I want to add an answer here that noone has explicitly stated with implementation.
This is a great resource to refer to for this failure: https://matplotlib.org/faq/usage_faq.html
In my case, using matplotlib.use
did not work because it was somehow already set somewhere else. However, I was able to get beyond the error by defining an environment variable:
export MPLBACKEND=Agg
This takes care of the issue.
My error was in a CircleCI flow specifically, and this resolved the failing tests. One wierd thing was, my tests would pass when run using pytest
, however would fail when using parallelism
along with circleci tests split
feature. However, declaring this env variable resolved the issue.
No there isn't. Instead use a while
loop such as:
while 1:
...statements...
if cond:
break
Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.
def format_string(str, min_length):
while len(str) < min_length:
str += " "
return str
Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.
I also found that I didn't need the JavaScript.
I added the following class to my Models folder:
public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
private String PropertyName { get; set; }
private Object InvalidValue { get; set; }
private readonly RequiredAttribute _innerAttribute;
public RequiredIfNotAttribute(String propertyName, Object invalidValue)
{
PropertyName = propertyName;
InvalidValue = invalidValue;
_innerAttribute = new RequiredAttribute();
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);
if (dependentValue.ToString() != InvalidValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredifnot",
};
rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;
yield return rule;
}
I didn't need to make any changes to my view, but did make a change to the properties of my model:
[RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
public string TemplateGTSource { get; set; }
public string TemplateGTMedium
{
get
{
return "Email";
}
}
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
public string TemplateGTCampaign { get; set; }
[RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
public string TemplateGTTerm { get; set; }
Hope this helps!
In my case (.NET Core 3.0) I had to configure JSON serialization to resolve camelCase properties using AddNewtonsoftJson():
services.AddMvc(options =>
{
// (Irrelevant for the answer)
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Do this in your Startup / Dependency Injection setup.
In angular 7 got this fixed by adding these lines to .module.ts
file:
import { CommonModule } from '@angular/common';
imports: [CommonModule]
To be able to use it like that, you need to return this
. Without the return, fadeOut('slow'), will not get an object to perform that operation on.
I.e.:
$.fn.idle = function(time)
{
var o = $(this);
o.queue(function()
{
setTimeout(function()
{
o.dequeue();
}, time);
});
return this; //****
}
Then do this:
$('.notice').fadeIn().idle(2000).fadeOut('slow');
It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.
This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.
Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.
Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.
; ' Infinite loop. End the macro by closing the program from the Windows taskbar.
Loop {
; ' Wait for ANY "Save As" dialogue box in any program.
; ' BE CAREFUL!
; ' Ignore the "Confirm Save As" dialogue if attempt is made
; ' to overwrite an existing file.
WinWait, Save As,,, Confirm Save As
IfWinNotActive, Save As,,, Confirm Save As
WinActivate, Save As,,, Confirm Save As
WinWaitActive, Save As,,, Confirm Save As
sleep, 250 ; ' 0.25 second delay
Send, {ENTER} ; ' Save the Excel file.
; ' Wait for the "Save As" dialogue box to close.
WinWaitClose, Save As,,, Confirm Save As
}
What OS you are using and which Webserver? On Linux and Apache you can find the apache error_log in /var/log/apache2/
If you're using zsh and it has not been set up to read .bashrc, you need to add the Miniconda directory to the zsh shell PATH environment variable. Add this to your .zshrc
:
export PATH="/home/username/miniconda/bin:$PATH"
Make sure to replace /home/username/miniconda
with your actual path.
Save, exit the terminal and then reopen the terminal. conda
command should work.
You could process the file while being read by using streams. It's just like using buffers but with a more convenient API.
var fs = require('fs');
function searchReplaceFile(regexpFind, replace, cssFileName) {
var file = fs.createReadStream(cssFileName, 'utf8');
var newCss = '';
file.on('data', function (chunk) {
newCss += chunk.toString().replace(regexpFind, replace);
});
file.on('end', function () {
fs.writeFile(cssFileName, newCss, function(err) {
if (err) {
return console.log(err);
} else {
console.log('Updated!');
}
});
});
searchReplaceFile(/foo/g, 'bar', 'file.txt');
I had a similar question: In the manual, it describes rename as
rename [option] expression replacement file
so you can use it in this way
rename _h _half *.png
In the code: '_h' is the expression that you are looking for. '_half' is the pattern that you want to replace with. '*.png' is the range of files that you are looking for your possible target files.
Hope this can help c:
<?php
list($width, $height) = getimagesize("http://site.com/image.png");
$arr = array('h' => $height, 'w' => $width );
?>
This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.
(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)
$(function() {
// Get all textareas that have a "maxlength" property.
$("textarea[maxlength]").each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field
var maxlength = $textarea.attr("maxlength");
// Add a DIV to display remaining characters to user
$textarea.after($("<div>").addClass("charsRemaining"));
// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
$textarea.on("keyup blur", function(event) {
// Fix OS-specific line-returns to do an accurate count
var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
$textarea.val(val);
// Display updated count to user
$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
}).trigger("blur");
});
});
Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.
Define the float property of the check element to none:
float: none;
And center the parent element:
text-align: center;
It was the only that works for me.
When you try to connect your remote server with ssh:
$ ssh username@ip_address
then the error raise, to solve it:
$ ssh-keygen -f "/home/local_username/.ssh/known_hosts" -R "ip_address"
Java 1.7 makes our lives much easier thanks to the try-with-resources statement.
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement.executeQuery("some query")) {
// Do stuff with the result set.
}
try (ResultSet resultSet = statement.executeQuery("some query")) {
// Do more stuff with the second result set.
}
}
This syntax is quite brief and elegant. And connection
will indeed be closed even when the statement
couldn't be created.
You can also find the use of lambda expressions in writing generic codes to act on your methods.
For example: Generic function to calculate the time taken by a method call. (i.e. Action
in here)
public static long Measure(Action action)
{
Stopwatch sw = new Stopwatch();
sw.Start();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
And you can call the above method using the lambda expression as follows,
var timeTaken = Measure(() => yourMethod(param));
Expression allows you to get return value from your method and out param as well
var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));
Calling .isoformat()
on a date
object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
In Rails 4, this is a better (DRYer) solution:
change_column_null :my_models, :date_column, false
To ensure no records exist with NULL
values in that column, you can pass a fourth parameter, which is the default value to use for records with NULL
values:
change_column_null :my_models, :date_column, false, Time.now
Follow XDG Base Directory Specification usually ~/.config/yourapp/*
can be INF, JSON, YML or whatever format floats your boat, and whatever files... yourapp
should match your executable name, or be namespaced with your organization/company/username/handle to ~/.config/yourorg/yourapp/*
Per-user configuration, usually right in your home directory...
~/.yourapp
file for a single file~/.yourapp/
for multiple files + data usually in ~/.yourapp/configGlobal configurations are generally in /etc/appname
file or /etc/appname/
directory.
Global App data: /var/lib/yourapp/
Cache data: /var/cache/
Log data: /var/log/yourapp/
Some additional info from tutorialhelpdesk.com
The directory structure of Linux/other Unix-like systems and directory details.
In Windows, almost all programs install their files (all files) in the directory named: 'Program Files' Such is not the case in Linux. The directory system categorizes all installed files. All configuration files are in /etc
, all binary files are in /bin
or /usr/bin
or /usr/local/bin
. Here is the entire directory structure along with what they contain:
/
- Root directory that forms the base of the file system. All files and directories are logically contained inside the root directory regardless of their physical locations.
/bin
- Contains the executable programs that are part of the Linux operating system. Many Linux commands, such as cat, cp, ls, more, and tar, are locate in /bin
/boot
- Contains the Linux kernel and other files needed by LILO and GRUB boot managers.
/dev
- Contains all device files. Linux treats each device as a special file. All such files are located in /dev
.
/etc
- Contains most system configuration files and the initialisation scripts in /etc/rc.d
subdirectory.
/home
- Home directory is the parent to the home directories of users.
/lib
- Contains library files, including loadable driver modules needed to boot the system.
/lost+found
- Directory for lost files. Every disk partition has a lost+found directory.
/media
- Directory for mounting files systems on removable media like CD-ROM drives, floppy disks, and Zip drives.
/mnt
- A directory for temporarily mounted filesystems.
/opt
- Optional software packages copy/install files here.
/proc
- A special directory in a virtual filesystem. It contains the information about various aspects of a Linux system.
/root
- Home directory of the root user.
/sbin
- Contains administrative binary files. Commands such as mount, shutdown, umount, reside here.
/srv
- Contains data for services (HTTP, FTP, etc.) offered by the system.
/sys
- A special directory that contains information about the devices, as seen by the Linux kernel.
/tmp
- Temporary directory which can be used as a scratch directory (storage for temporary files). The contents of this directory are cleared each time the system boots.
/usr
- Contains subdirectories for many programs such as the X Window System.
/usr/bin
- Contains executable files for many Linux commands. It is not part of the core Linux operating system.
/usr/include
- Contains header files for C and C++ programming languages
/usr/lib
- Contains libraries for C and C++ programming languages.
/usr/local
- Contains local files. It has a similar directories as /usr contains.
/usr/sbin
- Contains administrative commands.
/usr/share
- Contains files that are shared, like, default configuration files, images, documentation, etc.
/usr/src
- Contains the source code for the Linux kernel.
/var
- Contains various system files such as log, mail directories, print spool, etc. which tend to change in numbers and size over time.
/var/cache
- Storage area for cached data for applications.
/var/lib
- Contains information relating to the current state of applications. Programs modify this when they run.
/var/lock
- Contains lock files which are checked by applications so that a resource can be used by one application only.
/var/log
- Contains log files for different applications.
/var/mail
- Contains users' emails.
/var/opt
- Contains variable data for packages stored in /opt directory.
/var/run
- Contains data describing the system since it was booted.
/var/spool
- Contains data that is waiting for some kind of processing.
/var/tmp
- Contains temporary files preserved between system reboots.
I had the same problem and I've found the cause.
I have avast! antivirus installed in my computer, and it asked me to install the update for chrome plugin. The new avast! plugin for chrome
has the functionality to block ads and tracking, and, by default, it blocks the facebook access. I have solved my problem simply allowing facebook in the avast! chrome plugin for the website I needed.
Since this question is very old, I think that some people might have the same cause as me, the new avast! chrome plugin.
On OSX, saving video frames and still images only worked for me when I gave a full path to cvSaveImage:
cvSaveImage("/Users/nicc/image.jpg",img);
I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?
Consider this code:
SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end
How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.
This is the code that brought me here:
where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)
I just need to compare if two fields (in where) have different values, I could use function, but...
Inspiring from @braitsch I have used the following in my AngularJS2 input-file-component
<input id="file" onclick="onClick($event) onchange="onChange($event)" type="file" accept="*/*" />
export class InputFile {
@Input()
file:File|Blob;
@Output()
fileChange = new EventEmitter();
onClick(event) {
event.target.value=''
}
onChange(e){
let files = e.target.files;
if(files.length){
this.file = files[0];
}
else { this.file = null}
this.fileChange.emit(this.file);
}
}
Here the onClick(event)
rescued me :-)
I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
Use following html
<link rel="stylesheet" href="app/components/directives/navBar/navBar.scss"/>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav">
<li><h5><a href="#/">Home</a></h5></li>
<li>|</li>
<li><h5><a href="#products">About</a></h5></li>
<li>|</li>
<li><h5><a href="#">Contacts</a></h5></li>
<li>|</li>
<li><h5><a href="#cart">Cart</a></h5></li>
</ul>
</div><!-- /.container-fluid -->
</nav>
And css
.navbar-nav {
width: 100%;
text-align: center;
}
.navbar-nav > li {
float: none;
display: inline-block;
}
.navbar-default {
background-color: white;
border-color: white;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus{
background-color:white;
}
Modify according to your needs
you could write
select DISTINCT f from t;
as
select f from t group by f;
thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING
after group by.
The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.
Maintainability-wise, it's always smarter to use the second form.
EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html
This seems to be added recently:
https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/3.0.1/
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Try this:
List<Double> l1= new ArrayList<Double>();
l1.add(1.38);
l1.add(2.56);
l1.add(4.3);
When you have more complex structures, you might need to convert to JSON before printing:
// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)
Heres another way of working this out from using the bash command line.
for i in
mysql -NB -e 'show databases'
; do echo $i; mysql -e "SELECT table_name AS 'Tables', round(((data_length+index_length)/1024/1024),2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema =\"$i\" ORDER BY (data_length + index_length) DESC" ; done
list2 = ['%sbar' % (x,) for x in list]
And don't use list
as a name; it shadows the built-in type.
Depending on the number of endpoints you need it may be easier to do it manually.
I have tried 10 libraries "soap nodejs" I finally do it manually.
I rewrote David's answer using the with
statement, it allows you do do this:
with timeout(seconds=3):
time.sleep(4)
Which will raise a TimeoutError.
The code is still using signal
and thus UNIX only:
import signal
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
Assuming state
is having a valid boolean value set in your actual code, then the following condition will succeed
if(state)
when state is boolean value is TRUE
If condition checks for the expression whether it is evaluated to TRUE/FALSE. If the expression is simple true
then the condition will succeed.
Visiting this thread after some period of inactivity, but given that I don't see a thorough answer, here's my two cents.
Breadth-first search will always find the shortest path in an unweighted graph. The graph may be cyclic or acyclic.
See below for pseudocode. This pseudocode assumes that you are using a queue to implement BFS. It also assumes you can mark vertices as visited, and that each vertex stores a distance parameter, which is initialized as infinity.
mark all vertices as unvisited
set the distance value of all vertices to infinity
set the distance value of the start vertex to 0
if the start vertex is the end vertex, return 0
push the start vertex on the queue
while(queue is not empty)
dequeue one vertex (we’ll call it x) off of the queue
if x is not marked as visited:
mark it as visited
for all of the unmarked children of x:
set their distance values to be the distance of x + 1
if the value of x is the value of the end vertex:
return the distance of x
otherwise enqueue it to the queue
if here: there is no path connecting the vertices
Note that this approach doesn't work for weighted graphs - for that, see Dijkstra's algorithm.
I tried this and it works perfectly
@Entity
public class Shipwreck {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
@Basic(optional = false)
@SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
Long id;
....
CREATE SEQUENCE public.shipwreck_seq
INCREMENT 1
START 110
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
How about typing document.cookie into the console? It just shows the values, but it's something.
char* data;
stringstream myStreamString;
myStreamString << data;
string myString = myStreamString.str();
cout << myString << endl;
You can check if the row exists, and then INSERT or UPDATE, but this guarantees you will be performing two SQL operations instead of one:
A better solution is to always UPDATE first, and if no rows were updated, then do an INSERT, like so:
update table1
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
if @@ROWCOUNT = 0
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')
This will either take one SQL operations, or two SQL operations, depending on whether the row already exists.
But if performance is really an issue, then you need to figure out if the operations are more likely to be INSERT's or UPDATE's. If UPDATE's are more common, do the above. If INSERT's are more common, you can do that in reverse, but you have to add error handling.
BEGIN TRY
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')
END TRY
BEGIN CATCH
update table1
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
END CATCH
To be really certain if you need to do an UPDATE or INSERT, you have to do two operations within a single TRANSACTION. Theoretically, right after the first UPDATE or INSERT (or even the EXISTS check), but before the next INSERT/UPDATE statement, the database could have changed, causing the second statement to fail anyway. This is exceedingly rare, and the overhead for transactions may not be worth it.
Alternately, you can use a single SQL operation called MERGE to perform either an INSERT or an UPDATE, but that's also probably overkill for this one-row operation.
Consider reading about SQL transaction statements, race conditions, SQL MERGE statement.
SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
MAX([Value])
FOR [Period] IN ([2000], [2001], [2002])
) as pvt
Another way,
SELECT ACCOUNT,
MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account
Explicitly creating an out
folder and then setting the output path to C:\Users\USERNAME\IdeaProjects\PROJECTNAME\out
seemed to work for me when just out
, and expecting IntelliJ to make the folder wouldn't.
Also try having IntelliJ make you a new run configuration:
Find the previous one by clicking
then remove it
and hit okay.
Now, (IMPORTANT STEP) open the class containing your main method. This is probably easiest done by clicking on the class name in the left-hand side Project Pane.
Give 'er a Alt + Shift + F10 and you should get a
Now hit Enter!!
Tadah?? (Did it work?)
Yet another multi-functional CSV (and not only) manipulation tool: Miller. From its own description, it is like awk, sed, cut, join, and sort for name-indexed data such as CSV, TSV, and tabular JSON. (link to github repository: https://github.com/johnkerl/miller)
You can use match()
as well:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
But test()
seems to be faster as you can read here.
Important difference between match()
and test()
:
match()
works only with strings, but test()
works also with integers.
12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345); // true
/^([a-z0-9]{5,})$/.test(null); // false
// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true
It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.
If you're here in 2020 and you think the device receiving the error message should be compatible:
Several other major apps have run into this including Instagram (1B+ installs) and Clash of Clans (100M+ installs). It appears to be an issue with Google's Android operating system.
To fix the “your device is not compatible with this version” error message, try clearing the Google Play Store cache, and then data. Next, restart the Google Play Store and try installing the app again.
Here is a link to Google's official support page that you can link to your users on how to clear the cache: https://support.google.com/googleplay/answer/7513003
I found SimulatorManager application very useful. It takes you directly to the application folder of installed simulators. I have tried with 7.1, 8.0 and 8.1 simulators.
SimulatorManager resides as an icon in the system tray and provides an option to "Launch At Login".
Note: This works only with Xcode 6 (6.1.1 in my case) and above.
Hope that helps!
You could set your SVG as a mask. That way setting a background-color would act as your fill color.
HTML
<div class="logo"></div>
CSS
.logo {
background-color: red;
-webkit-mask: url(logo.svg) no-repeat center;
mask: url(logo.svg) no-repeat center;
}
JSFiddle: https://jsfiddle.net/KuhlTime/2j8exgcb/
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/mask
Please check whether your browser supports this feature: https://caniuse.com/#search=mask
Suppose you have this nested Style dictionary. LightGreen is at the root level while Pink is nested inside a Grid.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type Grid}">
<Style.Resources>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="Pink"/>
</Style>
</Style.Resources>
</Style>
<Style TargetType="{x:Type Button}" x:Key="ConflictButton">
<Setter Property="Background" Value="LightGreen"/>
</Style>
</ResourceDictionary>
In view:
<Window x:Class="WpfStyleDemo.ConflictingStyleWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ConflictingStyleWindow" Height="100" Width="100">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/ConflictingStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Button Style="{DynamicResource ConflictButton}" Content="Test"/>
</Grid>
</Window>
StaticResource will render the button as LightGreen, the first value it found in the style. DynamicResource will override the LightGreen button as Pink as it renders the Grid.
StaticResource
DynamicResource
Keep in mind that VS Designer treats DynamicResource as StaticResource. It will get first value. In this case, VS Designer will render the button as LightGreen although it actually ends up as Pink.
StaticResource will throw an error when the root-level style (LightGreen) is removed.
This should do the trick for you.
For one word:
if (!string.Contains("One"))
For two words:
if (!(string.Contains("One") && string.Contains("Two")))
You can print the request type using:
request.getMethod();
You can print all the headers as mentioned here:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
To print all the request params, use this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
request
is the instance of HttpServletRequest
You can beautify the outputs as you desire.
Use the android.webkit.URLUtil
on android:
URLUtil.isValidUrl(URL_STRING);
Note: It is just checking the initial scheme of URL, not that the entire URL is valid.
I found myself in a similar predicament today while trying to run a command through a Node.js module:
I was using the PowerShell and trying to run:
command -e 'func($a)'
But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:
command -e `"func($a)`"
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
The purpose of BASE64 encoding is to take binary data and be able to persist that to a string. That benefit comes at a cost, an increase in the size of the result (I think it's a 4 to 3 ratio). There are two solutions. If you know the data will be well formed XML, include it directly. The other, an better option, is to include the HTML in a CDATA section within an element within the XML.
My Solution - Java - Without duplicates
public static void printAllPairSum(int[] a, int x){
System.out.printf("printAllPairSum(%s,%d)\n", Arrays.toString(a),x);
if(a==null||a.length==0){
return;
}
int length = a.length;
Map<Integer,Integer> reverseMapOfArray = new HashMap<>(length,1.0f);
for (int i = 0; i < length; i++) {
reverseMapOfArray.put(a[i], i);
}
for (int i = 0; i < length; i++) {
Integer j = reverseMapOfArray.get(x - a[i]);
if(j!=null && i<j){
System.out.printf("a[%d] + a[%d] = %d + %d = %d\n",i,j,a[i],a[j],x);
}
}
System.out.println("------------------------------");
}
You could use .find("is")
, it would return position of "is" in the string
or use .start() from re
>>> re.search("is", String).start()
2
Actually its match "is" from "This"
If you need to match per word, you should use \b
before and after "is", \b
is the word boundary.
>>> re.search(r"\bis\b", String).start()
5
>>>
for more info about python regular expressions, docs here
this works for me.
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
Redirect "https://www.example.com/" "http://www.example.com/"
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# ...
</VirtualHost>
be sure to listen to both ports 80 and 443.
First, ensure MySQL is running. Command: mysqld start
If you still cannot connect then: What does your /etc/my.cnf look like? (or /etc/msyql/my.cnf)
The other 2 posts are correct in that you need to check your socket because 2002 is a socket error.
A great tutorial on setting up LAMP is: http://library.linode.com/lamp-guides/centos-5.3/index-print
I found a way for this on the net
It demands a little bit of work, because it has to be done table by table. But anyway, I could copy the tables, data and constraints into a MS SQL database.
Here is the link
http://www.codeproject.com/KB/database/migrate-mysql-to-mssql.aspx
When I'm teaching someone programming (just about any language) I introduce for
loops with terminology similar to this code example:
for eachItem in someList:
doSomething(eachItem)
... which, conveniently enough, is syntactically valid Python code.
The Python range()
function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).
So range(5)
returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).
A call to range(2,10)
would return: 2, 3, 4, 5, 6, 7, 8, 9
A call to range(2,12,3)
would return: 2, 5, 8, 11
Notice that I said, a couple times, that Python's range()
function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range()
built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break
" out of the loop early (after finding some particular item in which you were interested, for example).
Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.
The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."
Other constructs in the language (such as those underlying the for
loop) can then work with that object (iterate through it) as though it were a list.
For most cases you don't have to know whether your version of Python is using the old implementation of range()
or the newer one based on generators. You can just use it and be happy.
If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range()
on an old version of Python. In such cases you could re-think your design and use while
loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange()
version of range()
if your version of Python includes it, or the range()
function from a version of Python that uses the generators implicitly.
Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).
[Update: for Python3 (the currently maintained versions of Python) the range()
function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].
String Constants
Just use the +
operator and break the string up into human-readable lines. The compiler will pick up that the strings are constant and concatenate them at compile time. See the MSDN C# Programming Guide here.
e.g.
const string myVeryLongString =
"This is the opening paragraph of my long string. " +
"Which is split over multiple lines to improve code readability, " +
"but is in fact, just one long string.";
IL_0003: ldstr "This is the opening paragraph of my long string. Which is split over multiple lines to improve code readability, but is in fact, just one long string."
String Variables
Note that when using string interpolation to substitute values into your string, that the $
character needs to precede each line where a substitution needs to be made:
var interpolatedString =
"This line has no substitutions. " +
$" This line uses {count} widgets, and " +
$" {CountFoos()} foos were found.";
However, this has the negative performance consequence of multiple calls to string.Format
and eventual concatenation of the strings (marked with ***
)
IL_002E: ldstr "This line has no substitutions. "
IL_0033: ldstr " This line uses {0} widgets, and "
IL_0038: ldloc.0 // count
IL_0039: box System.Int32
IL_003E: call System.String.Format ***
IL_0043: ldstr " {0} foos were found."
IL_0048: ldloc.1 // CountFoos
IL_0049: callvirt System.Func<System.Int32>.Invoke
IL_004E: box System.Int32
IL_0053: call System.String.Format ***
IL_0058: call System.String.Concat ***
Although you could either use $@
to provide a single string and avoid the performance issues, unless the whitespace is placed inside {}
(which looks odd, IMO), this has the same issue as Neil Knight's answer, as it will include any whitespace in the line breakdowns:
var interpolatedString = $@"When breaking up strings with `@` it introduces
<- [newLine and whitespace here!] each time I break the string.
<- [More whitespace] {CountFoos()} foos were found.";
The injected whitespace is easy to spot:
IL_002E: ldstr "When breaking up strings with `@` it introduces
<- [newLine and whitespace here!] each time I break the string.
<- [More whitespace] {0} foos were found."
An alternative is to revert to string.Format
. Here, the formatting string is a single constant as per my initial answer:
const string longFormatString =
"This is the opening paragraph of my long string with {0} chars. " +
"Which is split over multiple lines to improve code readability, " +
"but is in fact, just one long string with {1} widgets.";
And then evaluated as such:
string.Format(longFormatString, longFormatString.Length, CountWidgets());
However this can still be tricky to maintain given the potential separation between the formatting string and the substitution tokens.
It is worth noting that
In AngularJS, we update our models, and our views/templates update the DOM "automatically" (via built-in or custom directives).
$apply and $watch, both being Scope methods, are not related to the DOM.
The Concepts page (section "Runtime") has a pretty good explanation of the $digest loop, $apply, the $evalAsync queue and the $watch list. Here's the picture that accompanies the text:
Whatever code has access to a scope – normally controllers and directives (their link functions and/or their controllers) – can set up a "watchExpression" that AngularJS will evaluate against that scope. This evaluation happens whenever AngularJS enters its $digest loop (in particular, the "$watch list" loop). You can watch individual scope properties, you can define a function to watch two properties together, you can watch the length of an array, etc.
When things happen "inside AngularJS" – e.g., you type into a textbox that has AngularJS two-way databinding enabled (i.e., uses ng-model), an $http callback fires, etc. – $apply has already been called, so we're inside the "AngularJS" rectangle in the figure above. All watchExpressions will be evaluated (possibly more than once – until no further changes are detected).
When things happen "outside AngularJS" – e.g., you used bind() in a directive and then that event fires, resulting in your callback being called, or some jQuery registered callback fires – we're still in the "Native" rectangle. If the callback code modifies anything that any $watch is watching, call $apply to get into the AngularJS rectangle, causing the $digest loop to run, and hence AngularJS will notice the change and do its magic.
I have looked at the above answers and have mixed together this version which works for me:
function getFilesFromPath(path, extension) {
let files = fs.readdirSync( path );
return files.filter( file => file.match(new RegExp(`.*\.(${extension})`, 'ig')));
}
console.log(getFilesFromPath("./testdata", ".txt"));
This test will return an array of filenames from the files found in the folder at the path ./testdata
. Working on node version 8.11.3.
Your Application.java
class should extend the SpringBootServletInitializer
class
ex:
public class Application extends SpringBootServletInitializer {}
You can make use of apache's commons lang DateUtils helper utility class.
Date newDate = DateUtils.addMonths(new Date(), 1);
You can download commons lang jar at http://commons.apache.org/proper/commons-lang/
The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:
<img src="..." onload="this.width/=2;this.onload=null;" />
The reason for the this.onload=null
addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:
<img src="..." onload="this.width/=2;" />
Which is quite succinct.
One way is to convert your array to an object and use it in scope (simulation of an array). This way has the benefit of maintaining the template.
$scope.telephone = {};
for (var i = 0, l = $scope.phones.length; i < l; i++) {
$scope.telephone[i.toString()] = $scope.phone[i];
}
<input type="text" ng-model="telephone[0.toString()]" />
<input type="text" ng-model="telephone[1.toString()]" />
and on save, change it back.
$scope.phones = [];
for (var i in $scope.telephone) {
$scope.phones[parseInt(i)] = $scope.telephone[i];
}
for .sql files Ctrl+K or Ctrl+Q does not work.
to insert comments in .sql files in Notepad++ try Ctrl+Shift+Q
(there is no shortcut to uncomment the code block though. I have tried that on v5.8.2 )
i've written a function that extract numbers from string:
int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
// get startIndex
int startIndex = src.Find(str) + CString(str).GetLength();
// cut the string
CString toreturn = src.Mid(startIndex, length);
// convert to number
return _wtoi(toreturn); // atoi(toreturn)
}
Usage:
CString str = _T("digit:1, number:102");
int digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);
AffineTransform
instances can be concatenated (added together). Therefore you can have a transform that combines 'shift to origin', 'rotate' and 'shift back to desired position'.
Yes, first set a datetime to the start of the current month.
Second test if current date day > 25 and get a true/false on that. If True then add add one month to the start of month datetime object. If false then use the datetime object with the value set to the beginning of the month.
import datetime
from dateutil.relativedelta import relativedelta
todayDate = datetime.date.today()
resultDate = todayDate.replace(day=1)
if ((todayDate - resultDate).days > 25):
resultDate = resultDate + relativedelta(months=1)
print resultDate
obj
is an array in your example.
fs.writeFileSync(filename, data, [options]) requires either String
or Buffer
in the data parameter. see docs.
Try to write the array in a string format:
// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8');
Or:
// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');
edit: The reason you see the array in your example is because node's implementation of console.log
doesn't just call toString
, it calls util.format
see console.js source
if you just want to hold the screen so you can see the result on the terminal just write
input()
at the end of the code and it will hold the screen
There is indeed a Groovier Way.
if(members){
//Some work
}
does everything if members
is a collection. Null check as well as empty check (Empty collections are coerced to false
). Hail Groovy Truth. :)
2 ways to do it
insert tbl (other, col1, intcol) values ('abc', 123, NULL)
or just omit it from the column list
insert tbl (other, col1) values ('abc', 123)
Security concern using express.bodyParser()
While all the other answers currently recommend using the express.bodyParser()
middleware, this is actually a wrapper around the express.json()
, express.urlencoded()
, and express.multipart()
middlewares (http://expressjs.com/api.html#bodyParser). The parsing of form request bodies is done by the express.urlencoded()
middleware and is all that you need to expose your form data on req.body
object.
Due to a security concern with how express.multipart()
/connect.multipart()
creates temporary files for all uploaded files (and are not garbage collected), it is now recommended not to use the express.bodyParser()
wrapper but instead use only the middlewares you need.
Note: connect.bodyParser()
will soon be updated to only include urlencoded
and json
when Connect 3.0 is released (which Express extends).
So in short, instead of ...
app.use(express.bodyParser());
...you should use
app.use(express.urlencoded());
app.use(express.json()); // if needed
and if/when you need to handle multipart forms (file uploads), use a third party library or middleware such as multiparty, busboy, dicer, etc.
Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.
Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website
Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)
@hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.
@hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html
Getting 7.5 MySQL Connector/C++ Complete Example 1 to work
Downloads:
-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.
-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector
Now proceed:
-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt
-Extract the boost library to your c drive
Next:
It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:
-First: change
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
to
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
Not sure what that tiny double arrow is for, but I don't think it is part of c++
-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below
[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.
Just follow that chapter 5,
-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder
-While doing the above, also include your boost folder see note 2 below
-And for the Linker, General.. etc use the opt folder from connector/lib/opt
*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp, this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include
Next:
What is next I think is the Static Build, well it is what I did anyways. Follow it.
Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).
if you are using extracted tomcat then,
startup.sh
and shutdown.sh
are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that
if tomcat is installed then
/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart
I find:
ps -ax | grep mongo
To be a lot more consistent. The value returned can be used to detect how many instances of mongod there are running
See sys.path As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.
Use this path as the root folder from which you apply your relative path
>>> import sys
>>> import os.path
>>> sys.path[0]
'C:\\Python25\\Lib\\idlelib'
>>> os.path.relpath(sys.path[0], "path_to_libs") # if you have python 2.6
>>> os.path.join(sys.path[0], "path_to_libs")
'C:\\Python25\\Lib\\idlelib\\path_to_libs'
For a reusable React hook solution
import React, { useEffect } from 'react';
const useEscape = (onEscape) => {
useEffect(() => {
const handleEsc = (event) => {
if (event.keyCode === 27)
onEscape();
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, []);
}
export default useEscape
Usage:
const [isOpen, setIsOpen] = useState(false);
useEscape(() => setIsOpen(false))
"Resetting" styles for a specific element isn't possible, you'll have to overwrite all styles you don't want/need. If you do this with CSS directly or using JQuery to apply the styles (depends on what's easier for you, but I wouldn't recommend using JavaScript/JQuery for this, as it's completely unnecessary).
If your div is some kind of "widget" that can be included into other sites, you could try to wrap it into an iframe. This will "reset" the styles, because its content is another document, but maybe this affects how your widget works (or maybe breaks it completely) so this might not be possible in your case.
In App.config:
<add key="YOURKEY" value="a,b,c"/>
In C#:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
savez() save data in a zip file, It may take some time to zip & unzip the file. You can use save() & load() function:
f = file("tmp.bin","wb")
np.save(f,a)
np.save(f,b)
np.save(f,c)
f.close()
f = file("tmp.bin","rb")
aa = np.load(f)
bb = np.load(f)
cc = np.load(f)
f.close()
To save multiple arrays in one file, you just need to open the file first, and then save or load the arrays in sequence.
Since PHP >= 5.2.2 you can use the DateTime
class as such:
if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00
# in other words, 2010-05-15 16:00:00 has passed
}
The string passed to the DateTime constructor is parsed according to these rules.
Note that it is also possible to use time
and strtotime
functions. See original answer.
This should work.
var url = 'http://<your_url_here>';
var headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
'Content-Type' : 'application/x-www-form-urlencoded'
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};
request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
// your callback body
});
I'll throw my answer into the ring as well. If you want to do this programmatically you can do the following.
final Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.somedrawable);
final boolean isLTR = ViewCompat.LAYOUT_DIRECTION_LTR == ViewCompat.getLayoutDirection(this);
final int iconInsetPadding = getResources().getDimensionPixelSize(R.dimen.icon_padding);
final Drawable insetDrawable = new InsetDrawable(drawable, isLTR ? 0 : iconInsetPadding, 0, isLTR ? iconInsetPadding : 0, 0);
This will add the padding to the end of the drawable where end will mean left/right depending if phone is in LTR or RTL.
If you want information about all exceptions then use exception.ToString()
. It will collect data from all inner exceptions.
If you want only the original exception then use exception.GetBaseException().ToString()
. This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.
Example:
try {
Exception ex1 = new Exception( "Original" );
Exception ex2 = new Exception( "Second", ex1 );
Exception ex3 = new Exception( "Third", ex2 );
throw ex3;
} catch( Exception ex ) {
// ex => ex3
Exception baseEx = ex.GetBaseException(); // => ex1
}
Here's an excellent article by Scott Allen: Developing Gadgets for the Windows Sidebar
This site, Windows 7/Vista Sidebar Gadgets, has links to many gadget resources.
Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.
You can't do window.history.back(); and location.reload(); in the same function.
window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.
location.reload() has to be called on the page you redirect to when using window.history.back().
I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.
There's no way to specify a StringComparer
at the point where you try to get a value. If you think about it, "foo".GetHashCode()
and "FOO".GetHashCode()
are totally different so there's no reasonable way you could implement a case-insensitive get on a case-sensitive hash map.
You can, however, create a case-insensitive dictionary in the first place using:-
var comparer = StringComparer.OrdinalIgnoreCase;
var caseInsensitiveDictionary = new Dictionary<string, int>(comparer);
Or create a new case-insensitive dictionary with the contents of an existing case-sensitive dictionary (if you're sure there are no case collisions):-
var oldDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var newDictionary = new Dictionary<string, int>(oldDictionary, comparer);
This new dictionary then uses the GetHashCode()
implementation on StringComparer.OrdinalIgnoreCase
so comparer.GetHashCode("foo")
and comparer.GetHashcode("FOO")
give you the same value.
Alternately, if there are only a few elements in the dictionary, and/or you only need to lookup once or twice, you can treat the original dictionary as an IEnumerable<KeyValuePair<TKey, TValue>>
and just iterate over it:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
var value = myDictionary.FirstOrDefault(x => String.Equals(x.Key, myKey, comparer)).Value;
Or if you prefer, without the LINQ:-
var myKey = ...;
var myDictionary = ...;
var comparer = StringComparer.OrdinalIgnoreCase;
int? value;
foreach (var element in myDictionary)
{
if (String.Equals(element.Key, myKey, comparer))
{
value = element.Value;
break;
}
}
This saves you the cost of creating a new data structure, but in return the cost of a lookup is O(n) instead of O(1).
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"
solution : first identified all jpg files and then replace keyword
find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \;
Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:
<string name="welcome_messages">Hello, <xliff:g name="name">%s</xliff:g>! You have
<xliff:g name="count">%d</xliff:g> new messages.</string>
2. use string substitution:
c.getString(R.string.welcome_messages,name,count);
where c is the Context, name is a string variable and count your int variable
You'll need to include
<resources xmlns:xliff="http://schemas.android.com/apk/res-auto">
in your res/strings.xml. Works for me. :)
You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:
>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'
This would of course fail if there is multiple numbers in the input. a quick check would be:
assert(age in input_given)
and also:
assert(len(name)<len(input_given))
There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (
.
) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs.+
and.-
are unnecessary.
On unix systems, you can use the following command to determine where git is installed:
whereis git
If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.
For newbies like myself, these resources helped:
Finding the apc.ini file to make the changes recommended by c33s above, and setting recommended amounts: http://www.untwistedvortex.com/optimizing-tuning-apc-alternate-php-cache/
Understanding what apc.ttl is: http://www.php.net/manual/en/apc.configuration.php#ini.apc.ttl
Understanding what apc.shm_size is: http://www.php.net/manual/en/apc.configuration.php#ini.apc.shm-size
Query:
select ord_num, agent_code, ord_date, ord_amount
from orders
where (agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders
GROUP BY agent_code);
above query worked for me in mysql. refer following link -->
https://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php
For people using @akashivskyy's answer to instantiate UIViewController
and are having the exception:
fatal error: use of unimplemented initializer 'init(coder:)' for class
Quick tip:
Manually implement required init?(coder aDecoder: NSCoder)
at your destination UIViewController
that you are trying to instantiate
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
If you need more description please refer to my answer here
MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);
Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:
MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);
In addition to what other have said, you may also be interested to know that what in
does is to call the list.__contains__
method, that you can define on any class you write and can get extremely handy to use python at his full extent.
A dumb use may be:
>>> class ContainsEverything:
def __init__(self):
return None
def __contains__(self, *elem, **k):
return True
>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>
Here is the detailed answer to the question:
Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).
There is more than one way we can pass data into the headers. The syntax is different but all means the same.
// Option 1
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'ID': emp.UserID,
})
};
// Option 2
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');
let options = {headers:httpHeaders};
// Option 1
return this.http.post(this.url + 'testMethod', body,httpOptions)
// Option 2
return this.http.post(this.url + 'testMethod', body,options)
In the call you can find the field passed as a header as shown in the image below :
Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)
Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access
Response for preflight does not have HTTP ok status.
Find my detailed answer at https://stackoverflow.com/a/52620468/3454221
In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.
This compact method return 1 if exist 0 if not exist.
set @ret = 0;
SELECT 1 INTO @ret FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'my_table';
SELECT @ret;
You can put in into a mysql function
DELIMITER $$
CREATE FUNCTION ExistTable (_tableName varchar(255))
RETURNS tinyint(4)
SQL SECURITY INVOKER
BEGIN
DECLARE _ret tinyint;
SET _ret = 0;
SELECT
1 INTO _ret
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = _tablename LIMIT 1;
RETURN _ret;
END
$$
DELIMITER ;
and call it
Select ExistTable('my_table');
return 1 if exist 0 if not exist.
Assuming that you do not have the log file from the expdp job that generated the file in the first place, the easiest option would probably be to use the SQLFILE parameter to have impdp generate a file of DDL (based on a full import). Then you can grab the schema names from that file. Not ideal, of course, since impdp has to read the entire dump file to extract the DDL and then again to get to the schema you're interested in, and you have to do a bit of text file searching for the various CREATE USER statements, but it should be doable.
Unfortunately, no. This feature is not available for facebook albums.
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
Updated the Android SDK platform tools using SDK Manager (in Eclipse). Works for me.
Using html5 doctype at the beginning of the page.
<!DOCTYPE html>
Force IE to use the latest render mode
<meta http-equiv="X-UA-Compatible" content="IE=edge">
If your target browser is ie8, then check your compatible settings in IE8
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
var totally = eval(arr.join('+'))
That way you can put all kinds of exotic things in the array.
var arr = ['(1/3)','Date.now()','foo','bar()',1,2,3,4]
I'm only half joking.
Because Depth-First Searches use a stack as the nodes are processed, backtracking is provided with DFS. Because Breadth-First Searches use a queue, not a stack, to keep track of what nodes are processed, backtracking is not provided with BFS.
Try http://php.net/manual/en/curl.examples-basic.php :)
<?php
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
As the documentation says:
The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().
No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE
permission and just make a connected method
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
You can also use requestRouteToHost
if you have a particualr host and connection type (wifi/mobile) in mind.
You will also need:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your android manifest.
for more detail go here
Do you know the length of your prefix and suffix? In your case:
result=$(echo $string | cut -c5- | rev | cut -c3- | rev)
Or more general:
result=$(echo $string | cut -c$((${#prefix}+1))- | rev | cut -c$((${#suffix}+1))- | rev)
But the solution from Adrian Frühwirth is way cool! I didn't know about that!
You can use ellipsizeMode and numberOfLines. e.g
<Text ellipsizeMode='tail' numberOfLines={2}>
This very long text should be truncated with dots in the beginning.
</Text>
Redux itself is a pretty verbose library, and for such stuff you would have to use something like Redux-thunk, which will give a dispatch
function, so you will be able to dispatch closing of the notification after several seconds.
I have created a library to address issues like verbosity and composability, and your example will look like the following:
import { createTile, createSyncTile } from 'redux-tiles';
import { sleep } from 'delounce';
const notifications = createSyncTile({
type: ['ui', 'notifications'],
fn: ({ params }) => params.data,
// to have only one tile for all notifications
nesting: ({ type }) => [type],
});
const notificationsManager = createTile({
type: ['ui', 'notificationManager'],
fn: ({ params, dispatch, actions }) => {
dispatch(actions.ui.notifications({ type: params.type, data: params.data }));
await sleep(params.timeout || 5000);
dispatch(actions.ui.notifications({ type: params.type, data: null }));
return { closed: true };
},
nesting: ({ type }) => [type],
});
So we compose sync actions for showing notifications inside async action, which can request some info the background, or check later whether the notification was closed manually.
This can also happen in safari if you try a selector with a missing ], for example
$('select[name="something"')
but interestingly, this same jquery selector with a missing bracket will work in chrome.
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.
5 Jan 2021: link update thanks to @Sadap's comment.
Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.
For example, you can see that _WIN32
is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).
Anyway, I found the tables quite informative and thought I'd share here.
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
Transform the sets into arrays, flatten them and finally the constructor will uniqify.
const union = (...sets) => new Set(sets.map(s => [...s]).flat());
Depending on the structure of the string, you can use lstrip
:
str = str.lstrip(':')
But this would remove all colons at the beginning, i.e. if you have ::foo
, the result would be foo
. But this function is helpful if you also have strings that do not start with a colon and you don't want to remove the first character then.
You are confuising two CSS styles, the display style and the visibility style.
If the element is hidden by setting the visibility css style, then you should be able to get the height regardless of whether or not the element is visible or not as the element still takes space on the page.
If the element is hidden by changing the display css style to "none", then the element doesn't take space on the page, and you will have to give it a display style which will cause the element to render in some space, at which point, you can get the height.
Use this in project.gradle:
buildscript {
repositories
{
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
}
}
allprojects {
repositories {
mavenCentral()
}
}
To add items to drop down list with value in asp.net using c# just add below codes for example:
try
{
SqlConnection conn = new SqlConnection(conStr);
SqlCommand comm = conn.CreateCommand();
comm = conn.CreateCommand();
comm.CommandText = "SELECT title,gid from Groups";
comm.CommandType = CommandType.Text;
conn.Open();
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
dropDownList.Items.Add(new
ListItem(dr[0].ToString(),dr[1].ToString()));
}
}
catch (Exception e)
{
lblText.Text = e.Message;
}
finally
{
conn.Close();
}
copy and paste this xml instead of your xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:background="@android:drawable/btn_dropdown"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:background="@android:drawable/btn_dropdown"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:background="@android:drawable/btn_dropdown"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
</RelativeLayout>
I found a new way to do it that is Emit.
We can use Emit to add the IL to app and run it. But I dont think its a good way for I want to perfect this that I write my answer.
The Emit can see the official document and Guide
You should learn some IL to read the code. I will write the code that can copy the property in class.
public static class Clone
{
// ReSharper disable once InconsistentNaming
public static void CloneObjectWithIL<T>(T source, T los)
{
//see http://lindexi.oschina.io/lindexi/post/C-%E4%BD%BF%E7%94%A8Emit%E6%B7%B1%E5%85%8B%E9%9A%86/
if (CachedIl.ContainsKey(typeof(T)))
{
((Action<T, T>) CachedIl[typeof(T)])(source, los);
return;
}
var dynamicMethod = new DynamicMethod("Clone", null, new[] { typeof(T), typeof(T) });
ILGenerator generator = dynamicMethod.GetILGenerator();
foreach (var temp in typeof(T).GetProperties().Where(temp => temp.CanRead && temp.CanWrite))
{
//do not copy static that will except
if (temp.GetAccessors(true)[0].IsStatic)
{
continue;
}
generator.Emit(OpCodes.Ldarg_1);// los
generator.Emit(OpCodes.Ldarg_0);// s
generator.Emit(OpCodes.Callvirt, temp.GetMethod);
generator.Emit(OpCodes.Callvirt, temp.SetMethod);
}
generator.Emit(OpCodes.Ret);
var clone = (Action<T, T>) dynamicMethod.CreateDelegate(typeof(Action<T, T>));
CachedIl[typeof(T)] = clone;
clone(source, los);
}
private static Dictionary<Type, Delegate> CachedIl { set; get; } = new Dictionary<Type, Delegate>();
}
The code can be deep copy but it can copy the property. If you want to make it to deep copy that you can change it for the IL is too hard that I cant do it.
Think in the inverse way: how to make the 2 ranges not overlap? Given [x1, x2]
, then [y1, y2]
should be outside [x1, x2]
, i.e., y1 < y2 < x1 or x2 < y1 < y2
which is equivalent to y2 < x1 or x2 < y1
.
Therefore, the condition to make the 2 ranges overlap: not(y2 < x1 or x2 < y1)
, which is equivalent to y2 >= x1 and x2 >= y1
(same with the accepted answer by Simon).
$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");
Swift:
var index = 1 + random() % 6
You can do it directly from Drive & Gmail. Here's how:
1.Upload an image to Google drive and set permissions for viewing (can be public OR anyone w/ link)
Go to Gmail>Compose. Select the + next to attachment icon.
Select drive icon (triangle shape)
Navigate to your image and right-click copy image url
Paste into web browser or embed on webpages as needed.
Other way to refresh (hard way) a page in angular 2 like this
it's look like f5
import { Location } from '@angular/common';
constructor(private location: Location) {}
pageRefresh() {
location.reload();
}