If you have array of custom Objects, you can search by specific property like this:
if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
doctorsInArea.remove(at: index)
}
or if you want to search by name for example
if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
doctorsInArea.remove(at: index)
}
This line:
public object Hours { get; set; }}
Your have a redundand }
at the end
If you're wondering about what glob.glob has done on your system in the past and cannot add a sorted
call, the ordering will be consistent on Mac HFS+ filesystems and will be traversal order on other Unix systems. So it will likely have been deterministic unless the underlying filesystem was reorganized which can happen if files were added, removed, renamed, deleted, moved, etc...
We're all in agreement that it is a difficult problem for many reasons, but that's precisely the reason to try to make it easier on everybody.
There is a recent module on CPAN, utf8::all, that attempts to "turn on Unicode. All of it".
As has been pointed out, you can't magically make the entire system (outside programs, external web requests, etc.) use Unicode as well, but we can work together to make sensible tools that make doing common problems easier. That's the reason that we're programmers.
If utf8::all doesn't do something you think it should, let's improve it to make it better. Or let's make additional tools that together can suit people's varying needs as well as possible.
`
The trailing quote "
in line 4 is adding a quote "
to the string. It should be removed.
The syntax for line 4 ends with %
For Javascript:
For PHP:
For OO design & programming, patterns:
For Refactoring:
For SQL/MySQL:
using System.IO; //add this namespace also
string[] filePaths = Directory.GetFiles(@"c:\Maps\", "*.txt",
SearchOption.TopDirectoryOnly);
6 years late to the party but I've been searching for how to extract an html element's tag attribute value, so for:
<span property="addressLocality">Ayr</span>
I want "addressLocality". I kept being directed back here, but the answers didn't really solve my problem.
How I managed to do it eventually:
>>> from bs4 import BeautifulSoup as bs
>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}
As it's a dict, you can then also use keys
and 'values'
>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']
Hopefully it helps someone else!
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
I'm forced to post this as an answer instead of a comment due to low reputation.
I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata
. I was able to use Dhara's answer to do this with a modification:
ax2.lines = []
instead of using:
ax2.cla()
When in use also cleared my plot from ax1
.
As it turns out, the problem wasn't actually a looping chain of synonyms, but the fact that the synonym was pointing to a view that did not exist.
Oracle apparently errors out as a looping chain in this condition.
Try this, in case of id
$("#YourId").text('Your text');
OR this, in case of class
$(".YourClassName").text('Your text');
I noticed that many examples are overcomplicated for localhost where just postgres user without password exist in many cases:
psql -d db_name -f dump.sql
I have solved the issue by the following way.
class MyTrustManager implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
throws CertificateException {
// TODO Auto-generated method stub
}
private static void disableSSL() {
try {
TrustManager[] trustAllCerts = new TrustManager[] { new MyTrustManager() };
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
Use "&
" instead of "&".
You can remove all the branches removing all the unnecessary refs:
rm .git/refs/heads/3.2.*
Includes are not directly supported in YAML as far as I know, you will have to provide a mechanism yourself however, this is generally easy to do.
I have used YAML as a configuration language in my python apps, and in this case often define a convention like this:
>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]
Then in my (python) code I do:
import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
cfg.update(yaml.load(open(inc)))
The only down side is that variables in the includes will always override the variables in main, and there is no way to change that precedence by changing where the "includes: statement appears in the main.yml file.
On a slightly different point, YAML doesn't support includes as its not really designed as as exclusively as a file based mark up. What would an include mean if you got it in a response to an AJAX request?
print "bla: ", $myvar =~ tr{a}{b},"\n";
Expanding @kravits88 answer:
This will stretch the buttons to fit whole width:
<div className="btn-group-justified">
<div className="btn-group">
<button type="button" className="btn btn-primary">SAVE MY DEAR!</button>
</div>
<div className="btn-group">
<button type="button" className="btn btn-default">CANCEL</button>
</div>
</div>
You might be just missing the column list, as the message says
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] ON
INSERT INTO [MyDB].[dbo].[Equipment]
(COL1,
COL2)
SELECT COL1,
COL2
FROM [MyDBQA].[dbo].[Equipment]
SET IDENTITY_INSERT [MyDB].[dbo].[Equipment] OFF
Try This :
document.getElementById(<element_ID>).readOnly=true;
Facebook seemingly randomly disables the ability to set localhost as a domain on your facebook app. I found the easiest work around was to tunnel my localhost to the web. This can be done for free using http://progrium.com/localtunnel/ or with a custom url (easier since you don't have to change url everytime in facebook) https://showoff.io
There are libraries that do charset conversion in Javascript. But if you want something simple, this function does approximately what you want:
function stringToBytes(text) {
const length = text.length;
const result = new Uint8Array(length);
for (let i = 0; i < length; i++) {
const code = text.charCodeAt(i);
const byte = code > 255 ? 32 : code;
result[i] = byte;
}
return result;
}
If you want to convert the resulting byte array into a Blob, you would do something like this:
const originalString = 'ååå';
const bytes = stringToBytes(originalString);
const blob = new Blob([bytes.buffer], { type: 'text/plain; charset=ISO-8859-1' });
Now, keep in mind that some apps do accept UTF-8 encoding, but they can't guess the encoding unless you prepend a BOM character, as explained here.
The underscore is the wildcard in a LIKE
query for one arbitrary character.
Hence LIKE %_%
means "give me all records with at least one arbitrary character in this column".
You have to escape the wildcard character, in sql-server with []
around:
SELECT m.*
FROM Manager m
WHERE m.managerid LIKE '[_]%'
AND m.managername LIKE '%[_]%'
See: LIKE (Transact-SQL)
If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine
library, there is a built in ListField
that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.
Using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df <- as_data_frame(mat) %>% # convert the matrix to a data frame
gather(name, val, C_0:C_1) %>% # convert the data frame from wide to long
select(name, time, val) # reorder the columns
df
# A tibble: 6 x 3
name time val
<chr> <dbl> <dbl>
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
What you're seeing is integer division. To get floating point division by default,
from __future__ import division
Or, you could convert 1 or 2 of 1/2 into a floating point value.
sqrt = x**(1.0/2)
Here's how you can mock your FileConnection
Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
.Throws(new IOException());
Then instantiate your Transfer class and use the mock in your method call
Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);
Update:
First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.
Since you are setting those properties using another dependency, I would write it like this:
public class Transfer
{
public Transfer(IInternalConfig internalConfig)
{
source = internalConfig.GetFileConnection("source");
destination = internalConfig.GetFileConnection("destination");
}
//you should consider making these private or protected fields
public virtual IFileConnection source { get; set; }
public virtual IFileConnection destination { get; set; }
public virtual void GetFile(IFileConnection connection,
string remoteFilename, string localFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void PutFile(IFileConnection connection,
string localFilename, string remoteFilename)
{
connection.Get(remoteFilename, localFilename);
}
public virtual void TransferFiles(string sourceName, string destName)
{
var tempName = Path.GetTempFileName();
GetFile(source, sourceName, tempName);
PutFile(destination, tempName, destName);
}
}
This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.
int i=99;//is what row you want to select and focus
listViewRamos.FocusedItem = listViewRamos.Items[0];
listViewRamos.Items[i].Selected = true;
listViewRamos.Select();
listViewRamos.EnsureVisible(i);//This is the trick
If you want nice button with rounded corners, then use this class:
.link_button {_x000D_
-webkit-border-radius: 4px;_x000D_
-moz-border-radius: 4px;_x000D_
border-radius: 4px;_x000D_
border: solid 1px #20538D;_x000D_
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.4);_x000D_
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);_x000D_
background: #4479BA;_x000D_
color: #FFF;_x000D_
padding: 8px 12px;_x000D_
text-decoration: none;_x000D_
}
_x000D_
<a href="#" class="link_button">Example</a>
_x000D_
Usually you restore your state in onCreate()
. It is possible to restore it in onRestoreInstanceState()
as well, but not very common. (onRestoreInstanceState()
is called after onStart()
, whereas onCreate()
is called before onStart()
.
Use the put methods to store values in onSaveInstanceState()
:
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putLong("param", value);
}
And restore the values in onCreate()
:
public void onCreate(Bundle icicle) {
if (icicle != null){
value = icicle.getLong("param");
}
}
It depends on (a) how attached you are to the number 7 as opposed to, say, Lemons, and (b) whether any of your file names contain newlines (and whether you're willing to rename them if they do).
There are many ways to deal with it, but some of them are:
mplayer Lemon*.mp3
find . -name 'Lemon*.mp3' -exec mplayer {} ';'
i=0
for mp3 in *.mp3
do
i=$((i+1))
[ $i = 7 ] && mplayer "$mp3"
done
for mp3 in *.mp3
do
case "$mp3" in
(Lemon*) mplayer "$mp3";;
esac
done
i=0
find . -name *.mp3 |
while read mp3
do
i=$((i+1))
[ $i = 7 ] && mplayer "$mp3"
done
The read
loop doesn't work if file names contain newlines; the others work correctly even with newlines in the names (let alone spaces). For my money, if you have file names containing a newline, you should rename the file without the newline. Using the double quotes around the file name is key to the loops working correctly.
If you have GNU find
and GNU xargs
(or FreeBSD (*BSD?), or Mac OS X), you can also use the -print0
and -0
options, as in:
find . -name 'Lemon*.mp3' -print0 | xargs -0 mplayer
This works regardless of the contents of the name (the only two characters that cannot appear in a file name are slash and NUL, and the slash causes no problems in a file path, so using NUL as the name delimiter covers everything). However, if you need to filter out the first 6 entries, you need a program that handles 'lines' ended by NUL instead of newline...and I'm not sure there are any.
The first is by far the simplest for the specific case on hand; however, it may not generalize to cover your other scenarios that you've not yet listed.
I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard
I was struggling with the same thing, running a shell script that set variables, then wanting to use the variables in the shared-pom. The goal was to have environment variables replace strings in my project files using the com.google.code.maven-replacer-plugin.
Using ${env.foo}
or ${env.FOO}
didn't work for me. Maven just wasn't finding the variable. What worked was passing the variable in as a command-line parameter in Maven. Here's the setup:
Set the variable in the shell script. If you're launching Maven in a sub-script, make sure the variable is getting set, e.g. using source ./maven_script.sh
to call it from the parent script.
In shared-pom, create a command-line param that grabs the environment variable:
<plugin> ... <executions> <executions> ... <execution> ... <configuration> <param>${foo}</param> <!-- Note this is *not* ${env.foo} --> </configuration>
In com.google.code.maven-replacer-plugin, make the replacement value ${foo}
.
In my shell script that calls maven, add this to the command: -Dfoo=$foo
There are multiple ways to calculate the distance based on the coordinates i.e latitude and longitude
from geopy import distance
from math import sin, cos, sqrt, atan2, radians
from sklearn.neighbors import DistanceMetric
import osrm
import numpy as np
lat1, lon1, lat2, lon2, R = 20.9467,72.9520, 21.1702, 72.8311, 6373.0
coordinates_from = [lat1, lon1]
coordinates_to = [lat2, lon2]
dlon = radians(lon2) - radians(lon1)
dlat = radians(lat2) - radians(lat1)
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance_haversine_formula = R * c
print('distance using haversine formula: ', distance_haversine_formula)
dist = DistanceMetric.get_metric('haversine')
X = [[radians(lat1), radians(lon1)], [radians(lat2), radians(lon2)]]
distance_sklearn = R * dist.pairwise(X)
print('distance using sklearn: ', np.array(distance_sklearn).item(1))
osrm_client = osrm.Client(host='http://router.project-osrm.org')
coordinates_osrm = [[lon1, lat1], [lon2, lat2]] # note that order is lon, lat
osrm_response = osrm_client.route(coordinates=coordinates_osrm, overview=osrm.overview.full)
dist_osrm = osrm_response.get('routes')[0].get('distance')/1000 # in km
print('distance using OSRM: ', dist_osrm)
distance_geopy = distance.distance(coordinates_from, coordinates_to).km
print('distance using geopy: ', distance_geopy)
distance_geopy_great_circle = distance.great_circle(coordinates_from, coordinates_to).km
print('distance using geopy great circle: ', distance_geopy_great_circle)
distance using haversine formula: 26.07547017310917
distance using sklearn: 27.847882224769783
distance using OSRM: 33.091699999999996
distance using geopy: 27.7528030550408
distance using geopy great circle: 27.839182219511834
Try putting your text in another div inside your span:
i.e.
<span><div>some text</div></span>
Update - I verified the below works. Maybe the creation of your JArray isn't quite right.
[TestMethod]
public void TestJson()
{
var jsonString = @"{""trends"": [
{
""name"": ""Croke Park II"",
""url"": ""http://twitter.com/search?q=%22Croke+Park+II%22"",
""promoted_content"": null,
""query"": ""%22Croke+Park+II%22"",
""events"": null
},
{
""name"": ""Siptu"",
""url"": ""http://twitter.com/search?q=Siptu"",
""promoted_content"": null,
""query"": ""Siptu"",
""events"": null
},
{
""name"": ""#HNCJ"",
""url"": ""http://twitter.com/search?q=%23HNCJ"",
""promoted_content"": null,
""query"": ""%23HNCJ"",
""events"": null
},
{
""name"": ""Boston"",
""url"": ""http://twitter.com/search?q=Boston"",
""promoted_content"": null,
""query"": ""Boston"",
""events"": null
},
{
""name"": ""#prayforboston"",
""url"": ""http://twitter.com/search?q=%23prayforboston"",
""promoted_content"": null,
""query"": ""%23prayforboston"",
""events"": null
},
{
""name"": ""#TheMrsCarterShow"",
""url"": ""http://twitter.com/search?q=%23TheMrsCarterShow"",
""promoted_content"": null,
""query"": ""%23TheMrsCarterShow"",
""events"": null
},
{
""name"": ""#Raw"",
""url"": ""http://twitter.com/search?q=%23Raw"",
""promoted_content"": null,
""query"": ""%23Raw"",
""events"": null
},
{
""name"": ""Iran"",
""url"": ""http://twitter.com/search?q=Iran"",
""promoted_content"": null,
""query"": ""Iran"",
""events"": null
},
{
""name"": ""#gaa"",
""url"": ""http://twitter.com/search?q=%23gaa"",
""promoted_content"": null,
""query"": ""gaa"",
""events"": null
},
{
""name"": ""Facebook"",
""url"": ""http://twitter.com/search?q=Facebook"",
""promoted_content"": null,
""query"": ""Facebook"",
""events"": null
}]}";
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
}
So call Children on your JArray to get each JObject in JArray. Call Children on each JObject to access the objects properties.
foreach(var item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
This worked fine for me:
$('#myelement').datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: "hh:mm:ss"
});
The option to make whitespace visible now appears as an option on the View menu, as "Toggle Render Whitespace" in version 1.15.1 of Visual Studio Code.
An empty String is a wrapper on a char[]
with no elements. You can have an empty char[]
. But you cannot have an "empty" char
. Like other primitives, a char
has to have a value.
You say you want to "replace a character without leaving a space".
If you are dealing with a char[]
, then you would create a new char[]
with that element removed.
If you are dealing with a String
, then you would create a new String
(String is immutable) with the character removed.
Here are some samples of how you could remove a char:
public static void main(String[] args) throws Exception {
String s = "abcdefg";
int index = s.indexOf('d');
// delete a char from a char[]
char[] array = s.toCharArray();
char[] tmp = new char[array.length-1];
System.arraycopy(array, 0, tmp, 0, index);
System.arraycopy(array, index+1, tmp, index, tmp.length-index);
System.err.println(new String(tmp));
// delete a char from a String using replace
String s1 = s.replace("d", "");
System.err.println(s1);
// delete a char from a String using StringBuilder
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(index);
s1 = sb.toString();
System.err.println(s1);
}
Try using viewport (vh, vm) units of measure at the body level
html, body { margin: 0; padding: 0; } body { min-height: 100vh; }
Use vh units for horizontal margins, paddings, and borders on the body and subtract them from the min-height value.
I've had bizarre results using vh,vm units on elements within the body, especially when re-sizing.
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
Use new percentage support library
compile 'com.android.support:percent:24.0.0'
See below example
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
app:layout_marginTopPercent="25%"
app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentRelativeLayout>
It's just two lines of code if LINQ is allowed to use. Please see my answer here.
EDIT
Here is my generic function which can return all the permutations (not combinations) from a list of T:
static IEnumerable<IEnumerable<T>>
GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1)
.SelectMany(t => list.Where(e => !t.Contains(e)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
Example:
IEnumerable<IEnumerable<int>> result =
GetPermutations(Enumerable.Range(1, 3), 3);
Output - a list of integer-lists:
{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}
As this function uses LINQ so it requires .net 3.5 or higher.
You should be able to put them in your ~/matlab on unix.
I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath
from the matlab command line.
You can traverse through the DataTable like below and set the value
foreach(DataTable thisTable in dataSet.Tables)
{
foreach(DataRow row in thisTable.Rows)
{
row["Product_name"] = "cde";
}
}
OR
thisTable.Rows[1]["Product_name"] = "cde";
Hope this helps
Using console.log(object)
will throw your object to the Javascript console, but that's not always what you want. Using JSON.stringify(object)
will return most stuff to be stored in a variable, for example to send it to a textarea input and submit the content back to the server.
First off, Xvfb doesn't read configuration from xorg.conf. Xvfb is a variant of the KDrive X servers and like all members of that family gets its configuration from the command line.
It is true that XRandR and Xinerama are mutually exclusive, but in the case of Xvfb there's no Xinerama in the first place. You can enable the XRandR extension by starting Xvfb using at least the following command line options
Xvfb +extension RANDR [further options]
Try the following :
try
{
var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
string body = "Your registration has been done successfully. Thank you.";
MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
message.Subject = "Thank You For Your Registration";
message.IsBodyHtml = true;
message.Body = body;
var client = new SmtpClient();
client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
client.Host = smtpHost;
client.EnableSsl = true;
client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
client.Send(message);
}
catch (Exception ex)
{
throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
}
And then in you web.config add the following in between
<!--Email Config-->
<add key="FromEmailAddress" value="sender emailaddress"/>
<add key="FromEmailDisplayName" value="Display Name"/>
<add key="FromEmailPassword" value="sender Password"/>
<add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
<add key="SMTPPort" value="smptp Port"/>
Future.delayed(Duration(seconds: 3) , your_function)
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
In ASP.Net you can use System.Web.HttpUtility
to safely encode the cookie value before writing to the cookie and convert it back to its original form on reading it out.
// Encode
HttpUtility.UrlEncode(cookieData);
// Decode
HttpUtility.UrlDecode(encodedCookieData);
This will stop ampersands and equals signs spliting a value into a bunch of name/value pairs as it is written to a cookie.
These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
for(int i = 0; i < getArray.size(); i++){
Object object = getArray.get(i);
// now do something with the Object
}
You need to check for the type:
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]
In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names()
to retrieve the individual keys.
This error means you can not directly load data from file system because there are security issues behind this. The only solution that I know is create a web service to serve load files.
In my case
In Control Panel -> System -> Advanced system settings -> Environment Variables
there is no JDK_HOME
OR JAVA_HOME
SO
I added an entry named: JDK_HOME pointing to: C:\Program Files\Java\jdk1.8.0_25\ (you have to point this to your JDK instalation path)
And all seems to work fine now
Use a color with an alpha value like #33------
, and set it as background of your editText using the XML attribute android:background=" "
.
255 * 0.2 = 51 ? in hex 33
You must use Eclipse WTP (Web Tool Platform), and should use the lastest version is Luna 4.4. Link download: Eclipse IDE for Java EE Developers http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunar
Menu Windows\Show view\Other, choose folder Server, click on Servers.
Right click on blank area to use context menu, choose New\Server
Press link "Download additional server adapters"
Choose "GlassFish Tools" from Oracle vendor.
Then, restart Eclipse.
Or you download GlassFish tools (Supports GlassFish 4.0 and 3.1) from: https://marketplace.eclipse.org/content/glassfish-tools and install manually.
Read more about creating a server: http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.wst.server.ui.doc.user%2Ftopics%2Ftwcrtins.html
If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.
The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.
Edit: Yeah, I guess I was wrong. See top entry. :)
Because C, where the concept originated, is 30 years old, and back then, it was the only viable way to link together code from multiple files.
Today, it's an awful hack which totally destroys compilation time in C++, causes countless needless dependencies (because class definitions in a header file expose too much information about the implementation), and so on.
Updated solution and workaround for SplitDateTime with required=False:
forms.py
from django import forms
class SplitDateTimeJSField(forms.SplitDateTimeField):
def __init__(self, *args, **kwargs):
super(SplitDateTimeJSField, self).__init__(*args, **kwargs)
self.widget.widgets[0].attrs = {'class': 'vDateField'}
self.widget.widgets[1].attrs = {'class': 'vTimeField'}
class AnyFormOrModelForm(forms.Form):
date = forms.DateField(widget=forms.TextInput(attrs={'class':'vDateField'}))
time = forms.TimeField(widget=forms.TextInput(attrs={'class':'vTimeField'}))
timestamp = SplitDateTimeJSField(required=False,)
form.html
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/admin_media/js/core.js"></script>
<script type="text/javascript" src="/admin_media/js/calendar.js"></script>
<script type="text/javascript" src="/admin_media/js/admin/DateTimeShortcuts.js"></script>
urls.py
(r'^admin/jsi18n/', 'django.views.i18n.javascript_catalog'),
If you know that the collection is a queue then you can cast the collection to a queue and get it easily.
There are several structures you can use to get the order, but you will need to cast to it.
If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p
first, or use the --rsync-path
trick as explained here :
rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/
Or use the --relative
option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:
rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/
This way, you will end up with /pre_existing/dir/new/x/y/z/
And if you want to have "y/z/" created, but not inside "new/x/", you can add ./
where you want --relative
to begin:
rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/
would create /pre_existing/dir/y/z/.
Adding @WebAppConfiguration
(org.springframework.test.context.web.WebAppConfiguration
) annotation to your DemoApplicationTests class will work.
If you want to parse using InputStreams
public Object xmlToObject(String xmlDataString) {
Object converted = null;
try {
JAXBContext jc = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
converted = unmarshaller.unmarshal(stream);
} catch (JAXBException e) {
e.printStackTrace();
}
return converted;
}
I had the same problem when I was using Eclipse Juno.. I installed Eclipse Indigo and it works fine. Try to reinstall eclipse.
Here's a generic version of Json converter
package com.github.platform.util;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import com.google.protobuf.AbstractMessage.Builder;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
/**
* Generic ProtoJsonUtil to be used to serialize and deserialize Proto to json
*
* @author [email protected]
*
*/
public final class ProtoJsonUtil {
/**
* Makes a Json from a given message or builder
*
* @param messageOrBuilder is the instance
* @return The string representation
* @throws IOException if any error occurs
*/
public static String toJson(MessageOrBuilder messageOrBuilder) throws IOException {
return JsonFormat.printer().print(messageOrBuilder);
}
/**
* Makes a new instance of message based on the json and the class
* @param <T> is the class type
* @param json is the json instance
* @param clazz is the class instance
* @return An instance of T based on the json values
* @throws IOException if any error occurs
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T extends Message> T fromJson(String json, Class<T> clazz) throws IOException {
// https://stackoverflow.com/questions/27642021/calling-parsefrom-method-for-generic-protobuffer-class-in-java/33701202#33701202
Builder builder = null;
try {
// Since we are dealing with a Message type, we can call newBuilder()
builder = (Builder) clazz.getMethod("newBuilder").invoke(null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
return null;
}
// The instance is placed into the builder values
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
// the instance will be from the build
return (T) builder.build();
}
}
Using it is as simple as follows:
GetAllGreetings.Builder allGreetingsBuilder = GetAllGreetings.newBuilder();
allGreetingsBuilder.addGreeting(makeNewGreeting("Marcello", "Hi %s, how are you", Language.EN))
.addGreeting(makeNewGreeting("John", "Today is hot, %s, get some ice", Language.ES))
.addGreeting(makeNewGreeting("Mary", "%s, summer is here! Let's go surfing!", Language.PT));
GetAllGreetings allGreetings = allGreetingsBuilder.build();
String json = ProtoJsonUtil.toJson(allGreetingsLoaded);
log.info("Json format: " + json);
GetAllGreetings parsed = ProtoJsonUtil.fromJson(json, GetAllGreetings.class);
log.info("The Proto deserialized from Json " + parsed);
Three slightly different answers depending how you look at the question:
1) Good enough for the exact question asked is Jonathan Leffler's solution, except that to round up to 16-aligned, you only need 15 extra bytes, not 16.
A:
/* allocate a buffer with room to add 0-15 bytes to ensure 16-alignment */
void *mem = malloc(1024+15);
ASSERT(mem); // some kind of error-handling code
/* round up to multiple of 16: add 15 and then round down by masking */
void *ptr = ((char*)mem+15) & ~ (size_t)0x0F;
B:
free(mem);
2) For a more generic memory allocation function, the caller doesn't want to have to keep track of two pointers (one to use and one to free). So you store a pointer to the 'real' buffer below the aligned buffer.
A:
void *mem = malloc(1024+15+sizeof(void*));
if (!mem) return mem;
void *ptr = ((char*)mem+sizeof(void*)+15) & ~ (size_t)0x0F;
((void**)ptr)[-1] = mem;
return ptr;
B:
if (ptr) free(((void**)ptr)[-1]);
Note that unlike (1), where only 15 bytes were added to mem, this code could actually reduce the alignment if your implementation happens to guarantee 32-byte alignment from malloc (unlikely, but in theory a C implementation could have a 32-byte aligned type). That doesn't matter if all you do is call memset_16aligned, but if you use the memory for a struct then it could matter.
I'm not sure off-hand what a good fix is for this (other than to warn the user that the buffer returned is not necessarily suitable for arbitrary structs) since there's no way to determine programatically what the implementation-specific alignment guarantee is. I guess at startup you could allocate two or more 1-byte buffers, and assume that the worst alignment you see is the guaranteed alignment. If you're wrong, you waste memory. Anyone with a better idea, please say so...
[Added:
The 'standard' trick is to create a union of 'likely to be maximally aligned types' to determine the requisite alignment. The maximally aligned types are likely to be (in C99) 'long long
', 'long double
', 'void *
', or 'void (*)(void)
'; if you include <stdint.h>
, you could presumably use 'intmax_t
' in place of long long
(and, on Power 6 (AIX) machines, intmax_t
would give you a 128-bit integer type). The alignment requirements for that union can be determined by embedding it into a struct with a single char followed by the union:
struct alignment
{
char c;
union
{
intmax_t imax;
long double ldbl;
void *vptr;
void (*fptr)(void);
} u;
} align_data;
size_t align = (char *)&align_data.u.imax - &align_data.c;
You would then use the larger of the requested alignment (in the example, 16) and the align
value calculated above.
On (64-bit) Solaris 10, it appears that the basic alignment for the result from malloc()
is a multiple of 32 bytes.
]
In practice, aligned allocators often take a parameter for the alignment rather than it being hardwired. So the user will pass in the size of the struct they care about (or the least power of 2 greater than or equal to that) and all will be well.
3) Use what your platform provides: posix_memalign
for POSIX, _aligned_malloc
on Windows.
4) If you use C11, then the cleanest - portable and concise - option is to use the standard library function aligned_alloc
that was introduced in this version of the language specification.
Hi for me I had to apply the 100% width to its grandparent element. Not its child element(s).
.grandparent {
float:left;
clear: both;
width:100%; //fix for IE11 text overflow
}
.parent {
display: flex;
border: 1px solid red;
align-items: center;
}
.child {
border: 1px solid blue;
}
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
grep
Forgetting performance, this is POSIX and looks nicer than case
solutions:
mystr="abcd"
if printf '%s' "$mystr" | grep -Eq '^ab'; then
echo matches
fi
Explanation:
printf '%s'
to prevent printf
from expanding backslash escapes: Bash printf literal verbatim stringgrep -q
prevents echo of matches to stdout: How to check if a file contains a specific string using Bashgrep -E
enables extended regular expressions, which we need for the ^
My variant for MySQL 5.7:
Stop service mysql:
$ sudo service mysql stop
Running in Safe Mode:
$ sudo mysqld_safe --skip-grant-tables --skip-networking
(above line is the whole command)
Open a new terminal window:
$ mysql -u root
$ mysql use mysql;
$ mysql update user set authentication_string=password('password') where user='root';
$ mysql update user set plugin="mysql_native_password" where User='root';
$ mysql flush privileges;
$ mysql quit;
Run the mysql service:
$ sudo service mysql start
I have joined the answer from Lucas and "ASP.NET MVC Helpers, Merging two object htmlAttributes together" and plus controllerName to following code:
// Sample usage in CSHTML
@Html.ActionImage("Edit",
"EditController"
new { id = MyId },
"~/Content/Images/Image.bmp",
new { width=108, height=129, alt="Edit" })
And the extension class for the code above:
using System.Collections.Generic;
using System.Reflection;
using System.Web.Mvc;
namespace MVC.Extensions
{
public static class MvcHtmlStringExt
{
// Extension method
public static MvcHtmlString ActionImage(
this HtmlHelper html,
string action,
string controllerName,
object routeValues,
string imagePath,
object htmlAttributes)
{
//https://stackoverflow.com/questions/4896439/action-image-mvc3-razor
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
var dictAttributes = htmlAttributes.ToDictionary();
if (dictAttributes != null)
{
foreach (var attribute in dictAttributes)
{
imgBuilder.MergeAttribute(attribute.Key, attribute.Value.ToString(), true);
}
}
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
public static IDictionary<string, object> ToDictionary(this object data)
{
//https://stackoverflow.com/questions/6038255/asp-net-mvc-helpers-merging-two-object-htmlattributes-together
if (data == null) return null; // Or throw an ArgumentNullException if you want
BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (PropertyInfo property in
data.GetType().GetProperties(publicAttributes))
{
if (property.CanRead)
{
dictionary.Add(property.Name, property.GetValue(data, null));
}
}
return dictionary;
}
}
}
As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:
git reset HEAD .
(note the trailing dot)git stash
git checkout master
git fetch upstream; git merge upstream/master
git checkout new-branch; git rebase master
git stash apply stash@{1}
I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.
number_format = function (number, decimals, dec_point, thousands_sep) {
number = number.toFixed(decimals);
var nstr = number.toString();
nstr += '';
x = nstr.split('.');
x1 = x[0];
x2 = x.length > 1 ? dec_point + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1))
x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');
return x1 + x2;
}
For example:
var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
@Shane Arney
performSelector:withObject:withObject:
You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:)
.
kinda weird that apple only supports 2 objects to be send and didnt make it more generic.
Use strcat http://www.cplusplus.com/reference/cstring/strcat/
int main ()
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
puts (str);
return 0;
}
Output:
these strings are concatenated.
OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
zoom: 13,_x000D_
center: {_x000D_
lat: 59.325,_x000D_
lng: 18.070_x000D_
}_x000D_
});_x000D_
var markerOption = {_x000D_
latitude: 59.327,_x000D_
longitude: 18.067,_x000D_
color: "#" + "000",_x000D_
text: "ha"_x000D_
};_x000D_
marker = createMarker(markerOption);_x000D_
marker.setMap(map);_x000D_
marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
marker.setOptions( {_x000D_
icon: iconTmpObj_x000D_
} );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
//IE MarkerShape has problem_x000D_
var markerObj = new google.maps.Marker({_x000D_
icon: createSvgIcon(options.color, options.text),_x000D_
position: {_x000D_
lat: parseFloat(options.latitude),_x000D_
lng: parseFloat(options.longitude)_x000D_
},_x000D_
draggable: false,_x000D_
visible: true,_x000D_
zIndex: 10,_x000D_
shape: {_x000D_
coords: CustomShapeCoords,_x000D_
type: 'poly'_x000D_
}_x000D_
});_x000D_
_x000D_
return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
var div = $("<div></div>");_x000D_
_x000D_
var svg = $(_x000D_
'<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
'<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
'<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
'<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
'</svg>'_x000D_
);_x000D_
div.append(svg);_x000D_
_x000D_
var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
var svgHtml = div[0].innerHTML;_x000D_
_x000D_
canvg(dd[0], svgHtml);_x000D_
_x000D_
var imgSrc = dd[0].toDataURL("image/png");_x000D_
//"scaledSize" and "optimized: false" together seems did the tricky ---IE11 && viewBox influent IE scaledSize_x000D_
//var svg = '<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
// + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
// + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
// + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
// + '</svg>';_x000D_
//var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
var iconObj = {_x000D_
size: new google.maps.Size(32, 43),_x000D_
url: imgSrc,_x000D_
scaledSize: new google.maps.Size(32, 43)_x000D_
};_x000D_
_x000D_
return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Your Custom Marker </title>_x000D_
<style>_x000D_
/* Always set the map height explicitly to define the size of the div_x000D_
* element that contains the map. */_x000D_
#map {_x000D_
height: 100%;_x000D_
}_x000D_
/* Optional: Makes the sample page fill the window. */_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="map"></div>_x000D_
<script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
With the pandas
library, this is as easy as using two commands!
pandas.read_json()
To convert a JSON string to a pandas object (either a series or dataframe). Then, assuming the results were stored as df
:
df.to_csv()
Which can either return a string or write directly to a csv-file.
Based on the verbosity of previous answers, we should all thank pandas for the shortcut.
Using dplyr provides an easy syntax for sorting the data frames
library(dplyr)
mtcars %>% arrange(gear, desc(mpg))
It might be useful to use the NSE version as shown here to allow dynamically building the sort list
sort_list <- c("gear", "desc(mpg)")
mtcars %>% arrange_(.dots = sort_list)
What is webpack & webpack-dev-server? Official documentation says it's a module bundler but for me it's just a task runner. What's the difference?
webpack-dev-server is a live reloading web server that Webpack developers use to get immediate feedback what they do. It should only be used during development.
This project is heavily inspired by the nof5 unit test tool.
Webpack as the name implies will create a SINGLE package for the web. The package will be minimized, and combined into a single file (we still live in HTTP 1.1 age). Webpack does the magic of combining the resources (JavaScript, CSS, images) and injecting them like this: <script src="assets/bundle.js"></script>
.
It can also be called module bundler because it must understand module dependencies, and how to grab the dependencies and to bundle them together.
Where would you use browserify? Can't we do the same with node/ES6 imports?
You could use Browserify on the exact same tasks where you would use Webpack. – Webpack is more compact, though.
Note that the ES6 module loader features in Webpack2 are using System.import, which not a single browser supports natively.
When would you use gulp/grunt over npm + plugins?
You can forget Gulp, Grunt, Brokoli, Brunch and Bower. Directly use npm command line scripts instead and you can eliminate extra packages like these here for Gulp:
var gulp = require('gulp'),
minifyCSS = require('gulp-minify-css'),
sass = require('gulp-sass'),
browserify = require('gulp-browserify'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
jshint = require('gulp-jshint'),
jshintStyle = require('jshint-stylish'),
replace = require('gulp-replace'),
notify = require('gulp-notify'),
You can probably use Gulp and Grunt config file generators when creating config files for your project. This way you don't need to install Yeoman or similar tools.
PASS A HASH INTO THE METHOD AND POPULATE IT......
public void buildResponse(String data, Map response);
Basically It is used in HeapOverflows or other reversing type Problems i.e. If you want to change a 64 bit ELF to 32 bit ELF and it is showing error while converting.
You can simply run the commands
apt-get install gcc-multilib g++-multilib
which will update your libraries Packages upgraded:
The following additional packages will be installed: g++-8-multilib gcc-8-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-dev-i386 libc6-dev-x32 libc6-i386 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1 Suggested packages: lib32stdc++6-8-dbg libx32stdc++6-8-dbg glibc-doc The following NEW packages will be installed: g++-8-multilib g++-multilib gcc-8-multilib gcc-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc6-dev-i386 libc6-dev-x32 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1
similar to this will be shown to your terminal
You have to retrieve it from the HOST
header.
var host = req.get('host');
It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.
If this is for supporting cross-origin requests, you would instead use the Origin
header.
var origin = req.get('origin');
Note that some cross-origin requests require validation through a "preflight" request:
req.options('/route', function (req, res) {
var origin = req.get('origin');
// ...
});
If you're looking for the client's IP, you can retrieve that with:
var userIP = req.socket.remoteAddress;
Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.
The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).
I did all of the suggested stuff here and my code still did not work because I was using curl
If you are using curl
in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
before calling:
curl_exec():
in the php file.
I believe that this disables all verification of SSL certificates.
Add Unique Index on your table:
ALTER IGNORE TABLE TableA
ADD UNIQUE INDEX (member_id, quiz_num, question_num, answer_num);
is work very well
in eclipse
properties->c/c++Build->setting->GCC C++ linker->libraries in top part add "pthread"
The easiest way to remove any configuration at all from npm is to edit the npm config file. It only takes two(2) commands to do this; one to open npm config file for editing, the other to confirm your change.
npm config list
to view a list of all npm configurations that are active.npm config edit
to open a text editor with npm configurations.
To remove the proxy line ( or simply comment it out ).npm config list
to confirm that the proxy configuration has been removed.C'est la vie!
I tried everything listed on this page, none worked, then I tried to the config edit. It worked instantly. (I use Windows 10)
double r2()
{
return (rand() % 10001) / 10000.0;
}
You can simply use
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
document.getElementById("gotoTop").style.display = "block";_x000D_
} else {_x000D_
document.getElementById("gotoTop").style.display = "none";_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
_x000D_
$('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
font-size: 20px;_x000D_
}_x000D_
_x000D_
#gotoTop {_x000D_
display: none;_x000D_
position: fixed;_x000D_
bottom: 20px;_x000D_
right: 30px;_x000D_
z-index: 99;_x000D_
font-size: 18px;_x000D_
border: none;_x000D_
outline: none;_x000D_
background-color: red;_x000D_
color: white;_x000D_
cursor: pointer;_x000D_
padding: 15px;_x000D_
border-radius: 4px;_x000D_
}_x000D_
_x000D_
#gotoTop:hover {_x000D_
background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
I am creating Dialog in onCreate
and using it with show
and hide
. For me the root cause was not dismissing onBackPressed
, which was finishing the Home
activity.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
Home.this.finish();
return;
}
}).create().show();
I was finishing the Home Activity onBackPressed
without closing / dismissing my dialogs.
When I dismissed my dialogs the crash disappeared.
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
networkErrorDialog.dismiss() ;
homeLocationErrorDialog.dismiss() ;
currentLocationErrorDialog.dismiss() ;
Home.this.finish();
return;
}
}).create().show();
You can add a span to your html and css .
Here's an example from my code ...
HTML ( JSX ):
<input type="radio" name="AMPM" id="radiostyle1" value="AM" checked={this.state.AMPM==="AM"} onChange={this.handleChange}/>
<label for="radiostyle1"><span></span> am </label>
<input type="radio" name="AMPM" id="radiostyle2" value="PM" checked={this.state.AMPM==="PM"} onChange={this.handleChange}/>
<label for="radiostyle2"><span></span> pm </label>
CSS to make standard radio button vanish on screen and superimpose custom button image:
input[type="radio"] {
opacity:0;
}
input[type="radio"] + label {
font-size:1em;
text-transform: uppercase;
color: white ;
cursor: pointer;
margin:auto 15px auto auto;
}
input[type="radio"] + label span {
display:inline-block;
width:30px;
height:10px;
margin:1px 0px 0 -30px;
cursor:pointer;
border-radius: 20%;
}
input[type="radio"] + label span {
background-color: #FFFFFF
}
input[type="radio"]:checked + label span{
background-color: #660006;
}
height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;
You can use this:
window.setInterval(yourfunction, 10000);
function yourfunction() { alert('test'); }
Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.
With LINQ:
List<string> l = new List<string> { "1", "2", "3" ,"4","5"};
List<string> l2 = l.Skip(1).Take(2).ToList();
If you need foreach, then no need for ToList:
foreach (string s in l.Skip(1).Take(2)){}
Advantage of LINQ is that if you want to just skip some leading element,you can :
List<string> l2 = l.Skip(1).ToList();
foreach (string s in l.Skip(1)){}
i.e. no need to take care of count/length, etc.
The ID of the two repos are both localSnap
; that's probably not what you want and it might confuse Maven.
If that's not it: There might be more repository
elements in your POM. Search the output of mvn help:effective-pom
for repository
to make sure the number and place of them is what you expect.
for me, it was because of all the outgoing files, i.e workspace is not in sync with SVN, due to the 'target' folders (maven project, or when building web project), add them to svn:ignore.
std::hex
gets you the hex formatting, but it is a stateful option, meaning you need to save and restore state or it will impact all future output.
Naively switching back to std::dec
is only good if that's where the flags were before, which may not be the case, particularly if you're writing a library.
#include <iostream>
#include <ios>
...
std::ios_base::fmtflags f( cout.flags() ); // save flags state
std::cout << std::hex << a;
cout.flags( f ); // restore flags state
This combines Greg Hewgill's answer and info from another question.
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_
This is how you can do it without a Dim
, using MessageBox.Show
instead of MsgBox
. This is in my opinion the cleanest way of writing it!
Select Case MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo)
Case vbYes
' Other Code goes here
Case vbNo
' Other Code goes here
End Select
You can shorten it down even further by using If
:
If MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo) = vbYes Then
' Other Code goes here
End If
By default Vagrant uses a generated private key to login, you can try this:
ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
First make sure you have SessionMiddleware
and AuthenticationMiddleware
middlewares added to your MIDDLEWARE_CLASSES
setting.
The current user
is in request
object, you can get it by:
def sample_view(request):
current_user = request.user
print current_user.id
request.user
will give you a User
object representing the currently logged-in user. If a user isn't currently logged in, request.user
will be set to an instance of AnonymousUser
. You can tell them apart with the field is_authenticated
, like so:
if request.user.is_authenticated:
# Do something for authenticated users.
else:
# Do something for anonymous users.
Try this:
(add-hook 'text-mode-hook
(function
(lambda ()
(setq tab-width 4)
(define-key text-mode-map "\C-i" 'self-insert-command)
)))
That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.
Simple. The GNU time
utility has an option for that.
But you have to ensure that you are not using your shell's builtin time
command, at least the bash
builtin does not provide that option! That's why you need to give the full path of the time
utility:
/usr/bin/time -o time.txt sleep 1
Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.
HTML
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
</a></div>
CSS
.navbar-toggle, .icon-bar {
border:1px solid orange;
}
BOOM...
On windows I used the following command
:wq
and it aborts the previous commit because of the empty commit message
I recently ran into this problem too and unfortunately had many occurences of names beginning with Mc and Mac, I ended up using a version of scottb's code which I changed to handle these prefixes so it's here in case anyone wants to use it.
There are still edge cases which this misses but the worst thing that can happen is that a letter will be lower case when it should be capitalized.
/**
* Get a nicely formatted representation of the name.
* Don't send this the whole name at once, instead send it the components.<br>
* For example: andrew macnamara would be returned as:<br>
* Andrew Macnamara if processed as a single string<br>
* Andrew MacNamara if processed as 2 strings.
* @param name
* @return correctly formatted name
*/
public static String getNameTitleCase (String name) {
final String ACTIONABLE_DELIMITERS = " '-/";
StringBuilder sb = new StringBuilder();
if (name !=null && !name.isEmpty()){
boolean capitaliseNext = true;
for (char c : name.toCharArray()) {
c = (capitaliseNext)?Character.toUpperCase(c):Character.toLowerCase(c);
sb.append(c);
capitaliseNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0);
}
name = sb.toString();
if (name.startsWith("Mc") && name.length() > 2 ) {
char c = name.charAt(2);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,2));
sb.append (name.substring(2,3).toUpperCase());
sb.append (name.substring(3));
name=sb.toString();
}
} else if (name.startsWith("Mac") && name.length() > 3) {
char c = name.charAt(3);
if (ACTIONABLE_DELIMITERS.indexOf((int) c) < 0) {
sb = new StringBuilder();
sb.append (name.substring(0,3));
sb.append (name.substring(3,4).toUpperCase());
sb.append (name.substring(4));
name=sb.toString();
}
}
}
return name;
}
MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.
for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php
to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/
The file basically contain data for two new tables.
Then you may find it simpler to just DTS (or SSIS, if this is SQL Server 2005+) the data over, if the two servers are on the same network.
If the two servers are not on the same network, you can backup the source database and restore it to a new database on the destination server. Then you can use DTS/SSIS, or even a simple INSERT INTO SELECT
, to transfer the two tables to the destination database.
In SQL Server 2012 or higher, you can use a combination of IIF
and ISNULL
(or COALESCE
) to get the maximum of 2 values.
Even when 1 of them is NULL.
IIF(col1 >= col2, col1, ISNULL(col2, col1))
Or if you want it to return 0 when both are NULL
IIF(col1 >= col2, col1, COALESCE(col2, col1, 0))
Example snippet:
-- use table variable for testing purposes
declare @Order table
(
OrderId int primary key identity(1,1),
NegotiatedPrice decimal(10,2),
SuggestedPrice decimal(10,2)
);
-- Sample data
insert into @Order (NegotiatedPrice, SuggestedPrice) values
(0, 1),
(2, 1),
(3, null),
(null, 4);
-- Query
SELECT
o.OrderId, o.NegotiatedPrice, o.SuggestedPrice,
IIF(o.NegotiatedPrice >= o.SuggestedPrice, o.NegotiatedPrice, ISNULL(o.SuggestedPrice, o.NegotiatedPrice)) AS MaxPrice
FROM @Order o
Result:
OrderId NegotiatedPrice SuggestedPrice MaxPrice
1 0,00 1,00 1,00
2 2,00 1,00 2,00
3 3,00 NULL 3,00
4 NULL 4,00 4,00
But if one needs the maximum of multiple columns?
Then I suggest a CROSS APPLY on an aggregation of the VALUES.
Example:
SELECT t.*
, ca.[Maximum]
, ca.[Minimum], ca.[Total], ca.[Average]
FROM SomeTable t
CROSS APPLY (
SELECT
MAX(v.col) AS [Maximum],
MIN(v.col) AS [Minimum],
SUM(v.col) AS [Total],
AVG(v.col) AS [Average]
FROM (VALUES (t.Col1), (t.Col2), (t.Col3), (t.Col4)) v(col)
) ca
This has the extra benefit that this can calculate other things at the same time.
I'm sure it is executing properly, but you're trying to change the UI elements in the background thread and that won't do.
Revise your call and AsyncTask as follows:
Calling Class
Note: I personally suggest using onPostExecute()
wherever you execute your AsyncTask thread and not in the class that extends AsyncTask itself. I think it makes the code easier to read especially if you need the AsyncTask in multiple places handling the results slightly different.
new LongThread() {
@Override public void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
}.execute("");
LongThread class (extends AsyncTask):
@Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Executed";
}
I usually start out with some combination of:
typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)
as appropriate based on what's revealed. For example, try with:
obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)
..etc.
If obj
is an S3 or S4 object, you can also try methods
or showMethods
, showClass
, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).
EDIT: Dirk and Hadley mention str(obj)
in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.
A little late to the party, but here's a more comprehensive answer with examples:
React is a component based UI library that uses a "shadow DOM" to efficiently update the DOM with what has changed instead of rebuilding the entire DOM tree for every change. It was initially built for web apps, but now can be used for mobile & 3D/vr as well.
Components between React and React Native cannot be interchanged because React Native maps to native mobile UI elements but business logic and non-render related code can be re-used.
Was initially included with the React library but was split out once React was being used for other platforms than just web. It serves as the entry point to the DOM and is used in union with React.
Example:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
state = {
data: [],
}
componentDidMount() {
const data = API.getData(); // fetch some data
this.setState({ data })
}
clearData = () => {
this.setState({
data: [],
});
}
render() {
return (
<div>
{this.state.data.map((data) => (
<p key={data.id}>{data.label}</p>
))}
<button onClick={this.clearData}>
Clear list
</button>
</div>
);
}
}
ReactDOM.render(App, document.getElementById('app'));
React Native is a cross-platform mobile framework that uses React and communicates between Javascript and it's native counterpart via a "bridge". Due to this, a lot of UI structuring has to be different when using React Native. For example: when building a list, you will run into major performance issues if you try to use map
to build out the list instead of React Native's FlatList
. React Native can be used to build out IOS/Android mobile apps, as well as for smart watches and TV's.
Expo is the go-to when starting a new React Native app.
Expo is a framework and a platform for universal React applications. It is a set of tools and services built around React Native and native platforms that help you develop, build, deploy, and quickly iterate on iOS, Android, and web apps
Note: When using Expo, you can only use the Native Api's they provide. All additional libraries you include will need to be pure javascript or you will need to eject expo.
Same example using React Native:
import React, { Component } from 'react';
import { Flatlist, View, Text, StyleSheet } from 'react-native';
export default class App extends Component {
state = {
data: [],
}
componentDidMount() {
const data = API.getData(); // fetch some data
this.setState({ data })
}
clearData = () => {
this.setState({
data: [],
});
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={({ item }) => <Text key={item.id}>{item.label}</Text>}
/>
<Button title="Clear list" onPress={this.clearData}></Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
onClick
turn into onPress
, React Native uses stylesheets to define styles in a more performant way, and React Native uses flexbox as the default layout structure to keep things responsive.It's also worth mentioning that React can also be used to develop 3D/VR applications. The component structure is very similar to React Native. https://facebook.github.io/react-360/
Use COALESCE
, which returns the first not-null value e.g.
SELECT COALESCE(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) as Succeeded
Will set Succeeded as 0 if it is returned as NULL
.
I also experienced this error.
I add into header Content-Type
: application/json
. Following the change, my submissions succeed!
The only reason that I know of why a formula wouldn't be available to summarize on is if it didn't reference any database fields or whose value wasn't dynamic throughout sections of the report. For example, if you have a formula that returns a constant it won't be available. Or if it only references a field that is set throughout the report and returns a value based on that field, like "if {parameter}=1 then 1" would not be available either.
In general, the formula's value should not be static through the sections of the report you're summarizing over (Though the way Crystal determines this is beyond me and this doesn't seem to be a hard and fast rule)
EDIT: One other reason why a formula wouldn't be available is if you're already using a summary function in that formula. Only one level of summaries at a time!
Regex: match everything but:
foo
):
world.
at the end):
foo
) (no POSIX compliant patern, sorry):
|
symbol):
foo
):
cat
): /cat(*SKIP)(*FAIL)|[^c]*(?:c(?!at)[^c]*)*/i
or /cat(*SKIP)(*FAIL)|(?:(?!cat).)+/is
(cat)|[^c]*(?:c(?!at)[^c]*)*
(or (?s)(cat)|(?:(?!cat).)*
, or (cat)|[^c]+(?:c(?!at)[^c]*)*|(?:c(?!at)[^c]*)+[^c]*
) and then check with language means: if Group 1 matched, it is not what we need, else, grab the match value if not empty[^a-z]+
(any char other than a lowercase ASCII letter)|
: [^|]+
Demo note: the newline \n
is used inside negated character classes in demos to avoid match overflow to the neighboring line(s). They are not necessary when testing individual strings.
Anchor note: In many languages, use \A
to define the unambiguous start of string, and \z
(in Python, it is \Z
, in JavaScript, $
is OK) to define the very end of the string.
Dot note: In many flavors (but not POSIX, TRE, TCL), .
matches any char but a newline char. Make sure you use a corresponding DOTALL modifier (/s
in PCRE/Boost/.NET/Python/Java and /m
in Ruby) for the .
to match any char including a newline.
Backslash note: In languages where you have to declare patterns with C strings allowing escape sequences (like \n
for a newline), you need to double the backslashes escaping special characters so that the engine could treat them as literal characters (e.g. in Java, world\.
will be declared as "world\\."
, or use a character class: "world[.]"
). Use raw string literals (Python r'\bworld\b'
), C# verbatim string literals @"world\."
, or slashy strings/regex literal notations like /world\./
.
awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'
If I understood your problem correctly, $(this).parents('.box').children('.something1')
Is this what you are looking for?
My suspicion is that it has to do with how server-side controls are identified during processing. Rather than having to check every control at runtime by name to determine whether server-side processing needs to be done, it does a selection on the internal node representation by tag. The compiler checks to make sure that all controls that require server tags have them during the validation step.
From here (Google is your friend):
In a DTD, PCDATA and CDATA are used to assert something about the allowable content of elements and attributes, respectively. In an element's content model, #PCDATA says that the element contains (may contain) "any old text." (With exceptions as noted below.) In an attribute's declaration, CDATA is one sort of constraint you can put on the attribute's allowable values (other sorts, all mutually exclusive, include ID, IDREF, and NMTOKEN). An attribute whose allowable values are CDATA can (like PCDATA in an element) contain "any old text."
A potentially really confusing issue is that there's another "CDATA," also referred to as marked sections. A marked section is a portion of element (#PCDATA) content delimited with special strings: to close it. If you remember that PCDATA is "parsed character data," a CDATA section is literally the same thing, without the "parsed." Parsers transmit the content of a marked section to downstream applications without hiccupping every time they encounter special characters like < and &. This is useful when you're coding a document that contains lots of those special characters (like scripts and code fragments); it's easier on data entry, and easier on reading, than the corresponding entity reference.
So you can infer that the exception to the "any old text" rule is that PCDATA cannot include any of these unescaped special characters, UNLESS they fall within the scope of a CDATA marked section.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
*
* @author Xiao Ma
* mail : [email protected]
*
*/
public class SimilarityUtil {
public static double consineTextSimilarity(String[] left, String[] right) {
Map<String, Integer> leftWordCountMap = new HashMap<String, Integer>();
Map<String, Integer> rightWordCountMap = new HashMap<String, Integer>();
Set<String> uniqueSet = new HashSet<String>();
Integer temp = null;
for (String leftWord : left) {
temp = leftWordCountMap.get(leftWord);
if (temp == null) {
leftWordCountMap.put(leftWord, 1);
uniqueSet.add(leftWord);
} else {
leftWordCountMap.put(leftWord, temp + 1);
}
}
for (String rightWord : right) {
temp = rightWordCountMap.get(rightWord);
if (temp == null) {
rightWordCountMap.put(rightWord, 1);
uniqueSet.add(rightWord);
} else {
rightWordCountMap.put(rightWord, temp + 1);
}
}
int[] leftVector = new int[uniqueSet.size()];
int[] rightVector = new int[uniqueSet.size()];
int index = 0;
Integer tempCount = 0;
for (String uniqueWord : uniqueSet) {
tempCount = leftWordCountMap.get(uniqueWord);
leftVector[index] = tempCount == null ? 0 : tempCount;
tempCount = rightWordCountMap.get(uniqueWord);
rightVector[index] = tempCount == null ? 0 : tempCount;
index++;
}
return consineVectorSimilarity(leftVector, rightVector);
}
/**
* The resulting similarity ranges from -1 meaning exactly opposite, to 1
* meaning exactly the same, with 0 usually indicating independence, and
* in-between values indicating intermediate similarity or dissimilarity.
*
* For text matching, the attribute vectors A and B are usually the term
* frequency vectors of the documents. The cosine similarity can be seen as
* a method of normalizing document length during comparison.
*
* In the case of information retrieval, the cosine similarity of two
* documents will range from 0 to 1, since the term frequencies (tf-idf
* weights) cannot be negative. The angle between two term frequency vectors
* cannot be greater than 90°.
*
* @param leftVector
* @param rightVector
* @return
*/
private static double consineVectorSimilarity(int[] leftVector,
int[] rightVector) {
if (leftVector.length != rightVector.length)
return 1;
double dotProduct = 0;
double leftNorm = 0;
double rightNorm = 0;
for (int i = 0; i < leftVector.length; i++) {
dotProduct += leftVector[i] * rightVector[i];
leftNorm += leftVector[i] * leftVector[i];
rightNorm += rightVector[i] * rightVector[i];
}
double result = dotProduct
/ (Math.sqrt(leftNorm) * Math.sqrt(rightNorm));
return result;
}
public static void main(String[] args) {
String left[] = { "Julie", "loves", "me", "more", "than", "Linda",
"loves", "me" };
String right[] = { "Jane", "likes", "me", "more", "than", "Julie",
"loves", "me" };
System.out.println(consineTextSimilarity(left,right));
}
}
Shut down w3svc and delete everything from c:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\
added
on Windows 7
c:\Users\{username}\AppData\Local\Temp\Temporary ASP.NET Files\root\
on IIS servers (64 bit) this can also occur. Look for:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root
(replace v4.0.30319 by the framework version you're using if newer on your server)
For SASS/SCSS user using Bourbon, it has a built-in function.
//main.scss
@import 'bourbon';
input {
width: 300px;
@include placeholder {
color: red;
}
}
CSS Output, you can also grab this portion and paste into your code.
//main.css
input {
width: 300px;
}
input::-webkit-input-placeholder {
color: red;
}
input:-moz-placeholder {
color: red;
}
input::-moz-placeholder {
color: red;
}
input:-ms-input-placeholder {
color: red;
}
If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure.
For django-mptt, I used a structure like this:
id parent_id tree_id level lft rght -- --------- ------- ----- --- ---- 1 null 1 0 1 14 2 1 1 1 2 7 3 2 1 2 3 4 4 2 1 2 5 6 5 1 1 1 8 13 6 5 1 2 9 10 7 5 1 2 11 12
Which describes a tree which looks like this (with id
representing each item):
1 +-- 2 | +-- 3 | +-- 4 | +-- 5 +-- 6 +-- 7
Or, as a nested set diagram which makes it more obvious how the lft
and rght
values work:
__________________________________________________________________________ | Root 1 | | ________________________________ ________________________________ | | | Child 1.1 | | Child 1.2 | | | | ___________ ___________ | | ___________ ___________ | | | | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | | 1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14 | |________________________________| |________________________________| | |__________________________________________________________________________|
As you can see, to get the entire subtree for a given node, in tree order, you simply have to select all rows which have lft
and rght
values between its lft
and rght
values. It's also simple to retrieve the tree of ancestors for a given node.
The level
column is a bit of denormalisation for convenience more than anything and the tree_id
column allows you to restart the lft
and rght
numbering for each top-level node, which reduces the number of columns affected by inserts, moves and deletions, as the lft
and rght
columns have to be adjusted accordingly when these operations take place in order to create or close gaps. I made some development notes at the time when I was trying to wrap my head around the queries required for each operation.
In terms of actually working with this data to display a tree, I created a tree_item_iterator
utility function which, for each node, should give you sufficient information to generate whatever kind of display you want.
More info about MPTT:
You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.
<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
content: attr(value);
margin: -3px 15px;
vertical-align: top;
white-space:nowrap;
display: inline-block;
}
</style>
All pseudo element labels will be clickable.
JPA (from Java EE 5) is an excellent example of the (over)use of annotations. Java EE 6 will also introduce annotations in lot of new areas, such as RESTful webservices and new annotations for under each the good old Servlet API.
Here are several resources:
It is not only the configuration specifics which are to / can be taken over by annotations, but they can also be used to control the behaviour. You see this good back in the Java EE 6's JAX-RS examples.
Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)
import os
os.chmod("file_name" , 0777)
Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm
So for python 3.7, it will be
import os
os.chmod("file_name" , 0o777)
This work for me in .NET Core 3.1.
But not in .NET 5 preview 7.
using System;
using System.Security.Cryptography;
using System.Text;
namespace PortalAplicaciones.Shared.Models
{
public class Encriptar
{
public static string EncriptaPassWord(string Password)
{
try
{
SHA256Managed hasher = new SHA256Managed();
byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
byte[] keyBytes = hasher.ComputeHash(pwdBytes);
hasher.Dispose();
return Convert.ToBase64String(keyBytes);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
}
}
Note: This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.
If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)
title="This field should not be left blank."
See http://jsfiddle.net/kaleb/nfgfP/8/
And in Firefox, you can add this attribute:
x-moz-errormessage="This field should not be left blank."
This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.
Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.
I discovered that you can also do Device Manager -> Update Driver Software -> Browse my computer for driver software -> Let me pick from a list of device drivers on my computer -> Android Phone -> [ADB driver version 6 near top of list... sorry, I can't remember exact name]
As soon as I did that, it connected, and I was able to sideload version 4.2 on Windows 7 64 bit.
I called ng-click
to angularjs controller on Encourage button,
<tr ng-cloak
ng-repeat="user in result.users">
<td>{{user.userName}}</rd>
<td>
<a class="btn btn-primary span11" ng-click="setUsername({{user.userName}})" href="#encouragementModal" data-toggle="modal">
Encourage
</a>
</td>
</tr>
I set userName
of encouragementModal
from angularjs controller.
/**
* Encouragement controller for AngularJS
*
* @param $scope
* @param $http
* @param encouragementService
*/
function EncouragementController($scope, $http, encouragementService) {
/**
* set invoice number
*/
$scope.setUsername = function (username) {
$scope.userName = username;
};
}
EncouragementController.$inject = [ '$scope', '$http', 'encouragementService' ];
I provided a place(userName
) to get value from angularjs controller on encouragementModal
.
<div id="encouragementModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h3>Confirm encouragement?</h3>
</div>
<div class="modal-body">
Do you really want to encourage <b>{{userName}}</b>?
</div>
<div class="modal-footer">
<button class="btn btn-info"
ng-click="encourage('${createLink(uri: '/encourage/')}',{{userName}})">
Confirm
</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
</div>
</div>
I would argue you might want to use a cursor when you want to do comparisons of characteristics that are on different rows of the return set, or if you want to write a different output row format than a standard one in certain cases. Two examples come to mind:
One was in a college where each add and drop of a class had its own row in the table. It might have been bad design but you needed to compare across rows to know how many add and drop rows you had in order to determine whether the person was in the class or not. I can't think of a straight forward way to do that with only sql.
Another example is writing a journal total line for GL journals. You get an arbitrary number of debits and credits in your journal, you have many journals in your rowset return, and you want to write a journal total line every time you finish a journal to post it into a General Ledger. With a cursor you could tell when you left one journal and started another and have accumulators for your debits and credits and write a journal total line (or table insert) that was different than the debit/credit line.
If you don't have particular needs, I suggest to install Typescript locally.
npm install --global typescript # Global installation
npm install --save-dev typescript # Local installation
yarn global add typescript # Global installation
yarn add --dev typescript # Local installation
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
I noticed that if you have divisions it rounds off to integer, it would be better to use:
c=float(max(a1,...,an))/b
Sorry for the late post!
A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.
http://jsbin.com/ekohep/2/edit#javascript,html,live
Enjoy :)
PS, doesn't use jQuery - but obviously could.
Use Awk.
awk '{ print length }' abc.txt
In vb.net or C# I would expect that the fastest general approach to compare a variable against any reasonable number of separately-named objects (as opposed to e.g. all the things in a collection) will be to simply compare each object against the comparand much as you have done. It is certainly possible to create an instance of a collection and see if it contains the object, and doing so may be more expressive than comparing the object against all items individually, but unless one uses a construct which the compiler can explicitly recognize, such code will almost certainly be much slower than simply doing the individual comparisons. I wouldn't worry about speed if the code will by its nature run at most a few hundred times per second, but I'd be wary of the code being repurposed to something that's run much more often than originally intended.
An alternative approach, if a variable is something like an enumeration type, is to choose power-of-two enumeration values to permit the use of bitmasks. If the enumeration type has 32 or fewer valid values (e.g. starting Harry=1, Ron=2, Hermione=4, Ginny=8, Neville=16) one could store them in an integer and check for multiple bits at once in a single operation ((if ((thisOne & (Harry | Ron | Neville | Beatrix)) != 0) /* Do something */. This will allow for fast code, but is limited to enumerations with a small number of values.
A somewhat more powerful approach, but one which must be used with care, is to use some bits of the value to indicate attributes of something, while other bits identify the item. For example, bit 30 could indicate that a character is male, bit 29 could indicate friend-of-Harry, etc. while the lower bits distinguish between characters. This approach would allow for adding characters who may or may not be friend-of-Harry, without requiring the code that checks for friend-of-Harry to change. One caveat with doing this is that one must distinguish between enumeration constants that are used to SET an enumeration value, and those used to TEST it. For example, to set a variable to indicate Harry, one might want to set it to 0x60000001, but to see if a variable IS Harry, one should bit-test it with 0x00000001.
One more approach, which may be useful if the total number of possible values is moderate (e.g. 16-16,000 or so) is to have an array of flags associated with each value. One could then code something like "if (((characterAttributes[theCharacter] & chracterAttribute.Male) != 0)". This approach will work best when the number of characters is fairly small. If array is too large, cache misses may slow down the code to the point that testing against a small number of characters individually would be faster.
I tested all the answers about this topic. And nothing worked here… but I found another solution.
Go to pom -> overview and add these to your properties:
Name: “maven.compiler.target” Value: “1.8”
and
Name: “maven.compiler.source” Value: “1.8”
Now do a maven update.
Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here
Open the sources.list
file:
sudo nano /etc/apt/sources.list
Add a line with the source from where the packages will be retrieved. For example:
deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
Replace https://cloud.r-project.org
with whatever mirror you would like to use, and replace
version/
with whatever version of Ubuntu you are using (eg, trusty/
, xenial/
, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/
and version/
.
Fetch the secure APT key:
gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
or
gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
Add it to keyring:
gpg -a --export E084DAB9 | sudo apt-key add -
Update your sources and upgrade your installation:
sudo apt-get update && sudo apt-get upgrade
Install the new version
sudo apt-get install r-base-dev
Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:
-- copy the packages from R-oldversion/library
to R-newversion/library
, (do not overwrite a package if it already exists in the new version!).
-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE)
.
This post itself is not a direct answer to the question. What it is instead is a data-driven extensible benchmark that can be used to compare many of the answers (and variations of utilizing new features added in later, more modern, versions of Python) that have been posted to this question — and should therefore be helpful in determining which has the best performance.
In a few cases I've modified the code in the referenced answer to make it compatible with the benchmark framework.
First, here are the results for what currently are the latest versions of Python 2 & 3:
Fastest to slowest execution speeds with 32-bit Python 2.7.16
numpy version 1.16.5
Test file size: 1,024 KiB
100 executions, best of 3 repetitions
1 Tcll (array.array) : 3.8943 secs, rel speed 1.00x, 0.00% slower (262.95 KiB/sec)
2 Vinay Sajip (read all into memory) : 4.1164 secs, rel speed 1.06x, 5.71% slower (248.76 KiB/sec)
3 codeape + iter + partial : 4.1616 secs, rel speed 1.07x, 6.87% slower (246.06 KiB/sec)
4 codeape : 4.1889 secs, rel speed 1.08x, 7.57% slower (244.46 KiB/sec)
5 Vinay Sajip (chunked) : 4.1977 secs, rel speed 1.08x, 7.79% slower (243.94 KiB/sec)
6 Aaron Hall (Py 2 version) : 4.2417 secs, rel speed 1.09x, 8.92% slower (241.41 KiB/sec)
7 gerrit (struct) : 4.2561 secs, rel speed 1.09x, 9.29% slower (240.59 KiB/sec)
8 Rick M. (numpy) : 8.1398 secs, rel speed 2.09x, 109.02% slower (125.80 KiB/sec)
9 Skurmedel : 31.3264 secs, rel speed 8.04x, 704.42% slower ( 32.69 KiB/sec)
Benchmark runtime (min:sec) - 03:26
Fastest to slowest execution speeds with 32-bit Python 3.8.0
numpy version 1.17.4
Test file size: 1,024 KiB
100 executions, best of 3 repetitions
1 Vinay Sajip + "yield from" + "walrus operator" : 3.5235 secs, rel speed 1.00x, 0.00% slower (290.62 KiB/sec)
2 Aaron Hall + "yield from" : 3.5284 secs, rel speed 1.00x, 0.14% slower (290.22 KiB/sec)
3 codeape + iter + partial + "yield from" : 3.5303 secs, rel speed 1.00x, 0.19% slower (290.06 KiB/sec)
4 Vinay Sajip + "yield from" : 3.5312 secs, rel speed 1.00x, 0.22% slower (289.99 KiB/sec)
5 codeape + "yield from" + "walrus operator" : 3.5370 secs, rel speed 1.00x, 0.38% slower (289.51 KiB/sec)
6 codeape + "yield from" : 3.5390 secs, rel speed 1.00x, 0.44% slower (289.35 KiB/sec)
7 jfs (mmap) : 4.0612 secs, rel speed 1.15x, 15.26% slower (252.14 KiB/sec)
8 Vinay Sajip (read all into memory) : 4.5948 secs, rel speed 1.30x, 30.40% slower (222.86 KiB/sec)
9 codeape + iter + partial : 4.5994 secs, rel speed 1.31x, 30.54% slower (222.64 KiB/sec)
10 codeape : 4.5995 secs, rel speed 1.31x, 30.54% slower (222.63 KiB/sec)
11 Vinay Sajip (chunked) : 4.6110 secs, rel speed 1.31x, 30.87% slower (222.08 KiB/sec)
12 Aaron Hall (Py 2 version) : 4.6292 secs, rel speed 1.31x, 31.38% slower (221.20 KiB/sec)
13 Tcll (array.array) : 4.8627 secs, rel speed 1.38x, 38.01% slower (210.58 KiB/sec)
14 gerrit (struct) : 5.0816 secs, rel speed 1.44x, 44.22% slower (201.51 KiB/sec)
15 Rick M. (numpy) + "yield from" : 11.8084 secs, rel speed 3.35x, 235.13% slower ( 86.72 KiB/sec)
16 Skurmedel : 11.8806 secs, rel speed 3.37x, 237.18% slower ( 86.19 KiB/sec)
17 Rick M. (numpy) : 13.3860 secs, rel speed 3.80x, 279.91% slower ( 76.50 KiB/sec)
Benchmark runtime (min:sec) - 04:47
I also ran it with a much larger 10 MiB test file (which took nearly an hour to run) and got performance results which were comparable to those shown above.
Here's the code used to do the benchmarking:
from __future__ import print_function
import array
import atexit
from collections import deque, namedtuple
import io
from mmap import ACCESS_READ, mmap
import numpy as np
from operator import attrgetter
import os
import random
import struct
import sys
import tempfile
from textwrap import dedent
import time
import timeit
import traceback
try:
xrange
except NameError: # Python 3
xrange = range
class KiB(int):
""" KibiBytes - multiples of the byte units for quantities of information. """
def __new__(self, value=0):
return 1024*value
BIG_TEST_FILE = 1 # MiBs or 0 for a small file.
SML_TEST_FILE = KiB(64)
EXECUTIONS = 100 # Number of times each "algorithm" is executed per timing run.
TIMINGS = 3 # Number of timing runs.
CHUNK_SIZE = KiB(8)
if BIG_TEST_FILE:
FILE_SIZE = KiB(1024) * BIG_TEST_FILE
else:
FILE_SIZE = SML_TEST_FILE # For quicker testing.
# Common setup for all algorithms -- prefixed to each algorithm's setup.
COMMON_SETUP = dedent("""
# Make accessible in algorithms.
from __main__ import array, deque, get_buffer_size, mmap, np, struct
from __main__ import ACCESS_READ, CHUNK_SIZE, FILE_SIZE, TEMP_FILENAME
from functools import partial
try:
xrange
except NameError: # Python 3
xrange = range
""")
def get_buffer_size(path):
""" Determine optimal buffer size for reading files. """
st = os.stat(path)
try:
bufsize = st.st_blksize # Available on some Unix systems (like Linux)
except AttributeError:
bufsize = io.DEFAULT_BUFFER_SIZE
return bufsize
# Utility primarily for use when embedding additional algorithms into benchmark.
VERIFY_NUM_READ = """
# Verify generator reads correct number of bytes (assumes values are correct).
bytes_read = sum(1 for _ in file_byte_iterator(TEMP_FILENAME))
assert bytes_read == FILE_SIZE, \
'Wrong number of bytes generated: got {:,} instead of {:,}'.format(
bytes_read, FILE_SIZE)
"""
TIMING = namedtuple('TIMING', 'label, exec_time')
class Algorithm(namedtuple('CodeFragments', 'setup, test')):
# Default timeit "stmt" code fragment.
_TEST = """
#for b in file_byte_iterator(TEMP_FILENAME): # Loop over every byte.
# pass # Do stuff with byte...
deque(file_byte_iterator(TEMP_FILENAME), maxlen=0) # Data sink.
"""
# Must overload __new__ because (named)tuples are immutable.
def __new__(cls, setup, test=None):
""" Dedent (unindent) code fragment string arguments.
Args:
`setup` -- Code fragment that defines things used by `test` code.
In this case it should define a generator function named
`file_byte_iterator()` that will be passed that name of a test file
of binary data. This code is not timed.
`test` -- Code fragment that uses things defined in `setup` code.
Defaults to _TEST. This is the code that's timed.
"""
test = cls._TEST if test is None else test # Use default unless one is provided.
# Uncomment to replace all performance tests with one that verifies the correct
# number of bytes values are being generated by the file_byte_iterator function.
#test = VERIFY_NUM_READ
return tuple.__new__(cls, (dedent(setup), dedent(test)))
algorithms = {
'Aaron Hall (Py 2 version)': Algorithm("""
def file_byte_iterator(path):
with open(path, "rb") as file:
callable = partial(file.read, 1024)
sentinel = bytes() # or b''
for chunk in iter(callable, sentinel):
for byte in chunk:
yield byte
"""),
"codeape": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
"""),
"codeape + iter + partial": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
for chunk in iter(partial(f.read, chunksize), b''):
for b in chunk:
yield b
"""),
"gerrit (struct)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
fmt = '{}B'.format(FILE_SIZE) # Reads entire file at once.
for b in struct.unpack(fmt, f.read()):
yield b
"""),
'Rick M. (numpy)': Algorithm("""
def file_byte_iterator(filename):
for byte in np.fromfile(filename, 'u1'):
yield byte
"""),
"Skurmedel": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
byte = f.read(1)
while byte:
yield byte
byte = f.read(1)
"""),
"Tcll (array.array)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
arr = array.array('B')
arr.fromfile(f, FILE_SIZE) # Reads entire file at once.
for b in arr:
yield b
"""),
"Vinay Sajip (read all into memory)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f:
bytes_read = f.read() # Reads entire file at once.
for b in bytes_read:
yield b
"""),
"Vinay Sajip (chunked)": Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
chunk = f.read(chunksize)
while chunk:
for b in chunk:
yield b
chunk = f.read(chunksize)
"""),
} # End algorithms
#
# Versions of algorithms that will only work in certain releases (or better) of Python.
#
if sys.version_info >= (3, 3):
algorithms.update({
'codeape + iter + partial + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
for chunk in iter(partial(f.read, chunksize), b''):
yield from chunk
"""),
'codeape + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
yield from chunk
else:
break
"""),
"jfs (mmap)": Algorithm("""
def file_byte_iterator(filename):
with open(filename, "rb") as f, \
mmap(f.fileno(), 0, access=ACCESS_READ) as s:
yield from s
"""),
'Rick M. (numpy) + "yield from"': Algorithm("""
def file_byte_iterator(filename):
# data = np.fromfile(filename, 'u1')
yield from np.fromfile(filename, 'u1')
"""),
'Vinay Sajip + "yield from"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
chunk = f.read(chunksize)
while chunk:
yield from chunk # Added in Py 3.3
chunk = f.read(chunksize)
"""),
}) # End Python 3.3 update.
if sys.version_info >= (3, 5):
algorithms.update({
'Aaron Hall + "yield from"': Algorithm("""
from pathlib import Path
def file_byte_iterator(path):
''' Given a path, return an iterator over the file
that lazily loads the file.
'''
path = Path(path)
bufsize = get_buffer_size(path)
with path.open('rb') as file:
reader = partial(file.read1, bufsize)
for chunk in iter(reader, bytes()):
yield from chunk
"""),
}) # End Python 3.5 update.
if sys.version_info >= (3, 8, 0):
algorithms.update({
'Vinay Sajip + "yield from" + "walrus operator"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while chunk := f.read(chunksize):
yield from chunk # Added in Py 3.3
"""),
'codeape + "yield from" + "walrus operator"': Algorithm("""
def file_byte_iterator(filename, chunksize=CHUNK_SIZE):
with open(filename, "rb") as f:
while chunk := f.read(chunksize):
yield from chunk
"""),
}) # End Python 3.8.0 update.update.
#### Main ####
def main():
global TEMP_FILENAME
def cleanup():
""" Clean up after testing is completed. """
try:
os.remove(TEMP_FILENAME) # Delete the temporary file.
except Exception:
pass
atexit.register(cleanup)
# Create a named temporary binary file of pseudo-random bytes for testing.
fd, TEMP_FILENAME = tempfile.mkstemp('.bin')
with os.fdopen(fd, 'wb') as file:
os.write(fd, bytearray(random.randrange(256) for _ in range(FILE_SIZE)))
# Execute and time each algorithm, gather results.
start_time = time.time() # To determine how long testing itself takes.
timings = []
for label in algorithms:
try:
timing = TIMING(label,
min(timeit.repeat(algorithms[label].test,
setup=COMMON_SETUP + algorithms[label].setup,
repeat=TIMINGS, number=EXECUTIONS)))
except Exception as exc:
print('{} occurred timing the algorithm: "{}"\n {}'.format(
type(exc).__name__, label, exc))
traceback.print_exc(file=sys.stdout) # Redirect to stdout.
sys.exit(1)
timings.append(timing)
# Report results.
print('Fastest to slowest execution speeds with {}-bit Python {}.{}.{}'.format(
64 if sys.maxsize > 2**32 else 32, *sys.version_info[:3]))
print(' numpy version {}'.format(np.version.full_version))
print(' Test file size: {:,} KiB'.format(FILE_SIZE // KiB(1)))
print(' {:,d} executions, best of {:d} repetitions'.format(EXECUTIONS, TIMINGS))
print()
longest = max(len(timing.label) for timing in timings) # Len of longest identifier.
ranked = sorted(timings, key=attrgetter('exec_time')) # Sort so fastest is first.
fastest = ranked[0].exec_time
for rank, timing in enumerate(ranked, 1):
print('{:<2d} {:>{width}} : {:8.4f} secs, rel speed {:6.2f}x, {:6.2f}% slower '
'({:6.2f} KiB/sec)'.format(
rank,
timing.label, timing.exec_time, round(timing.exec_time/fastest, 2),
round((timing.exec_time/fastest - 1) * 100, 2),
(FILE_SIZE/timing.exec_time) / KiB(1), # per sec.
width=longest))
print()
mins, secs = divmod(time.time()-start_time, 60)
print('Benchmark runtime (min:sec) - {:02d}:{:02d}'.format(int(mins),
int(round(secs))))
main()
Your DemoApplication
class is in the com.ag.digital.demo.boot
package and your LoginBean
class is in the com.ag.digital.demo.bean
package. By default components (classes annotated with @Component
) are found if they are in the same package or a sub-package of your main application class DemoApplication
. This means that LoginBean
isn't being found so dependency injection fails.
There are a couple of ways to solve your problem:
LoginBean
into com.ag.digital.demo.boot
or a sub-package.scanBasePackages
attribute of @SpringBootApplication
that should be on DemoApplication
.A few of other things that aren't causing a problem, but are not quite right with the code you've posted:
@Service
is a specialisation of @Component
so you don't need both on LoginBean
@RestController
is a specialisation of @Component
so you don't need both on DemoRestController
DemoRestController
is an unusual place for @EnableAutoConfiguration
. That annotation is typically found on your main application class (DemoApplication
) either directly or via @SpringBootApplication
which is a combination of @ComponentScan
, @Configuration
, and @EnableAutoConfiguration
.Instead of changing the ticks, why not change the units instead? Make a separate array X
of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel
to indicate the units (which should always be done anyways).
from pylab import *
# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)
# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X
subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")
subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")
show()
Best solution for me was restart adb server (while I have Enabled ADB integration in Android studio - Tools - Android - checked). To do this quickly I created adbr.bat
file inside android-sdk\platform-tools
directory (where is adb.exe
located) with this inside:
adb kill-server
adb start-server
Because I have this folder in PATH system variable, always when I need restart adb
from Android studio, I can write only into terminal adbr
and it is done.
Another option to do this is through Android Device Monitor in Devices tab - Menu after click on small arrow right - Reset adb.
HashMap
is an array of Entry
objects.
Consider HashMap
as just an array of objects.
Have a look at what this Object
is:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final int hash;
…
}
Each Entry
object represents a key-value pair. The field next
refers to another Entry
object if a bucket has more than one Entry
.
Sometimes it might happen that hash codes for 2 different objects are the same. In this case, two objects will be saved in one bucket and will be presented as a linked list.
The entry point is the more recently added object. This object refers to another object with the next
field and so on. The last entry refers to null
.
When you create a HashMap
with the default constructor
HashMap hashMap = new HashMap();
The array is created with size 16 and default 0.75 load balance.
hash % (arrayLength-1)
where element should be placed (bucket number)HashMap
, then value gets overwritten.If the bucket already has at least one element, a new one gets added and placed in the first position of the bucket. Its next
field refers to the old element.
hash % (arrayLength-1)
Entry
.
If a desired element is not found, return null
You can pass small bits of key/value pair data via the query string:
res.redirect('/?error=denied');
And javascript on the home page can access that and adjust its behavior accordingly.
Note that if you don't mind /category
staying as the URL in the browser address bar, you can just render directly instead of redirecting. IMHO many times people use redirects because older web frameworks made directly responding difficult, but it's easy in express:
app.post('/category', function(req, res) {
// Process the data received in req.body
res.render('home.jade', {error: 'denied'});
});
As @Dropped.on.Caprica commented, using AJAX eliminates the URL changing concern.
You don't need to apply corner radius to your app icon, you can just apply square icons. The device is automatically applying corner radius.
If you're already using jQuery, then you may want to have a look at jQuery.trim()
which is already provided with jQuery.
In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
As mentioned above by @Ricky vue-router automatically applies two active classes, .router-link-active
and .router-link-exact-active
, to the component.
So, to change active link css use:
.router-link-exact-active{
//your desired design when link is clicked
font-weight: 700;
}
If you have a Viewcontroller not using any storyboard/Xib, you can push to this particular VC like below call :
let vcInstance : UIViewController = yourViewController()
self.present(vcInstance, animated: true, completion: nil)
The spot you have commented as // Code to trig on item change...
will only trigger when the collection object gets changed, such as when it gets set to a new object, or set to null.
With your current implementation of TrulyObservableCollection, to handle the property changed events of your collection, register something to the CollectionChanged
event of MyItemsSource
public MyViewModel()
{
MyItemsSource = new TrulyObservableCollection<MyType>();
MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;
MyItemsSource.Add(new MyType() { MyProperty = false });
MyItemsSource.Add(new MyType() { MyProperty = true});
MyItemsSource.Add(new MyType() { MyProperty = false });
}
void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Handle here
}
Personally I really don't like this implementation. You are raising a CollectionChanged
event that says the entire collection has been reset, anytime a property changes. Sure it'll make the UI update anytime an item in the collection changes, but I see that being bad on performance, and it doesn't seem to have a way to identify what property changed, which is one of the key pieces of information I usually need when doing something on PropertyChanged
.
I prefer using a regular ObservableCollection
and just hooking up the PropertyChanged
events to it's items on CollectionChanged
. Providing your UI is bound correctly to the items in the ObservableCollection
, you shouldn't need to tell the UI to update when a property on an item in the collection changes.
public MyViewModel()
{
MyItemsSource = new ObservableCollection<MyType>();
MyItemsSource.CollectionChanged += MyItemsSource_CollectionChanged;
MyItemsSource.Add(new MyType() { MyProperty = false });
MyItemsSource.Add(new MyType() { MyProperty = true});
MyItemsSource.Add(new MyType() { MyProperty = false });
}
void MyItemsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach(MyType item in e.NewItems)
item.PropertyChanged += MyType_PropertyChanged;
if (e.OldItems != null)
foreach(MyType item in e.OldItems)
item.PropertyChanged -= MyType_PropertyChanged;
}
void MyType_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyProperty")
DoWork();
}
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
I fell into this dilemma once, and researched quite a bit on google for opinions. What I found was that indeed many see saving images to disk better for larger images, while mySQL allows for easier access, specially from languages like PHP.
I found a similar question
MySQL BLOB vs File for Storing Small PNG Images?
My final verdict was that for things such as a profile picture, just a small square image that needs to be there per user, mySQL would be better than storing a bunch of thumbs in the hdd, while for photo albums and things like that, folders/image files are better.
Hope it helps
Because you have to have an index on a foreign key field you can just create a simple index on the field 'AID'
CREATE INDEX aid_index ON mytable (AID);
and only then drop the unique index 'AID'
ALTER TABLE mytable DROP INDEX AID;
De Morgan's laws allow us to convert disjunctions ("OR") into logical equivalents using only conjunctions ("AND") and negations ("NOT"). This means we can chain disjunctions ("OR") on to one line.
This means if name is "Yakko" or "Wakko" or "Dot", then echo "Warner brother or sister".
set warner=true
if not "%name%"=="Yakko" if not "%name%"=="Wakko" if not "%name%"=="Dot" set warner=false
if "%warner%"=="true" echo Warner brother or sister
This is another version of paxdiablo's "OR" example, but the conditions are chained on to one line. (Note that the opposite of leq
is gtr
, and the opposite of geq
is lss
.)
set res=true
if %hour% gtr 6 if %hour% lss 22 set res=false
if "%res%"=="true" set state=asleep
querySelector()
matched the id in document. You must write id of password in .html
Then pass it to querySelector()
with #symbol & .value property
.
Example:
let myVal = document.querySelector('#pwd').value
If you are able to add external libs to your project. I would recommend that you try out Joda-time. It has a very clever way of working with dates.
You can use git show
with a path from the root of the repository (./
or ../
for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION
with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c
from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show
.
Try to pass the serializable list using Bundle.Serializable:
Bundle bundle = new Bundle();
bundle.putSerializable("value", all_thumbs);
intent.putExtras(bundle);
And in SomeClass Activity get it as:
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
List<Thumbnail> thumbs=
(List<Thumbnail>)bundle.getSerializable("value");
Using Array.from, Array.prototype.forEach(), and arrow functions:
Iterate over the keys:
Array.from(myMap.keys()).forEach(key => console.log(key));
Iterate over the values:
Array.from(myMap.values()).forEach(value => console.log(value));
Iterate over the entries:
Array.from(myMap.entries()).forEach(entry => console.log('Key: ' + entry[0] + ' Value: ' + entry[1]));
I think the answer is incorrectly chosen, that method gives seconds, not milliseconds.
t = Time.now.to_f
=> 1382471965.146
Here I suppose the floating value are the milliseconds
It's perfectly normal in Javascript (and many languages) to have functions inside functions.
Take the time to learn the language, don't use it on the basis that it's similar to what you already know. I'd suggest watching Douglas Crockford's series of YUI presentations on Javascript, with special focus on Act III: Function the Ultimate (link to video download, slides, and transcript)
Now I've found the problem.
Removing the obj_exception_throw
from my breakpoints solved this. Now it's caught by the @try
block and also, NSSetUncaughtExceptionHandler
will handle this if a @try
block is missing.
In case you want to remove elements which are added dynamically try this:
document.body.addEventListener('DOMSubtreeModified', function(event) {
const elements = document.getElementsByClassName('your-class-name');
while (elements.length > 0) elements[0].remove();
});
Use display instead of visibility. display: none for invisible and no setting for visible.
You can do this using -T
option in cp
.
See Man page for cp
.
-T, --no-target-directory
treat DEST as a normal file
So as per your example, following is the file structure.
$ tree test
test
|-- bar
| |-- a
| `-- b
`-- foo
|-- a
`-- b
2 directories, 4 files
You can see the clear difference when you use -v
for Verbose.
When you use just -R
option.
$ cp -Rv foo/ bar/
`foo/' -> `bar/foo'
`foo/b' -> `bar/foo/b'
`foo/a' -> `bar/foo/a'
$ tree
|-- bar
| |-- a
| |-- b
| `-- foo
| |-- a
| `-- b
`-- foo
|-- a
`-- b
3 directories, 6 files
When you use the option -T
it overwrites the contents, treating the destination like a normal file and not directory.
$ cp -TRv foo/ bar/
`foo/b' -> `bar/b'
`foo/a' -> `bar/a'
$ tree
|-- bar
| |-- a
| `-- b
`-- foo
|-- a
`-- b
2 directories, 4 files
This should solve your problem.
In most housing services just add in the .htaccess on the target server folder this:
Header set Access-Control-Allow-Origin 'https://your.site.folder'
{
/your/first/command
/your/second/command
} &> /dev/null
To eliminate output from commands, you have two options:
Close the output descriptor file, which keeps it from accepting any more input. That looks like this:
your_command "Is anybody listening?" >&-
Usually, output goes either to file descriptor 1 (stdout) or 2 (stderr). If you close a file descriptor, you'll have to do so for every numbered descriptor, as &>
(below) is a special BASH syntax incompatible with >&-
:
/your/first/command >&- 2>&-
Be careful to note the order: >&-
closes stdout, which is what you want to do; &>-
redirects stdout and stderr to a file named -
(hyphen), which is not what what you want to do. It'll look the same at first, but the latter creates a stray file in your working directory. It's easy to remember: >&2
redirects stdout to descriptor 2 (stderr), >&3
redirects stdout to descriptor 3, and >&-
redirects stdout to a dead end (i.e. it closes stdout).
Also beware that some commands may not handle a closed file descriptor particularly well ("write error: Bad file descriptor"), which is why the better solution may be to...
Redirect output to /dev/null
, which accepts all output and does nothing with it. It looks like this:
your_command "Hello?" > /dev/null
For output redirection to a file, you can direct both stdout and stderr to the same place very concisely, but only in bash:
/your/first/command &> /dev/null
Finally, to do the same for a number of commands at once, surround the whole thing in curly braces. Bash treats this as a group of commands, aggregating the output file descriptors so you can redirect all at once. If you're familiar instead with subshells using ( command1; command2; )
syntax, you'll find the braces behave almost exactly the same way, except that unless you involve them in a pipe the braces will not create a subshell and thus will allow you to set variables inside.
{
/your/first/command
/your/second/command
} &> /dev/null
See the bash manual on redirections for more details, options, and syntax.
The most common issue is misconfiguration of your JAVA_HOME
variable which should point to the right Java Development Kit library, if you've multiple installed.
To find where SDK Java folder is located, run the following commands:
jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));'
To check which java (openjdk) you've installed, check via:
dpkg -l "openjdk*" | grep ^i
or:
update-java-alternatives -l
To change it, use:
update-alternatives --config java
Prefix with sudo
if required.
to select the alternative java version.
Or check which are available for install:
apt-cache search ^openjdk
Prefix with sudo
if required.
Then you can install, for example:
apt-get install openjdk-7-jre
Prefix with sudo
if required.
Install/upgrade appropriate package via:
yum install java-1.7.0-openjdk java-1.7.0-openjdk-devel
The
java-1.7.0-openjdk
package contains just the Java Runtime Environment. If you want to develop Java programs then install thejava-1.7.0-openjdk-devel
package.
There is an OpenJDK 7 package in the FreeBSD Ports collection called openjdk7 which probably needs to be reconfigured.
See: OpenJDK wiki page.
Just install appropriate Java SE Development Kit library from the Oracle site or install
If you're experiencing this issue with Jenkins, see:
However selecting the right version of Java (newer) with update-alternatives
should work.
How about alias gcc99= gcc -std=c99
?
As of Bootstrap 3.x, there's an example of this in the docs here: http://getbootstrap.com/components/#input-groups-buttons-dropdowns
<div class="input-group">
<input type="text" class="form-control" aria-label="...">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Action <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div><!-- /btn-group -->
</div><!-- /input-group -->
The easiest way to do this is to click on the Terminate button(red square) in the console:
Use a Border
control outside the cell control and define the padding for that:
<Grid>
<Grid.Resources >
<Style TargetType="Border" >
<Setter Property="Padding" Value="5,5,5,5" />
</Style>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Grid.Column="0">
<YourGridControls/>
</Border>
<Border Grid.Row="1" Grid.Column="0">
<YourGridControls/>
</Border>
</Grid>
Source:
All above answers perfectly gives the solution to center the form using Bootstrap 4
. However, if someone wants to use out of the box Bootstrap 4
css classes without help of any additional styles and also not wanting to use flex
, we can do like this.
A sample form
HTML
<div class="container-fluid h-100 bg-light text-dark">
<div class="row justify-content-center align-items-center">
<h1>Form</h1>
</div>
<hr/>
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
<form action="">
<div class="form-group">
<select class="form-control">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" />
</div>
<div class="form-group text-center">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 1
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 2
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio" disabled>Option 3
</label>
</div>
</div>
<div class="form-group">
<div class="container">
<div class="row">
<div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
<div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Link to CodePen
https://codepen.io/anjanasilva/pen/WgLaGZ
I hope this helps someone. Thank you.
If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's "Wrong" or anything, but anything involving reflection is generally less obvious and less clear.
You can achieve this with a conditional in an angular expression, such as:
<a href="#" class="{{ condition ? 'active' : '' }}">link</a>
That being said, I do find an angular directive to be the more "proper" way of doing it, even though outsourcing a lot of this mini-logic can somewhat pollute your code base.
I use conditionals for GUI styling every once in a while during development, because it's a little quicker than creating directives. I couldn't tell you an instance though in which they actually remained in the code base for long. In the end I either turn it into a directive or find a better way to solve the problem.
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
It seems like you are essentially looking into computing the z-score or standard score of your data, which is calculated through the formula: z = (x-mean(x))/std(x)
This should work:
%% Original data (Normal with mean 1 and standard deviation 2)
x = 1 + 2*randn(100,1);
mean(x)
var(x)
std(x)
%% Normalized data with mean 0 and variance 1
z = (x-mean(x))/std(x);
mean(z)
var(z)
std(z)
you can enable "Instant Run" on Android Studio to get multidex support.
In some browsers you will face problems if you are not giving an href attribute. I suggest you to write your code something like this:
<a href="#" onclick="yourcode();return false;">Link</a>
you can replace yourcode() with your own function or logic,but do remember to add return false; statement at the end.
The problem by using stream().forEach(..)
with a call to add
or put
inside the forEach
(so you mutate the external myMap
or myList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.
One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.
Map<Boolean, List<Map.Entry<K, V>>> partitions =
animalMap.entrySet()
.stream()
.collect(partitioningBy(e -> e.getValue() == null));
Map<K, V> myMap =
partitions.get(false)
.stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
List<K> myList =
partitions.get(true)
.stream()
.map(Map.Entry::getKey)
.collect(toList());
... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2>
class exists, you can create your own), e.g:
public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
return Collector.of(
() -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
(pair, entry) -> {
if(entry.getValue() == null) {
pair._2.add(entry.getKey());
} else {
pair._1.put(entry.getKey(), entry.getValue());
}
},
(p1, p2) -> {
p1._1.putAll(p2._1);
p1._2.addAll(p2._2);
return p1;
});
}
with its usage:
Tuple2<Map<K, V>, List<K>> pair =
animalMap.entrySet().parallelStream().collect(customCollector());
You can tune it more if you want, for example by providing a predicate as parameter.
You can add a android:layoutAnimation="@anim/rv_item_animation"
attribute to RecyclerView
like this:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutAnimation="@anim/layout_animation_fall_down"
/>
thanks for the excellent article here: https://proandroiddev.com/enter-animation-using-recyclerview-and-layoutanimation-part-1-list-75a874a5d213
If your source-file is already utf8 then drop the utf8_* functions. php5 is storing strings as array of byte.
you should add a meta tag for encoding within the html AND you should add an http header which sets the transferencoding to utf-8.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and in php
<?php
header('Content-Type: text/html; charset=utf-8');
If what you are trying to do is to split a string into several lines, you can use a backslash:
$ a="hello\
> world"
$ echo $a
helloworld
With one space in between:
$ a="hello \
> world"
$ echo $a
hello world
This one also adds only one space in between:
$ a="hello \
> world"
$ echo $a
hello world
mydata$sCode == "CA"
will return a boolean array, with a TRUE
value everywhere that the condition is met. To illustrate:
> mydata = data.frame(sCode = c("CA", "CA", "AC"))
> mydata$sCode == "CA"
[1] TRUE TRUE FALSE
There are a couple of ways to deal with this:
sum(mydata$sCode == "CA")
, as suggested in the comments; because
TRUE
is interpreted as 1 and FALSE
as 0, this should return the
numer of TRUE
values in your vector.
length(which(mydata$sCode == "CA"))
; the which()
function
returns a vector of the indices where the condition is met, the
length of which is the count of "CA"
.
Edit to expand upon what's happening in #2:
> which(mydata$sCode == "CA")
[1] 1 2
which()
returns a vector identify each column where the condition is met (in this case, columns 1 and 2 of the dataframe). The length()
of this vector is the number of occurences.
"margin: 0 auto" only centers an element in IE if the parent element has a "text-align: center".
Squash commits locally with
git rebase -i origin/master~4 master
and then force push with
git push origin +master
--force
and +
From the documentation of git push
:
Note that
--force
applies to all the refs that are pushed, hence using it withpush.default
set tomatching
or with multiple push destinations configured withremote.*.push
may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart). To force a push to only one branch, use a+
in front of the refspec to push (e.ggit push origin +master
to force a push to themaster
branch).
You are looking for System.Reflection.Assembly.GetExecutingAssembly()
string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string xmlFileName = Path.Combine(assemblyFolder,"AggregatorItems.xml");
Note:
The .Location
property returns the location of the currently running DLL file.
Under some conditions the DLL is shadow copied before execution, and the .Location
property will return the path of the copy. If you want the path of the original DLL, use the Assembly.GetExecutingAssembly().CodeBase
property instead.
.CodeBase
contains a prefix (file:\
), which you may need to remove.
I believe that a much more reliable way to detect mobile devices is to look at the navigator.userAgent string. For example, on my iPhone the user agent string is:
Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1
Note that this string contains two telltale keywords: iPhone and Mobile. Other user agent strings for devices that I don't have are provided at:
https://deviceatlas.com/blog/list-of-user-agent-strings
Using this string, I set a JavaScript Boolean variable bMobile on my website to either true or false using the following code:
var bMobile = // will be true if running on a mobile device
navigator.userAgent.indexOf( "Mobile" ) !== -1 ||
navigator.userAgent.indexOf( "iPhone" ) !== -1 ||
navigator.userAgent.indexOf( "Android" ) !== -1 ||
navigator.userAgent.indexOf( "Windows Phone" ) !== -1 ;
mariofertc completely solved this for me here are his steps:
Verify mysql's data directory is empty (before you delete it though, save the err file for your records).
Under the mysql bin path run: mysqld.exe --initialize-insecure
add to my.ini (mysql's configuration file) the following: [mysqld] default_authentication_plugin=mysql_native_password
Then check services (via task manager) to make sure MySql is running, if not - right click MySql and start it.
I'll also note, if you don't have your mysql configuration file in the mysql bin and can't find it via the windows search, you will want to look for it in C:\Program Data\Mysql\ Note that it might be a different name other than my.ini, like a template, as Heesu mentions here: Can't find my.ini (mysql 5.7) Just find the template that matches the version of your mysql via the command mysql --version
For install with zsh and Homebrew:
brew install nvm
Then Add the following to ~/.zshrc or your desired shell configuration file:
export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"
Then install a node version and use it.
nvm install 7.10.1
nvm use 7.10.1
It's quite easy and efficient to use Excel as a reporting tool for Access data.
A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:
strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst
That's it !
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2
I hope I am not adding something obvious, but I have been struggling with Django, Ajax, and JSON on this.
Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.
So I agree with ady, but with some care.
My bottom line is:
In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.
My simple case was:
tbox.innerHTML = tbox.innerHTML + '<div class="thisbox_des" style="width:210px;" onmouseout="clear()"><a href="/this/thislist/'
+ myThis[i].pk +'"><img src="/site_media/'
+ myThis[i].fields.thumbnail +'" height="80" width="80" style="float:left;" onmouseover="showThis('
+ myThis[i].fields.left +','
+ myThis[i].fields.right +',\''
+ myThis[i].fields.title +'\')"></a><p style="float:left;width:130px;height:80px;"><b>'
+ myThis[i].fields.title +'</b> '
+ myThis[i].fields.description +'</p></div>'
You can spot the ' in the third field of showThis.
The double quote didn't work!
It is clear why, but it is also clear why we should stick to single quotes... I guess...
This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.
So to answer the question:
Try to use single quotes while within HTML. It might save a couple of debug issues...