Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
.required label {
font-weight: bold;
}
.required label:after {
color: #e32;
content: ' *';
display:inline;
}
Fiddle with your exact structure: http://jsfiddle.net/bQ859/
Check whether your app has the needed permissions.I was also getting the same error and I checked the logcat debug log which showed this:
04-15 13:38:25.387: E/AndroidRuntime(694): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:555-555-5555 cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{44068640 694:rahulserver.test/10055} (pid=694, uid=10055) requires android.permission.CALL_PHONE
I then gave the needed permission in my android-manifest which worked for me.
rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).
Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/
I did not need to compile OpenCV with ffmpg support.
This worked for me:
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(false) <-- not necessary but useful!
.build();
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
First of all disable child views autoresizing
UIView *view1, *view2;
[childview setTranslatesAutoresizingMaskIntoConstraints:NO];
If you are UIView+Autolayout or Purelayout:
[view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
[view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
If you are using only UIKit level autolayout methods:
[view1 addConstraints:({
@[ [NSLayoutConstraint
constraintWithItem:view1
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeCenterX
multiplier:1.f constant:0.f],
[NSLayoutConstraint
constraintWithItem:view1
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:view2
attribute:NSLayoutAttributeCenterY
multiplier:1.f constant:0.f] ];
})];
I prefer:
UIView *parentView, *childView;
[childView setFrame:({
CGRect frame = childView.frame;
frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;
CGRectIntegral(frame);
})];
Swift 3.0 version
let arr = yourString.components(separatedBy: "/")
let month = arr[0]
Unit testing is usually done by the developers side, whereas testers are partly evolved in this type of testing where testing is done unit by unit. In Java JUnit test cases can also be possible to test whether the written code is perfectly designed or not.
This type of testing is possible after the unit testing when all/some components are integrated. This type of testing will make sure that when components are integrated, do they affect each others' working capabilities or functionalities?
This type of testing is done at the last when system is integrated successfully and ready to go on production server.
This type of testing will make sure that every important functionality from start to end is working fine and system is ready to deploy on production server.
This type of testing is important to test that unintended/unwanted defects are not present in the system when developer fixed some issues. This testing also make sure that all the bugs are successfully solved and because of that no other issues are occurred.
I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:
Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':
ssh-keygen -t rsa -C "[email protected]"
Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:
# Default GitHub
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
# Work GitHub
Host work.github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_work
Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:
$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)
If your entries aren't there then run:
ssh-add ~/.ssh/id_rsa_work
Step 4: test
To test you've done this all correctly, I suggest the following quick check:
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.
Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)
private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)
{
FileInfo[] files = directoryInfo.GetFiles();
List<FileInfo> lastUpdatedFile = null;
DateTime lastUpdate = new DateTime(1, 0, 0);
foreach (FileInfo file in files)
{
if (file.LastAccessTime > lastUpdate)
{
lastUpdatedFile.Add(file);
lastUpdate = file.LastAccessTime;
}
}
return lastUpdatedFile;
}
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation
).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
Assuming you are decoding or encoding xml and using JAXB
, then it's possible to replace the dateTime binding entirely and use something else than `XMLGregorianCalendar' for every date in the schema.
In that way you can have JAXB
do the repetitive stuff while you can spend the time on writing awesome code that delivers value.
Example for a jodatime DateTime
: (Doing this with java.util.Date would also work - but with certain limitations. I prefer jodatime and it's copied from my code so I know it works...)
<jxb:globalBindings>
<jxb:javaType name="org.joda.time.LocalDateTime" xmlType="xs:dateTime"
parseMethod="test.util.JaxbConverter.parseDateTime"
printMethod="se.seb.bis.test.util.JaxbConverter.printDateTime" />
<jxb:javaType name="org.joda.time.LocalDate" xmlType="xs:date"
parseMethod="test.util.JaxbConverter.parseDate"
printMethod="test.util.JaxbConverter.printDate" />
<jxb:javaType name="org.joda.time.LocalTime" xmlType="xs:time"
parseMethod="test.util.JaxbConverter.parseTime"
printMethod="test.util.JaxbConverter.printTime" />
<jxb:serializable uid="2" />
</jxb:globalBindings>
And the converter:
public class JaxbConverter {
static final DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
static final DateTimeFormatter df = ISODateTimeFormat.date();
static final DateTimeFormatter tf = ISODateTimeFormat.time();
public static LocalDateTime parseDateTime(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
LocalDateTime r = dtf.parseLocalDateTime(s);
return r;
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printDateTime(LocalDateTime d) {
try {
if (d == null)
return null;
return dtf.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static LocalDate parseDate(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
return df.parseLocalDate(s);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printDate(LocalDate d) {
try {
if (d == null)
return null;
return df.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static String printTime(LocalTime d) {
try {
if (d == null)
return null;
return tf.print(d);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static LocalTime parseTime(String s) {
try {
if (StringUtils.trimToEmpty(s).isEmpty())
return null;
return df.parseLocalTime(s);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
See here: how replace XmlGregorianCalendar by Date?
If you are happy to just map to an instant based on the timezone+timestamp, and the original timezone is not really relevant, then java.util.Date
is probably fine too.
decoration: InputDecoration(
border:OutLineInputBorder(
borderSide:BorderSide.none
bordeRadius: BordeRadius.circular(20.0)
)
)
Sharing my notes which I usually maintain while reading from Internet, I hope it may be helpful to someone
Candidate keys are those keys which is candidate for primary key of a table. In simple words we can understand that such type of keys which full fill all the requirements of primary key which is not null and have unique records is a candidate for primary key. So thus type of key is known as candidate key. Every table must have at least one candidate key but at the same time can have several.
Such type of candidate key which is chosen as a primary key for table is known as primary key. Primary keys are used to identify tables. There is only one primary key per table. In SQL Server when we create primary key to any table then a clustered index is automatically created to that column.
Foreign key are those keys which is used to define relationship between two tables. When we want to implement relationship between two tables then we use concept of foreign key. It is also known as referential integrity. We can create more than one foreign key per table. Foreign key is generally a primary key from one table that appears as a field in another where the first table has a relationship to the second. In other words, if we had a table A with a primary key X that linked to a table B where X was a field in B, then X would be a foreign key in B.
If any table have more than one candidate key, then after choosing primary key from those candidate key, rest of candidate keys are known as an alternate key of that table. Like here we can take a very simple example to understand the concept of alternate key. Suppose we have a table named Employee which has two columns EmpID and EmpMail, both have not null attributes and unique value. So both columns are treated as candidate key. Now we make EmpID as a primary key to that table then EmpMail is known as alternate key.
When we create keys on more than one column then that key is known as composite key. Like here we can take an example to understand this feature. I have a table Student which has two columns Sid and SrefNo and we make primary key on these two column. Then this key is known as composite key.
A natural key is one or more existing data attributes that are unique to the business concept. For the Customer table there was two candidate keys, in this case CustomerNumber and SocialSecurityNumber. Link http://www.agiledata.org/essays/keys.html
Introduce a new column, called a surrogate key, which is a key that has no business meaning. An example of which is the AddressID column of the Address table in Figure 1. Addresses don't have an "easy" natural key because you would need to use all of the columns of the Address table to form a key for itself (you might be able to get away with just the combination of Street and ZipCode depending on your problem domain), therefore introducing a surrogate key is a much better option in this case. Link http://www.agiledata.org/essays/keys.html
A unique key is a superkey--that is, in the relational model of database organization, a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set
When more than one column is combined to form a unique key, their combined value is used to access each row and maintain uniqueness. These keys are referred to as aggregate or compound keys. Values are not combined, they are compared using their data types.
Simple key made from only one attribute.
A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. Equivalently a super key can also be defined as a set of attributes of a relvar upon which all attributes of the relvar are functionally dependent.
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
When you do len(df['column name'])
you are just getting one number, namely the number of rows in the DataFrame (i.e., the length of the column itself). If you want to apply len
to each element in the column, use df['column name'].map(len)
. So try
df[df['column name'].map(len) < 2]
function readFromRegistry (strRegistryKey, strDefault )
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )
if err.number <> 0 then
readFromRegistry= strDefault
else
readFromRegistry=value
end if
set WSHShell = nothing
end function
Usage :
str = readfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
wscript.echo "returned " & str
You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
call :treeProcess
goto :eof
:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
cd %%d
call :treeProcess
cd ..
)
exit /b
Windows Batch File Looping Through Directories to Process Files?
In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj)
in your ModelForm.save
override, as ModelForm.save
later populates your m2m from self.cleaned_data['my_m2m']
which overwrites your changes. Instead call:
my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms
(It is fine to convert the incoming QuerySet to a list - the ManyToManyField
does that anyway.)
On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu
will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu
section, ie:
sysctl -a | grep machdep.cpu
In particular, for processors with HyperThreading
(HT), you'll see the total enumerated CPU count (logical_per_package
) as double that of the physical core count (cores_per_package
).
sysctl -a | grep machdep.cpu | grep per_package
If you are using Java 6 or higher you can use wildcards of this form:
java -classpath ".;c:\mylibs\*;c:\extlibs\*" MyApp
If you would like to add all subdirectories: lib\a\, lib\b\, lib\c\, there is no mechanism for this in except:
java -classpath ".;c:\lib\a\*;c:\lib\b\*;c:\lib\c\*" MyApp
There is nothing like lib\*\*
or lib\**
wildcard for the kind of job you want to be done.
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
Depending on what you plan to do with your sentence-as-a-list, you may want to look at the Natural Language Took Kit. It deals heavily with text processing and evaluation. You can also use it to solve your problem:
import nltk
words = nltk.word_tokenize(raw_sentence)
This has the added benefit of splitting out punctuation.
Example:
>>> import nltk
>>> s = "The fox's foot grazed the sleeping dog, waking it."
>>> words = nltk.word_tokenize(s)
>>> words
['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',',
'waking', 'it', '.']
This allows you to filter out any punctuation you don't want and use only words.
Please note that the other solutions using string.split()
are better if you don't plan on doing any complex manipulation of the sentence.
[Edited]
This should print out all Parameters that start with "Question".
<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
Enumeration parameterList = request.getParameterNames();
while( parameterList.hasMoreElements() )
{
String sName = parameterList.nextElement().toString();
if(sName.toLowerCase.startsWith("question")){
String[] sMultiple = request.getParameterValues( sName );
if( 1 >= sMultiple.length )
// parameter has a single value. print it.
out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
else
for( int i=0; i<sMultiple.length; i++ )
// if a paramater contains multiple values, print all of them
out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
}
}
%>
</body></html>
I'm not fully sure that this is what you're looking for, but if your question is how to read an integer using <stdio.h>
, then the proper syntax is
int myInt;
scanf("%d", &myInt);
You'll need to do a lot of error-handling to ensure that this works correctly, of course, but this should be a good start. In particular, you'll need to handle the cases where
stdin
file is closed or broken, so you get nothing at all.To check for this, you can capture the return code from scanf
like this:
int result = scanf("%d", &myInt);
If stdin
encounters an error while reading, result
will be EOF
, and you can check for errors like this:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
If, on the other hand, the user enters something invalid, like a garbage text string, then you need to read characters out of stdin
until you consume all the offending input. You can do this as follows, using the fact that scanf
returns 0 if nothing was read:
int myInt;
int result = scanf("%d", &myInt);
if (result == EOF) {
/* ... you're not going to get any input ... */
}
if (result == 0) {
while (fgetc(stdin) != '\n') // Read until a newline is found
;
}
Hope this helps!
EDIT: In response to the more detailed question, here's a more appropriate answer. :-)
The problem with this code is that when you write
printf("got the number: %d", scanf("%d", &x));
This is printing the return code from scanf
, which is EOF
on a stream error, 0
if nothing was read, and 1
otherwise. This means that, in particular, if you enter an integer, this will always print 1
because you're printing the status code from scanf
, not the number you read.
To fix this, change this to
int x;
scanf("%d", &x);
/* ... error checking as above ... */
printf("got the number: %d", x);
Hope this helps!
Simple way: Use file_get_contents()
:
$page = file_get_contents('http://stackoverflow.com/questions/ask');
Please note that allow_url_fopen
must be true
in you php.ini
to be able to use URL-aware fopen wrappers.
More advanced way: If you cannot change your PHP configuration, allow_url_fopen
is false
by default and if ext/curl is installed, use the cURL
library to connect to the desired page.
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationThis is something I've also been struggling with for my own images. I have a server environment from which I create a Docker image. When I update the server, I'd like all users who are running containers based on my Docker image to be able to upgrade to the latest server.
Ideally, I'd prefer to generate a new version of the Docker image and have all containers based on a previous version of that image automagically update to the new image "in place." But this mechanism doesn't seem to exist.
So the next best design I've been able to come up with so far is to provide a way to have the container update itself--similar to how a desktop application checks for updates and then upgrades itself. In my case, this will probably mean crafting a script that involves Git pulls from a well-known tag.
The image/container doesn't actually change, but the "internals" of that container change. You could imagine doing the same with apt-get, yum, or whatever is appropriate for you environment. Along with this, I'd update the myserver:latest image in the registry so any new containers would be based on the latest image.
I'd be interested in hearing whether there is any prior art that addresses this scenario.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/>
button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )
btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs
You have many solutions to that error.
You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity
If you want use ActionbarActivity or AppCompatActivity, you should change in styles.xml Theme.Holo.xxxx to Theme.AppCompat.Light (if necessary add to DarkActionbar)
If you don't need advanced attributes about action bar or AppCompat you don't need to use Actionbar or AppCompat.
More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):
from datetime import datetime
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
time2 = datetime.strftime('19 01 2021', '%d %m %Y')
difference = time2 - time1
difference_in_seconds = difference.total_seconds()
You get that error because ASP.NET MVC cannot find an id parameter value to provide for the id parameter of your action method.
You need to either pass that as part of the url, ("/Home/Edit/123"), as a query string parameter ("/Home/Edit?id=123") or as a POSTed parameter (make sure to have something like <input type="hidden" name="id" value="123" />
in your HTML form).
Alternatively, you could make the id
parameter be a nullable int (Edit(int? id, User collection) {...}
), but if the id were null, you wouldn't know what to edit.
I was experiencing this issue on a drupal site and none of the other solutions in this thread helped. After some troubleshooting I found the local.settings.php had a closing tag with a space after it like so:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
?>
Updating local.settings.php to the following resolved:
<?php
$databases = array(
'default' =>
array (
'default' =>
array (
'driver' => 'mysql',
'database' => 'xxx',
'username' => 'xxx',
'password' => 'xxx',
'port' => '',
'host' => 'xxx',
),
),
);
The closing "?>" PHP tag is not necessary here. If you choose to use a closing tag you must ensure there are no characters / whitespace after it.
I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.
If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.
However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:
import StringIO
s = StringIO.StringIO(myString)
for line in s:
do_something_with(line)
Do the following steps to resolve the issue
In Storyboard, select any view, then go to the File inspector. Uncheck the "Use Size Classes", you will ask to keep size class data for: iPhone/iPad. And then Click the "Disable Size Classes" button. Doing this will make the storyboard's view size with selected device.
You don't free anything at all. Since you never acquired any resources dynamically, there is nothing you have to, or even are allowed to, free.
(It's the same as when you say int n = 10;
: There are no dynamic resources involved that you have to manage manually.)
Yes, use %f
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* @return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta']; $to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC']; datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
FWIW, the following line works in windows and replaces semicolons in my path variables with a newline. I'm using the tools installed under my git bin directory.
echo %path% | sed -e $'s/;/\\n/g' | less
There is a new NuGet package that contains the System.Windows.Interactivity.dll that is compatible with:
To install Expression.Blend.Sdk, run the following command in the Package Manager Console
PM> Install-Package Expression.Blend.Sdk
An alternative to TikaEncodingDetector is to use Tika AutoDetectReader.
Charset charset = new AutoDetectReader(new FileInputStream(file)).getCharset();
You do not need to interact with managed code, as you can use LIKE:
CREATE TABLE #Sample(Field varchar(50), Result varchar(50))
GO
INSERT INTO #Sample (Field, Result) VALUES ('ABC123 ', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123.', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123&', 'Match')
SELECT * FROM #Sample WHERE Field LIKE '%[^a-z0-9 .]%'
GO
DROP TABLE #Sample
As your expression ends with +
you can go with '%[^a-z0-9 .][^a-z0-9 .]%'
EDIT:
To make it clear: SQL Server doesn't support regular expressions without managed code. Depending on the situation, the LIKE
operator can be an option, but it lacks the flexibility that regular expressions provides.
The number of groups of logical processors sharing a single processor core. (Using GetLogicalProcessorInformationEx, see GetLogicalProcessorInformation as well)
size_t NumberOfPhysicalCores() noexcept {
DWORD length = 0;
const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);
assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);
std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);
const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info =
reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());
const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);
assert(result_second != FALSE);
size_t nb_physical_cores = 0;
size_t offset = 0;
do {
const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =
reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);
offset += current_info->Size;
++nb_physical_cores;
} while (offset < length);
return nb_physical_cores;
}
Note that the implementation of NumberOfPhysicalCores
is IMHO far from trivial (i.e. "use GetLogicalProcessorInformation
or GetLogicalProcessorInformationEx
"). Instead it is rather subtle if one reads the documentation (explicitly present for GetLogicalProcessorInformation
and implicitly present for GetLogicalProcessorInformationEx
) at MSDN.
The number of logical processors. (Using GetSystemInfo)
size_t NumberOfSystemCores() noexcept {
SYSTEM_INFO system_info;
ZeroMemory(&system_info, sizeof(system_info));
GetSystemInfo(&system_info);
return static_cast< size_t >(system_info.dwNumberOfProcessors);
}
Note that both methods can easily be converted to C/C++98/C++03.
Another possibility, if using the -o
(output file) option - the destination directory does not exist.
eg. if you have -o /tmp/download/abc.txt
and /tmp/download does not exist.
Hence, ensure any required directories are created/exist beforehand, use the --create-dirs
option as well as -o
if necessary
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");
First, an apk file is just a modified jar file. So the real question is can they decompile the dex files inside. The answer is sort of. There are already disassemblers, such as dedexer and smali. You can expect these to only get better, and theoretically it should eventually be possible to decompile to actual Java source (at least sometimes). See the previous question decompiling DEX into Java sourcecode.
What you should remember is obfuscation never works. Choose a good license and do your best to enforce it through the law. Don't waste time with unreliable technical measures.
This problem mainly happens when you are using connection pooling because when you close connection that connection go back to the connection pool and all cursor associated with that connection never get closed as the connection to database is still open. So one alternative is to decrease the idle connection time of connections in pool, so may whenever connection sits idle in connection for say 10 sec , connection to database will get closed and new connection created to put in pool.
Its due to a conflict.
Clear all keys from ssh-agent
ssh-add -d ~/.ssh/id_rsa
ssh-add -d ~/.ssh/github
Add the github ssh key
ssh-add ~/.ssh/github
It should work now.
This works in Windows; didn't check Linux but don't see why it wouldn't work. Download the zip files for 5.6.8 portable. Unzip the files and copy the xampp/htdocs to the xampp/htdocs in your install directory.
As I know the way you can do it is to override paintComponent
method that demands to inherit JPanel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // paint the background image and scale it to fill the entire space
g.drawImage(/*....*/);
}
The other way (a bit complicated) to create second custom JPanel
and put is as background for your main
ImagePanel
public class ImagePanel extends JPanel
{
private static final long serialVersionUID = 1L;
private Image image = null;
private int iWidth2;
private int iHeight2;
public ImagePanel(Image image)
{
this.image = image;
this.iWidth2 = image.getWidth(this)/2;
this.iHeight2 = image.getHeight(this)/2;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
{
int x = this.getParent().getWidth()/2 - iWidth2;
int y = this.getParent().getHeight()/2 - iHeight2;
g.drawImage(image,x,y,this);
}
}
}
EmptyPanel
public class EmptyPanel extends JPanel{
private static final long serialVersionUID = 1L;
public EmptyPanel() {
super();
init();
}
@Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
public void init(){
LayoutManager overlay = new OverlayLayout(this);
this.setLayout(overlay);
ImagePanel iPanel = new ImagePanel(new IconToImage(IconFactory.BG_CENTER).getImage());
iPanel.setLayout(new BorderLayout());
this.add(iPanel);
iPanel.setOpaque(false);
}
}
IconToImage
public class IconToImage {
Icon icon;
Image image;
public IconToImage(Icon icon) {
this.icon = icon;
image = iconToImage();
}
public Image iconToImage() {
if (icon instanceof ImageIcon) {
return ((ImageIcon)icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
/**
* @return the image
*/
public Image getImage() {
return image;
}
}
Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.
Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.
Since you were asking only about the emulator's IP, what is it you're trying to do?
You have three options:
Style links to look like buttons using CSS.
Just look at the light blue "tags" under your question.
It is possible, even to give them a depressed appearance when clicked (using pseudo-classes like :active), without any scripting. Lots of major sites, such as Google, are starting to make buttons out of CSS styles these days anyway, scripting or not.
Put a separate <form> element around each one.
As you mentioned in the question. Easy and will definitely work without Javascript (or even CSS). But it adds a little extra code which may look untidy.
Rely on Javascript.
Which is what you said you didn't want to do.
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.
The onload property of the GlobalEventHandlers mixin is an event handler for the load event of a Window, XMLHttpRequest, element, etc., which fires when the resource has loaded.
So basically javascript already has onload method on window which get executed which page fully loaded including images...
You can do something:
var spinner = true;
window.onload = function() {
//whatever you like to do now, for example hide the spinner in this case
spinner = false;
};
It may have been covered elsewhere but simply changing the encoding line of the XML source to 'utf-16' allows the XML to be inserted into a SQL Server 'xml'data type.
using (DataSetTableAdapters.SQSTableAdapter tbl_SQS = new DataSetTableAdapters.SQSTableAdapter())
{
try
{
bodyXML = @"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test></test>";
bodyXMLutf16 = bodyXML.Replace("UTF-8", "UTF-16");
tbl_SQS.Insert(messageID, receiptHandle, md5OfBody, bodyXMLutf16, sourceType);
}
catch (System.Data.SqlClient.SqlException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
The result is all of the XML text is inserted into the 'xml' data type field but the 'header' line is removed. What you see in the resulting record is just
<test></test>
Using the serialization method described in the "Answered" entry is a way of including the original header in the target field but the result is that the remaining XML text is enclosed in an XML <string></string>
tag.
The table adapter in the code is a class automatically built using the Visual Studio 2013 "Add New Data Source: wizard. The five parameters to the Insert method map to fields in a SQL Server table.
I faced same issue in eclipse neon simple maven java project
But I add below details inside pom.xml file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
After right click on project > maven > update project (checked force update)
Its resolve me to display error on project
Hope it's will helpful
Thansk
you can simply use this format in you function just like
$(function() {
$( "#datepicker" ).datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true
});
});
<input type="text" id="datepicker"></p>
These are all close to the right answer, but I wouldn't say any solve the problem while remaining most readable to others reading your code. I'd say that answer is a combination of BrenBarn's Answer and tuomasttik's comment below that answer. BrenBarn's answer utilizes isspace
builtin, but does not support removing empty strings, as OP requested, and I would tend to attribute that as the standard use case of replacing strings with null.
I rewrote it with .apply
, so you can call it on a pd.Series
or pd.DataFrame
.
Python 3:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, str) and x.isspace() else x)
To use this in Python 2, you'll need to replace str
with basestring
.
Python 2:
To replace empty strings or strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and (x.isspace() or not x) else x)
To replace strings of entirely spaces:
df = df.apply(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)
I haven't done this in a while, but I had to go through this same thing once.
<img src="about:blank" alt="" />
Is my favorite - the //:0
one implies that you'll try to make an HTTP/HTTPS connection to the origin server on port zero (the tcpmux port?) - which is probably harmless, but I'd rather not do anyways. Heck, the browser may see the port zero and not even send a request. But I'd still rather it not be specified that way when that's probably not what you mean.
Anyways, the rendering of about:blank
is actually very fast in all browsers that I tested. I just threw it into the W3C validator and it didn't complain, so it might even be valid.
Edit: Don't do that; it doesn't work on all browsers (it will show a 'broken image' icon as pointed out in the comments for this answer). Use the <img src='data:...
solution below. Or if you don't care about validity, but still want to avoid superfluous requests to your server, you can do <img alt="" />
with no src attribute. But that is INVALID HTML so pick that carefully.
Test Page showing a whole bunch of different methods: http://desk.nu/blank_image.php - served with all kinds of different doctypes and content-types. - as mentioned in the comments below, use Mark Ormston's new test page at: http://memso.com/Test/BlankImage.html
if you are trying to get the elements only but not the functions then this code can help you
this.getKeys = function() {
var keys = new Array();
for(var key in this) {
if( typeof this[key] !== 'function') {
keys.push(key);
}
}
return keys;
}
this is part of my implementation of the HashMap and I only want the keys, this
is the hashmap object that contains the keys
Try this. Copy this into a batch file - such as send.bat - and then simply run send.bat
to send the message from the temperature program to the prismcom program.
temperature.exe > msg.txt
set /p msg= < msg.txt
prismcom.exe usb "%msg%"
Just make sure you add box-sizing:border-box;
to your #myWorkContent
.
I know this is old but I've used a function similar to this...
deleteRow: function (ctrl) {
//remove the row from the table
$(ctrl).closest('tr').remove();
}
... with markup like this ...
<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>
...and it works fine
$result = preg_replace('/ /', '%20', 'your string here');
you may also consider using
$result = urlencode($yourstring)
to escape other special characters as well
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
exp(x) = e^x where e= 2.718281(approx)
import numpy as np
ar=np.array([1,2,3])
ar=np.exp(ar)
print ar
outputs:
[ 2.71828183 7.3890561 20.08553692]
If there is no ORDER BY
clause, then TOP 100 PERCENT
is redundant. (As you mention, this was the 'trick' with views)
[Hopefully the optimizer will optimize this away.]
In Support Library 27.1.0 and later, Google has introduced new methods requireContext()
and requireActivity()
methods.
Eg:ContextCompat.getColor(requireContext(), R.color.soft_gray)
More info here
You can use the following snippet:
tr td:first-child {text-decoration: underline;}
tr td:last-child {color: red;}
Using the following pseudo classes:
:first-child means "select this element if it is the first child of its parent".
:last-child means "select this element if it is the last child of its parent".
Only element nodes (HTML tags) are affected, these pseudo-classes ignore text nodes.
Comparing with setHours()
will be a solution. Sample:
var d1 = new Date();
var d2 = new Date("2019-2-23");
if(d1.setHours(0,0,0,0) == d2.setHours(0,0,0,0)){
console.log(true)
}else{
console.log(false)
}
WMI queries are slow, so try to Select only the desired members instead of using Select *.
The following query takes 3.4s:
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
While this one takes 0.122s:
foreach (var item in new System.Management.ManagementObjectSearcher("Select NumberOfCores from Win32_Processor").Get())
Thank you for posting this question which is quite interesting, even in 2019 (Indeed, it is not easy to renew the shell cmd since it is a single instance as mentioned above), because renewing environment variables in windows allows to accomplish many automation tasks without having to manually restart the command line.
For example, we use this to allow software to be deployed and configured on a large number of machines that we reinstall regularly. And I must admit that having to restart the command line during the deployment of our software would be very impractical and would require us to find workarounds that are not necessarily pleasant. Let's get to our problem. We proceed as follows.
1 - We have a batch script that in turn calls a powershell script like this
[file: task.cmd].
cmd > powershell.exe -executionpolicy unrestricted -File C:\path_here\refresh.ps1
2 - After this, the refresh.ps1 script renews the environment variables using registry keys (GetValueNames(), etc.). Then, in the same powershell script, we just have to call the new environment variables available. For example, in a typical case, if we have just installed nodeJS before with cmd using silent commands, after the function has been called, we can directly call npm to install, in the same session, particular packages like follows.
[file: refresh.ps1]
function Update-Environment {
$locations = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'HKCU:\Environment'
$locations | ForEach-Object {
$k = Get-Item $_
$k.GetValueNames() | ForEach-Object {
$name = $_
$value = $k.GetValue($_)
if ($userLocation -and $name -ieq 'PATH') {
$env:Path += ";$value"
} else {
Set-Item -Path Env:\$name -Value $value
}
}
$userLocation = $true
}
}
Update-Environment
#Here we can use newly added environment variables like for example npm install..
npm install -g create-react-app serve
Once the powershell script is over, the cmd script goes on with other tasks. Now, one thing to keep in mind is that after the task is completed, cmd has still no access to the new environment variables, even if the powershell script has updated those in its own session. Thats why we do all the needed tasks in the powershell script which can call the same commands as cmd of course.
Ran into a similar issue the solution for me was to run fuser -k 'filename.db'
on the file that had a lock associated with it.
Hope this helps!
Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int beans[3][4]{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
cout << "Row size = " << _countof(beans) // Output row size
<< "\nColumn size = " << _countof(*beans); // Output column size
cout << endl;
// Used in a for loop with a pointer.
int(*pbeans)[4]{ beans };
for (int i{}; i < _countof(beans); ++i) {
cout << endl;
for (int j{}; j < _countof(*beans); ++j) {
cout << setw(4) << pbeans[i][j];
}
};
cout << endl;
}
If you seek a key that is equivalent to a directory then you might want this approach
session = boto3.session.Session()
resource = session.resource("s3")
bucket = resource.Bucket('mybucket')
key = 'dir-like-or-file-like-key'
objects = [o for o in bucket.objects.filter(Prefix=key).limit(1)]
has_key = len(objects) > 0
This works for a parent key or a key that equates to file or a key that does not exist. I tried the favored approach above and failed on parent keys.
Web developement generally involves html pages that hold forms (<form>
tags). Forms post to URLs. You can set a given form to post to any url you want to. A postback is when a form posts back to it's own page/url.
The term has special significance for ASP.Net developers, because it is the primary mechanism that drives a lot of the behavior for a page -- specifically 'event handling'. ASP.Net pages have exactly one server form that nearly always posts back to itself, and these post backs trigger execution on the server of something called the Page Lifecycle.
Switch is not considered as loop so you cannot use Continue inside a case statement in switch...
I have tried to explain with my own sample, but I hope it will help you. You don't need onchange="test()" Please run code snippet for getting a live result.
document.getElementById("cars").addEventListener("change", displayCar);_x000D_
_x000D_
function displayCar() {_x000D_
var selected_value = document.getElementById("cars").value;_x000D_
alert(selected_value);_x000D_
}
_x000D_
<select id="cars">_x000D_
<option value="bmw">BMW</option>_x000D_
<option value="mercedes">Mercedes</option>_x000D_
<option value="volkswagen">Volkswagen</option>_x000D_
<option value="audi">Audi</option>_x000D_
</select>
_x000D_
The usual DP solution is true for the problem.
One optimization you may do, is to keep a count of how many solutions exist for the particular sum rather than the actual sets that make up that sum...
Also look for ptkdb on CPAN: http://search.cpan.org/search?query=ptkdb&mode=all
TL;DR: (As of September 2020) Open the Play Console. Select an app. Select Release > Setup >Advanced settings
. On the App Availability
tab, select Unpublish
.
From https://support.google.com/googleplay/android-developer/answer/9859350?hl=en&ref_topic=9872026:
When you unpublish an app, existing users can still use your app and receive app updates. Your app won’t be available for new users to find and download on Google Play.
Prerequisites
- You have accepted the latest Developer Distribution Agreement.
- Your app has no errors that need to be addressed, such as failing to fill in the content rating questionnaire or provide details about your app's target audience and content.
- Managed publishing is not active for the app you want to unpublish.
To unpublish your app:
Open the Play Console. Select an app. Select
Release > Setup > Advanced settings
. On theApp Availability
tab, selectUnpublish
.
Managed publishing
If You want to have a reference to this variable across the whole project, create somewhere d.ts
file, e.g. globals.d.ts
. Fill it with your global variables declarations, e.g.:
declare const BootBox: 'boot' | 'box';
Now you can reference it anywhere across the project, just like that:
const bootbox = BootBox;
Here's an example.
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
Beware:
There are also cells which are seemingly blank
, but are not truly empty but containg "" or something that is called NULL
in other languages. As an example, when a formula results in "" or such result is copied to a cell, the formula
ISBLANK(A1)
returns FALSE
. That means the cell is not truly empty.
The way to go there is to use enter code here
COUNTBLANK(A1)
Which finds both truly empty cells and those containing "". See also this very good answer here
You can try Wolfram Alpha as in this example based on your input:
The root of the answer is that the person asking the question needs to have a JavaScript interpreter to get what they are after. What I have found is I am able to get all of the information I wanted on a website in json before it was interpreted by JavaScript. This has saved me a ton of time in what would be parsing html hoping each webpage is in the same format.
So when you get a response from a website using requests really look at the html/text because you might find the javascripts JSON in the footer ready to be parsed.
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
This is what you need ...
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
Why not use an plain old array? Indexed access to a List is a code smell I think.
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
The html
data attribute does exactly what it says it does in the docs. Try this little example, no JavaScript necessary (broken into lines for clarification):
<span rel="tooltip"
data-toggle="tooltip"
data-html="true"
data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>
JSFiddle demos:
I'm not sure what vim
is doing, but it is an interesting effect. The way you're describing what you want sounds more like how macros work (:help macro
). Something like this would do what you want with macros (starting in normal-mode):
qa
: Record macro to a
register.0w
: 0
goto start of line, w
jump one word.i"<Esc>
: Enter insert-mode, insert a "
and return to normal-mode.2e
: Jump to end of second word.a"<Esc>
: Append a "
.jq
Move to next line and end macro recording.Taken together: qa0wi"<Esc>2ea"<Esc>
Now you can execute the macro with @a
, repeat last macro with @@
. To apply to the rest of the file, do something like 99@a
which assumes you do not have more than 99 lines, macro execution will end when it reaches end of file.
Here is how to achieve what you want with visual-block-mode
(starting in normal mode):
visual-block-mode
, select the lines you want to affect, G
to go to the bottom of the file.I"<Esc>
."
..
will suffice.function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.
Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.
This error is very non-descriptive but the key here is that 'ID' is in uppercase. This indicates that the route has not been correctly set up. To let the application handle URLs with an id, you need to make sure that there's at least one route configured for it. You do this in the RouteConfig.cs located in the App_Start folder. The most common is to add the id as an optional parameter to the default route.
public static void RegisterRoutes(RouteCollection routes)
{
//adding the {id} and setting is as optional so that you do not need to use it for every action
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now you should be able to redirect to your controller the way you have set it up.
[HttpPost]
public ActionResult RedirectToImages(int id)
{
return RedirectToAction("Index","ProductImageManager", new { id });
//if the action is in the same controller, you can omit the controller:
//RedirectToAction("Index", new { id });
}
In one or two occassions way back I ran into some issues by normal redirect and had to resort to doing it by passing a RouteValueDictionary. More information on RedirectToAction with parameter
return RedirectToAction("Index", new RouteValueDictionary(
new { controller = "ProductImageManager", action = "Index", id = id } )
);
If you get a very similar error but in lowercase 'id', this is usually because the route expects an id parameter that has not been provided (calling a route without the id /ProductImageManager/Index
). See this so question for more information.
int[] arr = new int[5] {1,2,3,4,5};
You can use Linq for it
String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);
Also worth noting the following from a document by the R Core Team summarizing changes in versions of R after v3.5.0 (here):
R has new serialization format (version 3) which supports custom serialization of ALTREP framework objects... Serialized data in format 3 cannot be read by versions of R prior to version 3.5.0.
I encountered this issue when I saved a workspace in v3.6.0, and then shared the file with a colleague that was using v3.4.2. I was able to resolve the issue by adding "version=2" to my save function.
Your Code
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
Replace it By
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
I too had come across this issue. I found below two solutions. 1). Same as mentioned by others above, remove extra comma from JSON object. 2). Also, My JSP/HTML was having . Because of this it was triggering browser's old mode which was giving JS error for extra comma. When used it triggers browser's HTML5 mode(If supported) and it works fine even with Extra Comma just like any other browsers FF, Chrome etc.
$ lsof | tree MyFold
As shown in the image attached:
For future reference, webpack 2 removed everything but modules
as a way to resolve paths. This means root
will not work.
https://gist.github.com/sokra/27b24881210b56bbaff7#resolving-options
The example configuration starts with:
{
modules: [path.resolve(__dirname, "app"), "node_modules"]
// (was split into `root`, `modulesDirectories` and `fallback` in the old options)
If you want it without the path then you would use ${0##*/}
window.scroll({top: 0, left: 0, behavior: 'smooth' });
Got it from an article about Smooth Scrolling.
If needed, there are some polyfills available.
public static boolean BFS(ListNode n, int x){
if(n==null){
return false;
}
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>();
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
return true;
}
while(tmp != null){
for(ListNode<Integer> child: n.getChildren()){
if(child.val == x){
return true;
}
q.enqueue(child);
}
tmp = q.dequeue();
}
return false;
}
I faced with this error today, reason was; IIS user doesn't have permission to reach to the application folder. I gave the read permissions to the app root folder.
#include <bits/stdc++.h> // to include all libraries
using namespace std;
int main()
{
double a,b;
cin>>a>>b;
double x=a/b; //say we want to divide a/b
cout<<fixed<<setprecision(10)<<x; //for precision upto 10 digit
return 0;
}
input: 1987 31
output: 662.3333333333 10 digits after decimal point
FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
You can use the setupFiles
feature of the Jest configuration. As the documentation said that,
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
npm install dotenv
dotenv that uses to access environment variable.
Create your .env
file to the root directory of your application and add this line into it:
#.env
APP_PORT=8080
Create your custom module file as its name being someModuleForTest.js and add this line into it:
// someModuleForTest.js
require("dotenv").config()
Update your jest.config.js
file like this:
module.exports = {
setupFiles: ["./someModuleForTest"]
}
You can access an environment variable within all test blocks.
test("Some test name", () => {
expect(process.env.APP_PORT).toBe("8080")
})
It's very easy just add android:backgroundTint
attribute in your EditText
.
android:backgroundTint="@color/blue"
android:backgroundTint="#ffffff"
android:backgroundTint="@color/red"
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#ffffff"/>
You can try something like the following:
h1{
margin-bottom:<x>px;
}
div{
margin-bottom:<y>px;
}
div:last-of-type{
margin-bottom:0;
}
or instead of the first h1
rule:
div:first-of-type{
margin-top:<x>px;
}
or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:
div + div{
margin-bottom:<y>px;
}
Respectively, h1 + div
would control the first div after your header, giving you additional styling options.
It seems that your problem is simply a concurrency issue. The post function takes a callback argument to tell you when the post has been finished. You cannot make the alert in global scope like this and expect that the post has already been finished. You have to move it to the callback function.
Rather than encoding the URL beforehand you can do the following
String link = "http://example.com";
URL url = null;
URI uri = null;
try {
url = new URL(link);
} catch(MalformedURLException e) {
e.printStackTrace();
}
try{
uri = new URI(url.toString())
} catch(URISyntaxException e {
try {
uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(),
url.getPort(), url.getPath(), url.getQuery(),
url.getRef());
} catch(URISyntaxException e1 {
e1.printStackTrace();
}
}
try {
url = uri.toURL()
} catch(MalfomedURLException e) {
e.printStackTrace();
}
String encodedLink = url.toString();
The answers vary between languages. For example, in Java a class can implement (inherit from) multiple interfaces but only inherit from one abstract class. So interfaces give you more flexibility. But this is not true in C++.
This is the conditional operator expression.
(condition) ? [true path] : [false path];
For example
string value = someBooleanExpression ? "Alpha" : "Beta";
So if the boolean expression is true, value will hold "Alpha", otherwise, it holds "Beta".
For a common pitfall that people fall into, see this question in the C# tag wiki.
Since it took me a while to figure it out, I thought it would be helpful to post my solution using Java 7+ ZipFileSystem
openZip(runFile);
addToZip(filepath); //loop construct;
zipfs.close();
private void openZip(File runFile) throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
env.put("encoding", "UTF-8");
Files.deleteIfExists(runFile.toPath());
zipfs = FileSystems.newFileSystem(URI.create("jar:" + runFile.toURI().toString()), env);
}
private void addToZip(String filename) throws IOException {
Path externalTxtFile = Paths.get(filename).toAbsolutePath();
Path pathInZipfile = zipfs.getPath(filename.substring(filename.lastIndexOf("results"))); //all files to be stored have a common base folder, results/ in my case
if (Files.isDirectory(externalTxtFile)) {
Files.createDirectories(pathInZipfile);
try (DirectoryStream<Path> ds = Files.newDirectoryStream(externalTxtFile)) {
for (Path child : ds) {
addToZip(child.normalize().toString()); //recursive call
}
}
} else {
// copy file to zip file
Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
}
}
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.
First of all, you probably don't want the align
environment if you have only one column of equations. In fact, your example is probably best with the cases
environment. But to answer your question directly, used the aligned
environment within equation
- this way the outside environment gives the number:
\begin{equation}
\begin{aligned}
w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1, \\
w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
\end{aligned}
\end{equation}
The documentation of the amsmath
package explains this and more.
my error disappeared by adding this '()' at the end
(function(){
var home = angular.module('home',[]);
home.controller('QuestionsController',function(){
console.log("controller initialized");
this.addPoll = function(){
console.log("inside function");
};
});
})();
How are you calling split
? It works like this:
def values = '1182-2'.split('-')
assert values[0] == '1182'
assert values[1] == '2'
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
import requests
from requests_toolbelt.utils import dump
resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
pip install requests_toolbelt
package.json
counts with a optionalDependencies
key.
NPM on Optional Dependencies.
You can add fsevents
to this object and if you find yourself installing packages in a different platform than MacOS, fsevents
will be skipped by either yarn or npm.
"optionalDependencies": {
"fsevents": "2.1.2"
},
You will find a message like the following in the installation log:
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
Hope it helps!
As far as I know, you can't.
Besides, that isnt what CSS is for anyway. CSS is for styling and HTML is for markup.
just right click on the desired folder and select git-bash Here option it will direct you to that folder and start working hope it will work.
See this page: https://slai.github.io/posts/powershell-and-external-commands-done-right/
Summary using vshadow as the external executable:
$exe = "H:\backup\scripts\vshadow.exe"
&$exe -p -script=H:\backup\scripts\vss.cmd E: M: P:
List<User> findByUsernameContainingIgnoreCase(String username);
in order to ignore case issues
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
Replace:
myBinding.Source = ViewModel.SomeString;
with:
myBinding.Source = ViewModel;
Example:
Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
Your source should be just ViewModel
, the .SomeString
part is evaluated from the Path
(the Path
can be set by the constructor or by the Path
property).
I use the following object:
function Padder(len, pad) {
if (len === undefined) {
len = 1;
} else if (pad === undefined) {
pad = '0';
}
var pads = '';
while (pads.length < len) {
pads += pad;
}
this.pad = function (what) {
var s = what.toString();
return pads.substring(0, pads.length - s.length) + s;
};
}
With it you can easily define different "paddings":
var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"
Oddly, it works with some types of input. At least in Chrome,
<input type="checkbox" />
works fine, same as
<input type="radio" />
It's just type=text
and some others that don't work.
Below method uploads file in a particular folder in a bucket and return the generated url of the file uploaded.
private String uploadFileToS3Bucket(final String bucketName, final File file) {
final String uniqueFileName = uploadFolder + "/" + file.getName();
LOGGER.info("Uploading file with name= " + uniqueFileName);
final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, file);
amazonS3.putObject(putObjectRequest);
return ((AmazonS3Client) amazonS3).getResourceUrl(bucketName, uniqueFileName);
}
The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.
If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.
I'm surprised nobody mentioned the command php artisan route:list
, which gives a list of all registered app routes (including Auth::routes()
and Passport::routes()
if registered)
Here is a more generic solution for any given weekday. Working demo on jsfiddle
var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.
var startOfPeriod = moment("2013-06-23T00:00:00"),
// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;
// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);
According to MySQL documentation, you should be able to just enclose that datetime string in single quotes, ('YYYY-MM-DD HH:MM:SS') and it should work. Look here: Date and Time Literals
So, in your case, the command should be as follows:
UPDATE products SET former_date='2011-12-18 13:17:17' WHERE id=1
If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:
public class ThreadProvider implements CustomInterface{
...
}
Then in your controller try this:
@Controller
public class ChiusuraController {
@Autowired
private CustomInterface chiusuraProvider;
}
The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider
extend ThreadProvider
Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).
When you DID extend from ThreadProvider
assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider
type.
If you absolutely need to use ChisuraProvider
you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:
<aop:aspectj-autoproxy proxy-target-class="true"/>
Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb
if you want to force using BETWEEN keyword on Codeigniter query helper. You can use where without escape false like this code. Works well on CI version 3.1.5. Hope its help someone.
if(!empty($tglmin) && !empty($tglmax)){
$this->db->group_start();
$this->db->where('DATE(create_date) BETWEEN "'.$tglmin.'" AND "'.$tglmax.'"', '',false);
$this->db->group_end();
}
This question has been answered, but maybe this might someone else coming here.
I also had an issue where this
is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:
import MyClass from "./myClass"
// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined
// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK
Sometimes JavaScript is not activated. Try something like:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"> <!--
function jActivator() {
document.getElementById("demo").onclick = function() {myFunction()};
document.getElementById("demo1").addEventListener("click", myFunction);
}
function myFunction( s ) {
document.getElementById("myresult").innerHTML = s;
}
// --> </script>
<noscript>JavaScript deactivated.</noscript>
<style type="text/css">
</style>
</head>
<body onload="jActivator()">
<ul>
<li id="demo">Click me -> onclick.</li>
<li id="demo1">Click me -> click event.</li>
<li onclick="myFunction('YOU CLICKED ME!')">Click me calling function.</li>
</ul>
<div id="myresult"> </div>
</body>
</html>
If you use the code inside a page, where no access to is possible, remove and tags and try to use 'onload=()' in a picture inside the image tag '
Map.values()
:
HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
new HashMap<String, HashMap<SomeInnerKeyType, String>>();
...
for(HashMap<SomeInnerKeyType, String> h : selects.values())
{
ComboBox cb = new ComboBox();
for(String s : h.values())
{
cb.items.add(s);
}
}
Google Finance has an API - you probably have to apply for a developers key, but at least you'd save yourself the hassle of screen-scraping: http://code.google.com/apis/finance/reference.html
Use os.environ[str(DEBUSSY)]
for both reading and writing (http://docs.python.org/library/os.html#os.environ).
As for reading, you have to parse the number from the string yourself of course.
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
Basicaly a promisified version of @espascarello and @adeneo answers, with a fallback parameter:
const getImageOrFallback = (path, fallback) => {_x000D_
return new Promise(resolve => {_x000D_
const img = new Image();_x000D_
img.src = path;_x000D_
img.onload = () => resolve(path);_x000D_
img.onerror = () => resolve(fallback);_x000D_
});_x000D_
};_x000D_
_x000D_
// Usage:_x000D_
_x000D_
const link = getImageOrFallback(_x000D_
'https://www.fillmurray.com/640/360',_x000D_
'https://via.placeholder.com/150'_x000D_
).then(result => console.log(result) || result)_x000D_
_x000D_
// It can be also implemented using the async / await API.
_x000D_
Note: I may personally like the fetch
solution more, but it has a drawback – if your server is configured in a specific way, it can return 200 / 304, even if your file doesn't exist. This, on the other hand, will do the job.
$.ajax(), $.get(), $.post(), $.load()
functions of jQuery internally send XML HTTP
request.
among these the load()
is only dedicated for a particular DOM Element
. See jQuery Ajax Doc. A details Q.A. on these are Here .
Try this procedure:
def procedure(input):
a=0
print input[a]
ecs = input[a] #ecs stands for each character separately
while ecs != input:
a = a + 1
print input[a]
In order to use it you have to know how to use procedures and although it works, it has an error in the end so you have to work that out too.
I had a situation whereby I had to replace the HTML tags with two different replacement results.
$trades = "<li>Sprinkler and Fire Protection Installer</li>
<li>Steamfitter </li>
<li>Terrazzo, Tile and Marble Setter</li>";
$s1 = str_replace('<li>', '"', $trades);
$s2 = str_replace('</li>', '",', $s1);
echo $s2;
result
"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",
"^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\\d\\d)$"
will validate any date between 1900-2099
Tomalak already gave you a correct answer, but I would like to add that most of the times when you would like to know the VBA code needed to do a certain action in the user interface it is a good idea to record a macro.
In this case click Record Macro on the developer tab of the Ribbon, freeze the top row and then stop recording. Excel will have the following macro recorded for you which also does the job:
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).
So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
I was plagued by this error message despite using async: true. It turns out the actual problem was using the success
method. I changed this to done
and warning is gone.
success: function(response) { ... }
replaced with:
done: function(response) { ... }
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
You Could always use and leave out the "when not matched section"
merge into table1 FromTable
using table2 ToTable
on ( FromTable.field1 = ToTable.field1
and FromTable.field2 =ToTable.field2)
when Matched then
update set
ToTable.fieldr = FromTable.fieldx,
ToTable.fields = FromTable.fieldy,
ToTable.fieldt = FromTable.fieldz)
when not matched then
insert (ToTable.field1,
ToTable.field2,
ToTable.fieldr,
ToTable.fields,
ToTable.fieldt)
values (FromTable.field1,
FromTable.field2,
FromTable.fieldx,
FromTable.fieldy,
FromTable.fieldz);
In addition to the ways already mentioned (dropping the war-file directly into the webapps-directory), if you have the Tomcat Manager -application installed, you can deploy war-files via browser too. To get to the manager, browse to the root of the server (in your case, localhost:8080), select "Tomcat Manager" (at this point, you need to know username and password for a Tomcat-user with "manager"-role, the users are defined in tomcat-users.xml in the conf-directory of the tomcat-installation). From the opening page, scroll downwards until you see the "Deploy"-part of the page, where you can click "browse" to select a WAR file to deploy from your local machine. After you've selected the file, click deploy. After a while the manager should inform you that the application has been deployed (and if everything went well, started).
Here's a longer how-to and other instructions from the Tomcat 7 documentation pages.
phpQuery and QueryPath are extremely similar in replicating the fluent jQuery API. That's also why they're two of the easiest approaches to properly parse HTML in PHP.
Examples for QueryPath
Basically you first create a queryable DOM tree from an HTML string:
$qp = qp("<html><body><h1>title</h1>..."); // or give filename or URL
The resulting object contains a complete tree representation of the HTML document. It can be traversed using DOM methods. But the common approach is to use CSS selectors like in jQuery:
$qp->find("div.classname")->children()->...;
foreach ($qp->find("p img") as $img) {
print qp($img)->attr("src");
}
Mostly you want to use simple #id
and .class
or DIV
tag selectors for ->find()
. But you can also use XPath statements, which sometimes are faster. Also typical jQuery methods like ->children()
and ->text()
and particularly ->attr()
simplify extracting the right HTML snippets. (And already have their SGML entities decoded.)
$qp->xpath("//div/p[1]"); // get first paragraph in a div
QueryPath also allows injecting new tags into the stream (->append
), and later output and prettify an updated document (->writeHTML
). It can not only parse malformed HTML, but also various XML dialects (with namespaces), and even extract data from HTML microformats (XFN, vCard).
$qp->find("a[target=_blank]")->toggleClass("usability-blunder");
.
phpQuery or QueryPath?
Generally QueryPath is better suited for manipulation of documents. While phpQuery also implements some pseudo AJAX methods (just HTTP requests) to more closely resemble jQuery. It is said that phpQuery is often faster than QueryPath (because of fewer overall features).
For further information on the differences see this comparison on the wayback machine from tagbyte.org. (Original source went missing, so here's an internet archive link. Yes, you can still locate missing pages, people.)
And here's a comprehensive QueryPath introduction.
Advantages
->find("a img, a object, div a")
Unless you are writing directly to the slave (Server2) the only problem should be that Server2 is missing any updates that have happened since it was disconnected. Simply restarting the slave with "START SLAVE;" should get everything back up to speed.
Please try running
brew install docker
This will install the Docker engine, which will require Docker-Machine (+ VirtualBox) to run on the Mac.
If you want to install the newer Docker for Mac, which does not require virtualbox, you can install that through Homebrew's Cask:
brew install --cask docker
open /Applications/Docker.app
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
A simple way to create a array to a PHP string array is:
<?PHP
$array = array("firstname"=>"John", "lastname"=>"doe");
$json = json_encode($array);
$phpStringArray = str_replace(array("{", "}", ":"),
array("array(", "}", "=>"), $json);
echo phpStringArray;
?>
The freezing / deadlock can also be caused by this bug on GTK3 + Xorg
https://bugs.eclipse.org/bugs/show_bug.cgi?id=568859
Can be workarounded by using Wayland session, although in my case Eclipse fails to detect reasonable font for some reason and looks like this:
Related:
https://www.reddit.com/r/swaywm/comments/bkzeo7/font_rendering_really_bad_and_rough_in_gtk3/
https://www.reddit.com/r/swaywm/comments/kmd3d1/webkit_gtk_font_rendering_on_wayland/
Just a small correction for Marko's answer: exact number can't be produced out of some general calculations straight forward due to the next fact: Valid IP addresses should also not end with binary 0 or 1 sequences that have same length as zero sequence in subnet mask. So the final answer really depends on the total number of subnets (Marko's answer - 2 * total subnet count).
$('#btnSaveComments').click(function () {
var comments = $('#txtComments').val();
var selectedId = $('#hdnSelectedId').val();
$.ajax({
url: '<%: Url.Action("SaveComments")%>',
data: { 'id' : selectedId, 'comments' : comments },
type: "post",
cache: false,
success: function (savingStatu`enter code here`s) {
$("#hdnOrigComments").val($('#txtComments').val());
$('#lblCommentsNotification').text(savingStatus);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblCommentsNotification').text("Error encountered while saving the comments.");
}
});
});
You can Try this,
$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
XML approach using androidx:
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/my_recycler_view"
android:orientation="horizontal"
tools:listitem="@layout/my_item"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:layout_height="wrap_content">
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
<iframe>
The iframe element represents a nested browsing context. HTML 5 standard - "The
<iframe>
element"
Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>
's strength is that the embedded code is 'live' and can communicate with the parent document.
<embed>
Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...
The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The
<embed>
element")
Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.
The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:
svg = document.getElementById("parent_id").getSVGDocument();
From inside an embedded SVG or HTML document you can reach the parent with:
parent = window.parent.document;
For embedded HTML there is no way to get at the embedded document from the parent (that I have found).
<object>
The
<object>
element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The<object>
element")
Unless you are embedding SVG or something static you are probably best of using <iframe>
. To include SVG use <embed>
(if I remember correctly <object>
won't let you script†). Honestly I don't know why you would use <object>
unless for older browsers or flash (that I don't work with).
† As pointed out in the comments below; scripts in <object>
will run but the parent and child contexts can't communicate directly. With <embed>
you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object>
or <iframe>
where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.
To quote the Christmas analogy again:
In SQL, NULL basically means "closed box" (unknown). So, the result of comparing two closed boxes will also be unknown (null).
I understand, for a developer, this is counter-intuitive, because in programming languages, often NULL rather means "empty box" (known). And comparing two empty boxes will naturally yield true / equal.
This is why JavaScript for example distinguishes between null
and undefined
.
This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.
A small demo may help you: In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Like the rest of the users say it is easiest to do this with CURL.
If curl isn't available for you then maybe http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
If that isn't possible you could write sockets yourself http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html
You will need these imports...
import javax.servlet.*;
import javax.servlet.http.*;
And, if you're using Maven, you'll also need this in the dependencies block of the pom.xml file in your project's base directory.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Then the above-listed fix by Jason will work:
@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
HttpServletResponse response, Model model){
String jsonString = request.getParameter("json");
}
Marian's solution adapted for long type numbers (up to 9,223,372,036,854,775,807), in case someone want's to Copy&Paste it. In the program I wrote this for numbers up to 10000 were much more probable, so I made a specific branch for them. Anyway it won't make a significative difference.
public static int numberOfDigits (long n) {
// Guessing 4 digit numbers will be more probable.
// They are set in the first branch.
if (n < 10000L) { // from 1 to 4
if (n < 100L) { // 1 or 2
if (n < 10L) {
return 1;
} else {
return 2;
}
} else { // 3 or 4
if (n < 1000L) {
return 3;
} else {
return 4;
}
}
} else { // from 5 a 20 (albeit longs can't have more than 18 or 19)
if (n < 1000000000000L) { // from 5 to 12
if (n < 100000000L) { // from 5 to 8
if (n < 1000000L) { // 5 or 6
if (n < 100000L) {
return 5;
} else {
return 6;
}
} else { // 7 u 8
if (n < 10000000L) {
return 7;
} else {
return 8;
}
}
} else { // from 9 to 12
if (n < 10000000000L) { // 9 or 10
if (n < 1000000000L) {
return 9;
} else {
return 10;
}
} else { // 11 or 12
if (n < 100000000000L) {
return 11;
} else {
return 12;
}
}
}
} else { // from 13 to ... (18 or 20)
if (n < 10000000000000000L) { // from 13 to 16
if (n < 100000000000000L) { // 13 or 14
if (n < 10000000000000L) {
return 13;
} else {
return 14;
}
} else { // 15 or 16
if (n < 1000000000000000L) {
return 15;
} else {
return 16;
}
}
} else { // from 17 to ...¿20?
if (n < 1000000000000000000L) { // 17 or 18
if (n < 100000000000000000L) {
return 17;
} else {
return 18;
}
} else { // 19? Can it be?
// 10000000000000000000L is'nt a valid long.
return 19;
}
}
}
}
}
Another option would be to use R via a small bash wrapper for convenience:
xlsx2txt(){
echo '
require(xlsx)
write.table(read.xlsx2(commandArgs(TRUE)[1], 1), stdout(), quote=F, row.names=FALSE, col.names=T, sep="\t")
' | Rscript --vanilla - $1 2>/dev/null
}
xlsx2txt file.xlsx > file.txt
Try this
$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;
Result:
-------------------
| String | Count |
-------------------
| table1 | 123 |
| table2 | 234 |
| table3 | 345 |
| table4 | 456 |
| table5 | 567 |
-------------------
We could use tidyr::extract()
x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#> A B C D
#> <chr> <chr> <chr> <chr>
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Another option is to use unglue::unglue_data()
# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#> A B C D
#> 1 F US CLE V13
#> 2 F US CA6 U13
#> 3 F US CA6 U13
#> 4 F US CA6 U13
#> 5 F US CA6 U13
#> 6 F US CA6 U13
#> 7 F US CA6 U13
#> 8 F US CA6 U13
#> 9 F US DL U13
#> 10 F US DL U13
#> 11 F US DL U13
#> 12 F US DL Z13
#> 13 F US DL Z13
Created on 2019-09-14 by the reprex package (v0.3.0)
^(\d{0,2}\\.)?\d{1,2}$
\d{1,2}$
matches a 1-2 digit number with nothing after it (3
, 33
, etc.), (\d{0,2}\.)?
matches optionally a number 0-2 digits long followed by a period (3.
, 44.
, .
, etc.). Put them together and you've got your regex.
In addition to the other answers here, non-breaking spaces will not be "collapsed" like regular spaces will. For example:
<!-- Both -->
<p>Word1 Word2</p>
<!-- and -->
<p>Word1 Word2</p>
<!-- will render the same on any browser -->
<!-- While the below one will keep the spaces when rendered. -->
<p>Word1 Word2</p>
_x000D_
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msgs) {
//write your code hear which give error
}
}
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
//this will call handleMessage function and hendal all error
}
}).start();
Your script seems incorrect in several places.
Try this
var timetemp = document.getElementsByTagName('input');
for (var i = 0; i < timetemp.length; i++){
if (timetemp[i].value == ""){
alert ('No value');
}
else{
alert (timetemp[i].value);
}
}
Example: http://jsfiddle.net/jasongennaro/FSzT2/
Here's what I changed:
input
s via TagName
. This makes an arrayi
with a var
and then looped through the timetemp
array using the timetemp.length
property.timetemp[i]
to reference each input
in the for statement
Method 1
CURRENT_TIME – Inserts only time
CURRENT_DATE – Inserts only date
CURRENT_TIMESTAMP – Inserts both time and date
CREATE TABLE users(
id INTEGER PRIMARY KEY,
username TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Method 2
db.execSQL("INSERT INTO users(username, created_at)
VALUES('ravitamada', 'datetime()'");
Method 3 Using java Date functions
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
ContentValues values = new ContentValues();
values.put('username', 'ravitamada');
values.put('created_at', getDateTime());
// insert the row
long id = db.insert('users', null, values);
As an answer strictly in line with your question, I support cleytus's proposal.
You could also use a marker interface (with no method), say DistantCall
, with several several sub-interfaces that have the precise signatures you want.
Examples of 'reusable' interfaces:
public interface DistantCall {
}
public interface TUDistantCall<T,U> extends DistantCall {
T execute(U... us);
}
public interface UDistantCall<U> extends DistantCall {
void execute(U... us);
}
public interface TDistantCall<T> extends DistantCall {
T execute();
}
public interface TUVDistantCall<T, U, V> extends DistantCall {
T execute(U u, V... vs);
}
....
UPDATED in response to OP comment
I wasn't thinking of any instanceof in the calling. I was thinking your calling code knew what it was calling, and you just needed to assemble several distant call in a common interface for some generic code (for example, auditing all distant calls, for performance reasons). In your question, I have seen no mention that the calling code is generic :-(
If so, I suggest you have only one interface, only one signature. Having several would only bring more complexity, for nothing.
However, you need to ask yourself some broader questions :
how you will ensure that caller and callee do communicate correctly?
That could be a follow-up on this question, or a different question...
Old thread, but still a valid concern. I noticed some good responses about security, and avoiding use of 'security through obscurity', but the actual technical methods given were not sufficient in my eyes. Things I must say before I contribute my method:
That all being said, there are two great ways to have auto-signin on your system.
First, the cheap, easy way that puts it all on someone else. If you make your site support logging in with, say, your google+ account, you probably have a streamlined google+ button that will log the user in if they are already signed into google (I did that here to answer this question, as I am always signed into google). If you want the user automatically signed in if they are already signed in with a trusted and supported authenticator, and checked the box to do so, have your client-side scripts perform the code behind the corresponding 'sign-in with' button before loading, just be sure to have the server store a unique ID in an auto-signin table that has the username, session ID, and the authenticator used for the user. Since these sign-in methods use AJAX, you are waiting for a response anyway, and that response is either a validated response or a rejection. If you get a validated response, use it as normal, then continue loading the logged in user as normal. Otherwise, the login failed, but don't tell the user, just continue as not logged in, they will notice. This is to prevent an attacker who stole cookies (or forged them in an attempt to escalate privileges) from learning that the user auto-signs into the site.
This is cheap, and might also be considered dirty by some because it tries to validate your potentially already signed in self with places like Google and Facebook, without even telling you. It should, however, not be used on users who have not asked to auto-signin your site, and this particular method is only for external authentication, like with Google+ or FB.
Because an external authenticator was used to tell the server behind the scenes whether or not a user was validated, an attacker cannot obtain anything other than a unique ID, which is useless on its own. I'll elaborate:
No matter what, even if an attacker uses an ID that does not exist, the attempt should fail on all attempts except when a validated response is received.
This method can and should be used in conjunction with your internal authenticator for those who sign into your site using an external authenticator.
=========
Now, for your very own authenticator system that can auto-signin users, this is how I do it:
DB has a few tables:
TABLE users:
UID - auto increment, PK
username - varchar(255), unique, indexed, NOT NULL
password_hash - varchar(255), NOT NULL
...
Note that the username is capable of being 255 characters long. I have my server program limit usernames in my system to 32 characters, but external authenticators might have usernames with their @domain.tld be larger than that, so I just support the maximum length of an email address for maximum compatibility.
TABLE sessions:
session_id - varchar(?), PK
session_token - varchar(?), NOT NULL
session_data - MediumText, NOT NULL
Note that there is no user field in this table, because the username, when logged in, is in the session data, and the program does not allow null data. The session_id and the session_token can be generated using random md5 hashes, sha1/128/256 hashes, datetime stamps with random strings added to them then hashed, or whatever you would like, but the entropy of your output should remain as high as tolerable to mitigate brute-force attacks from even getting off the ground, and all hashes generated by your session class should be checked for matches in the sessions table prior to attempting to add them.
TABLE autologin:
UID - auto increment, PK
username - varchar(255), NOT NULL, allow duplicates
hostname - varchar(255), NOT NULL, allow duplicates
mac_address - char(23), NOT NULL, unique
token - varchar(?), NOT NULL, allow duplicates
expires - datetime code
MAC addresses by their nature are supposed to be UNIQUE, therefore it makes sense that each entry has a unique value. Hostnames, on the other hand, could be duplicated on separate networks legitimately. How many people use "Home-PC" as one of their computer names? The username is taken from the session data by the server backend, so manipulating it is impossible. As for the token, the same method to generate session tokens for pages should be used to generate tokens in cookies for the user auto-signin. Lastly, the datetime code is added for when the user would need to revalidate their credentials. Either update this datetime on user login keeping it within a few days, or force it to expire regardless of last login keeping it only for a month or so, whichever your design dictates.
This prevents someone from systematically spoofing the MAC and hostname for a user they know auto-signs in. NEVER have the user keep a cookie with their password, clear text or otherwise. Have the token be regenerated on each page navigation, just as you would the session token. This massively reduces the likelihood that an attacker could obtain a valid token cookie and use it to login. Some people will try to say that an attacker could steal the cookies from the victim and do a session replay attack to login. If an attacker could steal the cookies (which is possible), they would certainly have compromised the entire device, meaning they could just use the device to login anyway, which defeats the purpose of stealing cookies entirely. As long as your site runs over HTTPS (which it should when dealing with passwords, CC numbers, or other login systems), you have afforded all the protection to the user that you can within a browser.
One thing to keep in mind: session data should not expire if you use auto-signin. You can expire the ability to continue the session falsely, but validating into the system should resume the session data if it is persistent data that is expected to continue between sessions. If you want both persistent AND non-persistent session data, use another table for persistent session data with the username as the PK, and have the server retrieve it like it would the normal session data, just use another variable.
Once a login has been achieved in this way, the server should still validate the session. This is where you can code expectations for stolen or compromised systems; patterns and other expected results of logins to session data can often lead to conclusions that a system was hijacked or cookies were forged in order to gain access. This is where your ISS Tech can put rules that would trigger an account lockdown or auto-removal of a user from the auto-signin system, keeping attackers out long enough for the user to determine how the attacker succeeded and how to cut them off.
As a closing note, be sure that any recovery attempt, password changes, or login failures past the threshold result in auto-signin being disabled until the user validates properly and acknowledges this has occurred.
I apologize if anyone was expecting code to be given out in my answer, that's not going to happen here. I will say that I use PHP, jQuery, and AJAX to run my sites, and I NEVER use Windows as a server... ever.
In layman's terms:
JDBC is a standard for connecting to a DB directly and running SQL against it - e.g SELECT * FROM USERS
, etc. Data sets can be returned which you can handle in your app, and you can do all the usual things like INSERT
, DELETE
, run stored procedures, etc. It is one of the underlying technologies behind most Java database access (including JPA providers).
One of the issues with traditional JDBC apps is that you can often have some crappy code where lots of mapping between data sets and objects occur, logic is mixed in with SQL, etc.
JPA is a standard for Object Relational Mapping. This is a technology which allows you to map between objects in code and database tables. This can "hide" the SQL from the developer so that all they deal with are Java classes, and the provider allows you to save them and load them magically. Mostly, XML mapping files or annotations on getters and setters can be used to tell the JPA provider which fields on your object map to which fields in the DB. The most famous JPA provider is Hibernate, so it's a good place to start for concrete examples.
Other examples include OpenJPA, toplink, etc.
Under the hood, Hibernate and most other providers for JPA write SQL and use JDBC to read and write from and to the DB.
Debug.Print
outputs to the "Immediate" window.
Also, you can simply type ?
and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:
This can be very handy to quickly output the property of an object...
? myWidget.name
...to set the property of an object...
myWidget.name = "thingy"
...or to even execute a function or line of code, while in debugging mode:
Sheet1.MyFunction()
You can do something like this
var now = moment();
var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');
For boot2docker, we can set it on /var/lib/boot2docker/profile
, for instance:
ulimit -n 2018
Be warned not to set this limit too high as it will slow down apt-get! See bug #1332440. I had it with debian jessie.
\n
is used for Unix systems (including Linux, and OSX).
\r\n
is mainly used on Windows.
\r
is used on really old Macs.
PHP_EOL
constant is used instead of these characters for portability between platforms.