Use "javascript.validate.enable": false
in your VS Code settings, It doesn't disable ESLINT. I use both ESLINT & Flow. Simply follow the instructions Flow For Vs Code Setup
Adding this line in settings.json. Helps
"javascript.validate.enable": false
Code Runner Extension will only let you "run" java files.
To truly debug 'Java' files follow the quick one-time setup:
.vscode
in the same folder..vscode
folder: tasks.json
and launch.json
tasks.json
:{ "version": "2.0.0", "type": "shell", "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "isBackground": true, "tasks": [ { "taskName": "build", "args": ["-g", "${file}"], "command": "javac" } ] }
launch.json
:{ "version": "0.2.0", "configurations": [ { "name": "Debug Java", "type": "java", "request": "launch", "externalConsole": true, //user input dosen't work if set it to false :( "stopOnEntry": true, "preLaunchTask": "build", // Runs the task created above before running this configuration "jdkPath": "${env:JAVA_HOME}/bin", // You need to set JAVA_HOME enviroment variable "cwd": "${workspaceRoot}", "startupClass": "${workspaceRoot}${file}", "sourcePath": ["${workspaceRoot}"], // Indicates where your source (.java) files are "classpath": ["${workspaceRoot}"], // Indicates the location of your .class files "options": [], // Additional options to pass to the java executable "args": [] // Command line arguments to pass to the startup class } ], "compounds": [] }
You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).
Tip: *To hide .class files in the side explorer of VS code, open settings
of VS code and paste the below config:
"files.exclude": {
"*.class": true
}
There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.
Name: Line endings
Id: jhartell.vscode-line-endings
Description: Display line ending characters in vscode
Version: 0.1.0
Publisher: Johnny Härtell
As of September 2016 (VSCode 1.6), this is now officially supported.
Add the following to your settings.json
file:
"editor.formatOnSave": true
As of today the download URL for the latest version of the extension is embedded verbatim in the source of the page on Marketplace, e.g. source at URL:
https://marketplace.visualstudio.com/items?itemName=lukasz-wronski.ftp-sync
contains string:
https://lukasz-wronski.gallerycdn.vsassets.io/extensions/lukasz-wronski/ftp-sync/0.3.3/1492669004156/Microsoft.VisualStudio.Services.VSIXPackage
I use following Python regexp to extract dl URL:
urlre = re.search(r'source.+(http.+Microsoft\.VisualStudio\.Services\.VSIXPackage)', content)
if urlre:
return urlre.group(1)
You might also want to set the editor.detectIndentation
to false, in addition to Elliot-J's answer.
VSCode will overwrite your editor.tabSize
and editor.insertSpaces
settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.
There is a much easier way to compile and run C code using GCC, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.Moreover you could update the config in settings.json using different C compilers as you want, the default config for C is as below:
"code-runner.executorMap": {
"c": "gcc $fullFileName && ./a.out"
}
Visual Studio 2017
I also wanted to clarify that if you have complex url parameters to build, you will need to build them manually. ie if your query is example.com/?latlng=-37,147
, instead of providing the lat and lng values individually, you will need to build the latlng string externally, then provide it as a parameter, ie:
public interface LocationService {
@GET("/example/")
void getLocation(@Query(value="latlng", encoded=true) String latlng);
}
Note the encoded=true
is necessary, otherwise retrofit will encode the comma in the string parameter. Usage:
String latlng = location.getLatitude() + "," + location.getLongitude();
service.getLocation(latlng);
It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.
It is also possible that your settings.xml file defined in maven/conf folder defines a location that it cannot access
Here's the solution,
If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,
1. GO TO
Window-> Preferences -> General -> Network Connection.
2. Change the Settings
Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS
If your active provider is already set to Manual, try restoring the default (native)
That's all, restart Eclipse and you are good to go!
Try this.
if(is_array($value) || is_object($value)){
foreach($value as $item){
//somecode
}
}
help=>install new software=>workwith choice Juno - http://download.eclipse.org/releases/juno and search in the below "type filter text" --------------market
you will see this plugs Marketplace Client
As opposed to what's written on the chosen answer, you don't need root and it is possible to get the APKs of the installed apps, which is how I've done it on my app (here). Example:
List<PackageInfo> packages=getPackageManager().getInstalledPackages(0);
Then, for each of the items of the list, you can access packageInfo.applicationInfo.sourceDir, which is the full path of the APK of the installed app.
I'm using if for day-to-day work and I find it stable. Lately the plugin has made good progress and has added:
Be sure to skim the EGit User Guide for a good overview of the current functionality.
I find that I only need to drop to the comand line for interactive rebases.
As an official Eclipse project I am confident that EGit will receive all the main features of the command-line client.
With appFuse framework, you can create an Spring MVC archetype with jpa support, etc ...
Take a look at it's quickStart guide to see how to create an archetype based on this Framework.
Foundational frameworks in AppFuse:
For example to create an appFuse light archetype :
mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes
-DarchetypeArtifactId=appfuse-light-struts-archetype -DarchetypeVersion=2.2.1
-DgroupId=com.mycompany -DartifactId=myproject
Example to get last article or any other element:
document.querySelector("article:last-child")
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
This answer extends on Jayson's excellent answer with some more opinionated guidance on the best approach for your use case:
Managing versions manually is probably the worst option. If you decide to manually switch versions, you can use this Bash code instead of Jayson's verbose code (code snippet from the homebrew-openjdk README:
jdk() {
version=$1
export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
java -version
}
Jayson's answer provides the basic commands for SDKMAN and jenv. Here's more info on SDKMAN and more info on jenv if you'd like more background on these tools.
double d = 28786.079999999998;
String str = String.format("%1.2f", d);
d = Double.valueOf(str);
If you want statically make columns not sortable. You can do this way
const toIntArray = (n) => ([...n + ""].map(v => +v))
_x000D_
You can pass the struct pointer to function as function argument. It called pass by reference.
If you modify something inside that pointer, the others will be updated to. Try like this:
typedef struct client_t client_t, *pno;
struct client_t
{
pid_t pid;
char password[TAM_MAX]; // -> 50 chars
pno next;
};
pno AddClient(client_t *client)
{
/* this will change the original client value */
client.password = "secret";
}
int main()
{
client_t client;
//code ..
AddClient(&client);
}
You can:
<input type="submit" ..>
, instead of that button.submit(..)
on it. Eg: form.submit()
. Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key
when it comes to authorization you use hashing.There is no key in hashing
Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password
why is hashing irreversible :
Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
<form method = 'post' action = '' id = 'theForm'>
...
</form>
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data
above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET
super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success
function is called, and any and all output produced by the PHP script will be stored in the variable html
.
...
success: function(html) {
alert(html);
}
...
To return all records from all indices you can do:
curl -XGET http://35.195.120.21:9200/_all/_search?size=50&pretty
Output:
"took" : 866,
"timed_out" : false,
"_shards" : {
"total" : 25,
"successful" : 25,
"failed" : 0
},
"hits" : {
"total" : 512034694,
"max_score" : 1.0,
"hits" : [ {
"_index" : "grafana-dash",
"_type" : "dashboard",
"_id" : "test",
"_score" : 1.0,
...
Below code shows the values that you can get from System API, these all things you can get through this API.
public class App {
public static void main( String[] args ) {
//Operating system name
System.out.println(System.getProperty("os.name"));
//Operating system version
System.out.println(System.getProperty("os.version"));
//Path separator character used in java.class.path
System.out.println(System.getProperty("path.separator"));
//User working directory
System.out.println(System.getProperty("user.dir"));
//User home directory
System.out.println(System.getProperty("user.home"));
//User account name
System.out.println(System.getProperty("user.name"));
//Operating system architecture
System.out.println(System.getProperty("os.arch"));
//Sequence used by operating system to separate lines in text files
System.out.println(System.getProperty("line.separator"));
System.out.println(System.getProperty("java.version")); //JRE version number
System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL
System.out.println(System.getProperty("java.vendor")); //JRE vendor name
System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)
System.out.println(System.getProperty("java.class.path"));
System.out.println(System.getProperty("file.separator"));
}
}
Answers:-
Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64
1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\
SELECT * FROM tbl WHERE trim(IFNULL(col,'')) <> '';
https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions
You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:
<MyComponent>foo</MyComponent> <MyComponent>{'foo'}</MyComponent>
This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:
function Item(props) { return <li>{props.message}</li>; } function TodoList() { const todos = ['finish doc', 'submit pr', 'nag dan to review']; return ( <ul> {todos.map((message) => <Item key={message} message={message} />)} </ul> ); }
class First extends React.Component {_x000D_
constructor(props) {_x000D_
super(props);_x000D_
this.state = {_x000D_
data: [{name: 'bob'}, {name: 'chris'}],_x000D_
};_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<ul>_x000D_
{this.state.data.map(d => <li key={d.name}>{d.name}</li>)}_x000D_
</ul>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<First />,_x000D_
document.getElementById('root')_x000D_
);_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="root"></div>
_x000D_
From JQuery Documentation
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax()
request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done()
for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail()
method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always()
method replaces the deprecated .complete()
method.
In response to a successful request, the function's arguments are the same as those of .done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail()
: the jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done()
and .fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then()
for implementation details.
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks are removed as of jQuery 3.0. You can usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
You can overlay a big, semi-transparent <div>
that takes all the clicks. Just append a new <div>
to <body>
with this style:
.overlay {
background-color: rgba(1, 1, 1, 0.7);
bottom: 0;
left: 0;
position: fixed;
right: 0;
top: 0;
}
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
ini_set('max_execution_time', 0);
or create file name called php.ini
and enter the first line max_execution_time=0
then save it and put the file in your root folder of your application.
That's it. Good luck.
On Visual Studio 2015 just go to: help/about Microsoft Visual Studio Then you will see something like this:
Microsoft Visual Studio Enterprise 2015 Version 14.0.24720.00 Update 1 Microsoft .NET Framework Version 4.6.01055
...
TypeScript 1.7.6.0 TypeScript for Microsoft Visual Studio
....
In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.
$this->container->getParameter('api_user');
This documentation chapter explains it.
While $this->get()
method in a controller will load a service (doc)
In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:
$this->getParameter('api_user');
A lot of the given answers fail on one or more of:
Here's what I wrote:
static int countMatches(Pattern pattern, String string)
{
Matcher matcher = pattern.matcher(string);
int count = 0;
int pos = 0;
while (matcher.find(pos))
{
count++;
pos = matcher.start() + 1;
}
return count;
}
Example call:
Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2
If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL
flag:
Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
Dir.pwd
seems to do the trick.
Multiline version (e.g. if you need to add comment after each line):
a = if b # a depends on b
then 5 # b is true
else 10 # b is false
1) In case you want to reload the same URL:
mWebView.loadUrl("http://www.websitehere.php");
so the full code would be
newButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dgeActivity.this.mWebView.loadUrl("http://www.websitehere.php");
}});
2) You can also call mWebView.reload()
but be aware this reposts a page if the request was POST, so only works correctly with GET.
In the earlier versions of MySQL ( < 5.7.5 ) the only way to set
'innodb_buffer_pool_size'
variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :
[mysqld]
innodb_buffer_pool_size = 2147483648
You need to restart your mysql server to have it's effect in action.
As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:
mysql> SET GLOBAL innodb_buffer_pool_size=402653184;
Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html
To add to Heath's answer: It looks like Subversion 1.6 disabled storing passwords by default if it can't store them in encrypted form. You can allow storing unencrypted passwords by explicitly setting password-stores =
(that is, to the empty value) in ~/.subversion/config
.
To check which password store subversion uses, look in ~/.subversion/auth/svn.simple
. This contains several files, each a hash table with a simple key/value encoding. The svn:realmstring
in each file identifies which realm that file is for. If the file has
K 8
passtype
V 6
simple
then it stores the password in plain text somewhere in that file, in a K 8 password
entry. Else, it tries to use one of the configured password-stores
.
As the detailed answer above says, this error can be caused by many things.
I had this problem too. My setup was Mac OSX 10.8, using a Vagrant managed VirtualBox VM of Ubuntu 12.04, with MySQL 5.5.34.
I had correctly setup port forwarding in the Vagrant config file. I could telnet to the MySQL instance both from my Mac and from within the VM. So I knew the MySQL daemon was running and reachable. But when I tried to connect over JDBC, I got the "Communications link failure" error.
In my case, the problem was solved by editing the /etc/mysql/my.cnf file. Specifically, I commented out the "#bind-address=127.0.0.1" line.
In your Manifest
define windowSoftInputMode
property:
<activity android:name=".MyActivity"
android:windowSoftInputMode="adjustNothing">
Before you can commit and push, you need to init a working repository tree for a submodule. I am using tortoise and do following things:
First check if there exist .git file (not a directory)
If there was .git file, there surly was .git directory which tracks local tree. You still need to a branch (you can create one) or switch to master (which sometimes does not work). Best to do is - git fetch - git pull. Do not omit fetch.
Now your commits and pulls will be synchronized with your origin/master
You must have to define encoding format
like utf-8
,
Try this easy way,
This example generates a random number using the SHA256 algorithm:
>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'
I have crossed with this issue many times, but I didnt try to dig deeper about it. Now I understand the main issue.
This time my problem was importing Serializers ( django and restframework ) from different modules such as the following :
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
# the line below was the problem 'srlzprod'
from products import serializers as srlzprod
I was getting a problem like this :
from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'
What I wanted to accomplished was the following :
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
# the nested relation of the line below
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
So, as mentioned by the lines above how to solve it ( top-level import ), I proceed to do the following changes :
# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by
product = serializers.SerializerMethodField()
# and create the following method and call from there the required serializer class
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
Therefore, django runserver was executed without problems :
./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...
System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.
Final state of the code lines was the following :
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
product = serializers.SerializerMethodField()
class Meta:
model = mdlpri.CampaignsProducts
fields = '__all__'
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
Hope this could be helpful for everybody else.
Greetings,
After installation of Oracle Client 11.02.04, reboot the server and make sure USERS(Local Computer) is added with Full Control on Root folder for eg WWW
Tested, it worked.
Pull changes first:
git pull origin branch_name
Check on yourCheckBox.Value
?
I am running an Iphone 8+ and VMWare macOS High Sierra on a Windows 10 machine.
I went through dozens of troubleshooting posts, and the none of them, excluding setting your VMs USBs to 2.0, helped. Through trial and error, and a decent amount of liquor, I have figured it out.
SOLUTION:
Do these things, in this order:
With the VM off, go to your settings for whichever machine you're using, and change the USBs to 2.0. You can find this in the same menu that you allocated your ram and cores
Make sure your phone is plugged in, and turned off.
Boot up the VM, macOS.
Turn Phone on when mac is booted
Open Xcode
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
You can also remove rows and columns by feeding a vector of logical boolean values to the matrix. This handles the situation where you have multiple non-contiguous rows or non-contiguous columns that need to be deleted.
# TRUE = Keep a row/column
# FALSE = Delete a row/column
#
# FALSE for rows 4, 5, and 6
# Row: 1 2 3 4 5 6 7 8 9 10
rows_to_keep <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
# FALSE for columns 7, 8, and 9
# Column: 1 2 3 4 5 6 7 8 9 10
cols_to_keep <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE)
To remove just the rows:
t1 <- t1[rows_to_keep,]
To remove just the columns:
t1 <- t1[,cols_to_keep]
To remove both the rows and columns:
t1 <- t1[rows_to_keep, cols_to_keep]
This coding technique is useful if you don't know in advance what rows or columns you need to remove. The rows_to_keep
and cols_to_keep
vectors can be calculated as appropriate by your code.
You could create another object that dispatches calls to magic methods to the underlying objects. Here's how you'd handle __get
, but to get it working fully you'd have to override all the relevant magic methods. You'll probably find syntax errors since I just entered it off the top of my head.
class Compositor {
private $obj_a;
private $obj_b;
public function __construct($obj_a, $obj_b) {
$this->obj_a = $obj_a;
$this->obj_b = $obj_b;
}
public function __get($attrib_name) {
if ($this->obj_a->$attrib_name) {
return $this->obj_a->$attrib_name;
} else {
return $this->obj_b->$attrib_name;
}
}
}
Good luck.
EDIT: The below answer no longer works see here
In Chrome or Opera, open a new tab and navigate to chrome://view-http-cache/
Click on whichever file you want to view. You should then see a page with a bunch of text and numbers. Copy all the text on that page. Paste it in the text box below.
Press "Go". The cached data will appear in the Results section below.
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
"Format" is your response type. Could be json or html, for example. It's the format of the output your visitor will receive.
# Pseudo code
# Corners in ax,ay,bx,by,dx,dy
# Point in x, y
bax = bx - ax
bay = by - ay
dax = dx - ax
day = dy - ay
if ((x - ax) * bax + (y - ay) * bay < 0.0) return false
if ((x - bx) * bax + (y - by) * bay > 0.0) return false
if ((x - ax) * dax + (y - ay) * day < 0.0) return false
if ((x - dx) * dax + (y - dy) * day > 0.0) return false
return true
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection. You can determine whether you are experiencing this more uncommon cause by using SHOW STATUS LIKE 'aborted_connections'. It will increase by one for each initial connection attempt that the server aborts. You may see “reading authorization packet” as part of the error message; if so, that also suggests that this is the solution that you need.
Try increasing connect_timeout in your my.cnf file
Another style:
MySQL: Lost connection to MySQL server at 'reading initial communication packet'
At some point, it was impossible for remote clients to connect to the MySQL server.
The client (some application on a Windows platform) gave a vague
description like Connection unexpectedly terminated
.
When remotely logging in with the MySQL client the following error appeared:
ERROR 2013 (HY000): Lost connection to MySQL server at 'reading initial communication packet', system error: 0
On FreeBSD this happens because there was no match found in /etc/hosts.allow.
Adding the following line before the line saying ALL:ALL
fixes this:
mysqld: ALL: allow
On non-FreeBSD Unix systems, it is worth to check the files /etc/hosts.allow
and /etc/hosts.deny.
If you are restricting connections, make sure this line is in /etc/hosts.allow
:
mysqld: ALL
or check if the host is listed in /etc/hosts.deny.
In Arch Linux, a similar line can be added to /etc/hosts.allow
:
mysqld: ALL
import string
asking = "".join(l for l in asking if l not in string.punctuation)
filter with string.punctuation
.
An optimized Imran Tariq's version
Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();
Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.
There is a very flaky coverage of the LIKE operator for dates in SQL Server. It only works using American date format. As an example you could try:
... WHERE register_date LIKE 'oct 10 2009%'
I've tested this in SQL Server 2005 and it works, but you'll really need to try different combinations. Odd things I have noticed are:
You only seem to get all or nothing for different sub fields within the date, for instance, if you search for 'apr 2%' you only get anything in the 20th's - it omits 2nd's.
Using a single underscore '_' to represent a single (wildcard) character does not wholly work, for instance, WHERE mydate LIKE 'oct _ 2010%'
will not return all dates before the 10th - it returns nothing at all, in fact!
The format is rigid American: 'mmm dd yyyy hh:mm
'
I have found it difficult to nail down a process for LIKEing seconds, so if anyone wants to take this a bit further, be my guest!
Hope this helps.
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
Just follow these steps i can assure pdf file will be generated
<html>
<head>
<title>Exporting table data to pdf Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/jspdf.js"></script>
<script type="text/javascript" src="js/from_html.js"></script>
<script type="text/javascript" src="js/split_text_to_size.js"></script>
<script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
<script type="text/javascript" src="js/cell.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#exportpdf").click(function() {
var pdf = new jsPDF('p', 'pt', 'ledger');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#yourTableIdName')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme' : function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top : 80,
bottom : 60,
left : 60,
width : 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width' : margins.width, // max width of content on PDF
'elementHandlers' : specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('fileNameOfGeneretedPdf.pdf');
}, margins);
});
});
</script>
</head>
<body>
<div id="yourTableIdName">
<table style="width: 1020px;font-size: 12px;" border="1">
<thead>
<tr align="left">
<th>Country</th>
<th>State</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
</tbody>
</table></div>
<input type="button" id="exportpdf" value="Download PDF">
</body>
</html>
Output:
Html file output:
Pdf file output:
Here's an extremely simple example:
import logging
l = logging.getLogger("test")
# Add a file logger
f = logging.FileHandler("test.log")
l.addHandler(f)
# Add a stream logger
s = logging.StreamHandler()
l.addHandler(s)
# Send a test message to both -- critical will always log
l.critical("test msg")
The output will show "test msg" on stdout and also in the file.
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
It can be changed in the $CATALINA_BASE/conf/server.xml
in the <Host />
. See the Tomcat documentation, specifically the section in regards to the Host container:
The default is webapps
relative to the $CATALINA_BASE
. An absolute pathname can be used.
Hope that helps.
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
For sql server (SSMS)
select MAX(LEN(ColumnName)) from table_name
This will returns number of characters.
select MAX(DATALENGTH(ColumnName)) from table_name
This will returns number of bytes used/required.
IF some one use varchar then use DATALENGTH
.More details
You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
This is a jQuery version of Moussawi7's answer.
$(function() {
$("textarea.auto-grow").on("input", function() {
var element = $(this)[0];
element.style.height = "5px";
element.style.height = (element.scrollHeight) + "px";
});
})
_x000D_
textarea {
resize: none;
overflow: auto;
width: 100%;
min-height: 50px;
max-height: 150px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="auto-grow"></textarea>
_x000D_
As other said, the comment in XML are like this
<!-- this is a comment -->
Notice that they can span on multiple lines
<!--
This is a comment
on multiple lines
-->
But they cannot be nested
<!-- This <!-- is a comment --> This is not -->
Also you cannot use them inside tags
<EditText <!--This is not valid--> android:layout_width="fill_parent" />
you can use the UNION ALL
keyword for this.
Here is the MSDN doc to do it in T-SQL http://msdn.microsoft.com/en-us/library/ms180026.aspx
UNION ALL - combines the result set
UNION- Does something like a Set Union and doesnt output duplicate values
For the difference with an example: http://sql-plsql.blogspot.in/2010/05/difference-between-union-union-all.html
Add private constructor:
private FilePathHelper(){
super();
}
One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.
>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0
Therefore, I use the following to test if a numpy array has elements:
>>> def elements(array):
... return array.ndim and array.size
>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24
My example
private options = new RequestOptions({headers: new Headers({'Content-Type': 'application/json'})});
My method
getUserByName(name: string): Observable<MyObject[]> {
//set request params
let params: URLSearchParams = new URLSearchParams();
params.set("name", name);
//params.set("surname", surname); for more params
this.options.search = params;
let url = "http://localhost:8080/test/user/";
console.log("url: ", url);
return this.http.get(url, this.options)
.map((resp: Response) => resp.json() as MyObject[])
.catch(this.handleError);
}
private handleError(err) {
console.log(err);
return Observable.throw(err || 'Server error');
}
in my component
userList: User[] = [];
this.userService.getUserByName(this.userName).subscribe(users => {
this.userList = users;
});
By postman
http://localhost:8080/test/user/?name=Ethem
Use /[^0-9.,]+/
if you want floats.
I think both the fastest and most concise way to do this is to use NumPy's built-in Fancy indexing. If you have an ndarray
named arr
, you can replace all elements >255
with a value x
as follows:
arr[arr > 255] = x
I ran this on my machine with a 500 x 500 random matrix, replacing all values >0.5 with 5, and it took an average of 7.59ms.
In [1]: import numpy as np
In [2]: A = np.random.rand(500, 500)
In [3]: timeit A[A > 0.5] = 5
100 loops, best of 3: 7.59 ms per loop
We can mock list properly for foreach loop. Please find below code snippet and explanation.
This is my actual class method where I want to create test case by mocking list.
this.nameList
is a list object.
public void setOptions(){
// ....
for (String str : this.nameList) {
str = "-"+str;
}
// ....
}
The foreach loop internally works on iterator, so here we crated mock of iterator.
Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn()
, i.e. on hasNext()
we pass 1st true and on second call false, so that our loop will continue only two times. On next()
we just return actual return value.
@Test
public void testSetOptions(){
// ...
Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
Mockito.when(itr.hasNext()).thenReturn(true, false);
Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);
List mockNameList = Mockito.mock(List.class);
Mockito.when(mockNameList.iterator()).thenReturn(itr);
// ...
}
In this way we can avoid sending actual list to test by using mock of list.
GitHub now has an import option that lets you choose whatever you want your new imported repository public or private
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
Maven remembers when it didn't find something. The key is "resolution will not be reattempted until the update interval of internal has elapsed or updates are forced ->"
The quick solution is to delete your local "repository" subdirectory for the problem artifact - assuming you have fixed the problem with it. :)
mvn -U
will force update from remote repository - again, assuming you have now populated remote with said artifact.
In drawable assets there was an image format which was an unsupported image. When i removed the image every thing started working fine.
Dictionary Class is exactly what you want, correct.
You can declare the field directly as Dictionary, instead of IDictionary, but that's up to you.
If you are using bootstrap-datepicker you may use this style:
$('#datepicker').datepicker('setStartDate', "01-01-1900");
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)
Just go through these links,
Run Android on Your Windows Mobile Phone
full tutorial on how to put android on windows mobile touch pro 2
How to install Android on most Windows Mobile phones
Update:
For Windows 7 to Android device, this also possible, (You need to do some hack for this)
Just go through these links,
Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]
HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND
Install windows phone 7 on android and iphones | Tips and Tricks
How to install Windows Phone 7 on HTC HD2? (Video)
To Install Android on your iOS Devices (This also possible...)
I combined the two above, because I needed to merge 3 pdfbytes and return a byte
internal static byte[] mergePdfs(byte[] pdf1, byte[] pdf2,byte[] pdf3)
{
MemoryStream outStream = new MemoryStream();
using (Document document = new Document())
using (PdfCopy copy = new PdfCopy(document, outStream))
{
document.Open();
copy.AddDocument(new PdfReader(pdf1));
copy.AddDocument(new PdfReader(pdf2));
copy.AddDocument(new PdfReader(pdf3));
}
return outStream.ToArray();
}
Just create a new array in your dictionary
Dictionary<string, List<string>> myDic = new Dictionary<string, List<string>>();
myDic.Add(newKey, new List<string>(existingList));
You can do it as following:
class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
ProjectInfo(string n, long id)
{
name = n; Id = id;
}
}
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(pro.ProjectName,pro.ProjectId);
return query.ToList<ProjectInfo>();
}
}
In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:
1) Mount your google drive in google colab:
from google.colab import drive
drive.mount('/content/gdrive/')
2) Append the directory to your python path using sys:
import sys
sys.path.append('/content/gdrive/mypythondirectory')
Now you should be able to import stuff from that directory!
I agree with Ken's answer as being the most dynamic and I like to take it a step further. If it's a function that you call multiple times with different arguments - I use Ken's design but then add default values:
function load(context) {
var defaults = {
parameter1: defaultValue1,
parameter2: defaultValue2,
...
};
var context = extend(defaults, context);
// do stuff
}
This way, if you have many parameters but don't necessarily need to set them with each call to the function, you can simply specify the non-defaults. For the extend method, you can use jQuery's extend method ($.extend()
), craft your own or use the following:
function extend() {
for (var i = 1; i < arguments.length; i++)
for (var key in arguments[i])
if (arguments[i].hasOwnProperty(key))
arguments[0][key] = arguments[i][key];
return arguments[0];
}
This will merge the context object with the defaults and fill in any undefined values in your object with the defaults.
If someone interested to know how to work with 2 list and between dates
var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))
fwrite()
is a smidgen faster and file_put_contents()
is just a wrapper around those three methods anyway, so you would lose the overhead.
Article
file_put_contents(file,data,mode,context):
The file_put_contents
writes a string to a file.
This function follows these rules when accessing a file.If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename Create the file if it does not exist then Open the file and Lock the file if LOCK_EX is set and If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content Write the data into the file and Close the file and release any locks. This function returns the number of the character written into the file on success, or FALSE on failure.
fwrite(file,string,length):
The fwrite
writes to an open file.The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.This function returns the number of bytes written or FALSE on failure.
You can run the SQL Profiler, and filter by CPU or Duration so that you're excluding all the "small stuff". Then it should be a lot easier to determine if you have a problem like a specific stored proc that is running much longer than it should (could be a missing index or something).
Two caveats:
But normally I start with the Activity Monitor or sp_who2.
After struggling with the same problem, I tried two different solutions that works:
""
) with your variables.Easiest way just double quotes your variables as pointed in previous answer:
cd "$yourPathWithBlankSpace"
eval
.According to this answer Unix command to escape spaces you can strip blank space then make use of eval
, like this:
yourPathEscaped=$(printf %q "$yourPathWithBlankSpace")
eval cd $yourPathEscaped
Just move it :)
command line :
move "C:\Documents and Setings\$USER\project" C:\project
or just drag the folder in explorer.
Git won't care where it is - all the metadata for the repository is inside a folder called .git
inside your project folder.
This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)
turning it back to 1.0.7 solved the problem instantly.
have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.
anyway, this problem is fixed when using AngularJS vs 1.0.7.
To sum up, 'valid' padding means no padding. The output size of the convolutional layer shrinks depending on the input size & kernel size.
On the contrary, 'same' padding means using padding. When the stride is set as 1, the output size of the convolutional layer maintains as the input size by appending a certain number of '0-border' around the input data when calculating convolution.
Hope this intuitive description helps.
Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.
Try setting the z-index higher on the contained element.
Its possible you don't need to know depending on what you are doing with it.
String myString = object.toString();
or if object can be null
String myString = String.valueOf(object);
The length in NTFS is 255. The NameLength
field in the NTFS $Filename
attribute is a byte with no offset; this yields a range of 0-255.
The file name iself can be in different "namespaces". So far there are: POSIX, WIN32, DOS and (WIN32DOS - when a filename can be natively a DOS name). (Since the string has a length, it could contain \0 but that would yield to problems and is not in the namespaces above.)
Thus the name of a file or directory can be up to 255 characters. When specifying the full path under Windows, you need to prefix the path with \\?\ (or use \\?\UNC\server\share for UNC paths) to mark this path as an extended-length one (~32k characters). If your path is longer, you will have to set your working directory along the way (ugh - side effects due to the process-wide setting).
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
extension String {
func subString(from: Int, to: Int) -> String {
let startIndex = self.index(self.startIndex, offsetBy: from)
let endIndex = self.index(self.startIndex, offsetBy: to)
return String(self[startIndex..<endIndex])
}
}
Usage:
var str = "Hello, Nick Michaels"
print(str.subString(from:7,to:20))
// print Nick Michaels
Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.
If you want to use objects as keys you need to overwrite their toString Method, as some already mentioned here. The hash functions that were used are all fine, but they only work for the same objects not for equal objects.
I've written a small library that creates hashes from objects, which you can easily use for this purpose. The objects can even have a different order, the hashes will be the same. Internally you can use different types for your hash (djb2, md5, sha1, sha256, sha512, ripemd160).
Here is a small example from the documentation:
var hash = require('es-hash');
// Save data in an object with an object as a key
Object.prototype.toString = function () {
return '[object Object #'+hash(this)+']';
}
var foo = {};
foo[{bar: 'foo'}] = 'foo';
/*
* Output:
* foo
* undefined
*/
console.log(foo[{bar: 'foo'}]);
console.log(foo[{}]);
The package can be used either in browser and in Node-Js.
Repository: https://bitbucket.org/tehrengruber/es-js-hash
Example - sending some data encoded as JSON as a POST data:
import json
import urllib2
data = json.dumps([1, 2, 3])
f = urllib2.urlopen(url, data)
response = f.read()
f.close()
Try this. Why are you using RegistrationIntentService
?
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
}
}
Make sure you have settings.xml. I had the same problem when I've deleted it by mistake.
I need to copy folder recursively, after trying different solutions, finally end up by ProcessBuilder + expect/spawn
scpFile("192.168.1.1", "root","password","/tmp/1","/tmp");
public void scpFile(String host, String username, String password, String src, String dest) throws Exception {
String[] scpCmd = new String[]{"expect", "-c", String.format("spawn scp -r %s %s@%s:%s\n", src, username, host, dest) +
"expect \"?assword:\"\n" +
String.format("send \"%s\\r\"\n", password) +
"expect eof"};
ProcessBuilder pb = new ProcessBuilder(scpCmd);
System.out.println("Run shell command: " + Arrays.toString(scpCmd));
Process process = pb.start();
int errCode = process.waitFor();
System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(process.getInputStream()));
if(errCode != 0) throw new Exception();
}
A simple example of O(1)
might be return 23;
-- whatever the input, this will return in a fixed, finite time.
A typical example of O(N log N)
would be sorting an input array with a good algorithm (e.g. mergesort).
A typical example if O(log N)
would be looking up a value in a sorted input array by bisection.
Try this:
listItems = $("#productList").find("li").each(function(){
var product = $(this);
// rest of code.
});
Or simpler you can put between your tags first, then to the css class.
<div style="height: 35px;overflow-y: auto;"> Some text o othre div scroll </div>
If its ok to use JavaScript here is my solution Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!
Tested in: Opera, Chrome, Safari, FF, IE5.5(Epic script fail), IE6, IE7, IE8, IE9
//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width
$(document).ready(function () {
$("table.Scrollify").each(function (index, element) {
var header = $(element).children().children().first();
var headerHtml = header.html();
var width = $(element).outerWidth();
var height = parseInt($(element).css("height")) - header.outerHeight();
$(element).height("auto");
header.remove();
var html = "<table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"><tr>" + headerHtml +
"</tr></table><div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\">" +
$(element).parent().html() + "</div>";
$(element).parent().html(html);
});
});
//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels
//License: Apache License, version 2
function scrollbarWidth() {
var scr = null;
var inn = null;
var wNoScroll = 0;
var wScroll = 0;
// Outer scrolling div
scr = document.createElement('div');
scr.style.position = 'absolute';
scr.style.top = '-1000px';
scr.style.left = '-1000px';
scr.style.width = '100px';
scr.style.height = '50px';
// Start with no scrollbar
scr.style.overflow = 'hidden';
// Inner content div
inn = document.createElement('div');
inn.style.width = '100%';
inn.style.height = '200px';
// Put the inner div in the scrolling div
scr.appendChild(inn);
// Append the scrolling div to the doc
document.body.appendChild(scr);
// Width of the inner div sans scrollbar
wNoScroll = inn.offsetWidth;
// Add the scrollbar
scr.style.overflow = 'auto';
// Width of the inner div width scrollbar
wScroll = inn.offsetWidth;
// Remove the scrolling div from the doc
document.body.removeChild(
document.body.lastChild);
// Pixel width of the scroller
return (wNoScroll - wScroll);
}
Edit: Fixed height.
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
x = [i for i in x if len(i)==2]
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.
Anyway, the php
command offers two switches to execute code from the command line:
-r <code> Run PHP <code> without using script tags <?..?>
-R <code> Run PHP <code> for every input line
You can use php
's -r switch as such:
php -r 'echo function_exists("foo") ? "yes" : "no";'
The above PHP command above should output no
and returns 0
as you can see:
>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0
Another funny switch is php -a:
-a Run as interactive shell
It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:
>>> php -a
Interactive shell
php > echo function_exists("foo") ? "yes" : "no";
no
php >
If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:
php -i | grep 'API'
You should see:
Server API => Command Line Interface
If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.
If you do see that your php
command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code
to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.
Another couple of examples, just to make sure it works on my boxes:
>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes
Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini
vs. /etc/php/cgi/php.ini
vs. /etc/php/apache/php.ini
on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini
.
I got same issue and i just add JAVA_HOME
to environment variables.
JAVA_HOME
open command prompt from project directory and run mvn clean install
(don't use intellij terminal).After reading all these explanations I thought I'd weigh in with the method my professor used to explain the Towers of Hanoi recursive solution. Here is the algorithm again with n representing the number of rings, and A, B, C representing the pegs. The first parameter of the function is the number of rings, second parameter represents the source peg, the third is the destination peg, and fourth is the spare peg.
procedure Hanoi(n, A, B, C);
if n == 1
move ring n from peg A to peg B
else
Hanoi(n-1, A, C, B);
move ring n-1 from A to C
Hanoi(n-1, C, B, A);
end;
I was taught in graduate school to never to be ashamed to think small. So, let's look at this algorithm for n = 5. The question to ask yourself first is if I want to move the 5th ring from A to B, where are the other 4 rings? If the 5th ring occupies peg A and we want to move it to peg B, then the other 4 rings can only be on peg C. In the algorithm above the function Hanoi (n-1, A, C, B) is trying to move all those 4 other rings on to peg C, so ring 5 will be able to move from A to B. Following this algorithm we look at n = 4. If ring 4 will be moved from A to C, where are rings 3 and smaller? They can only be on peg B. Next, for n = 3, if ring 3 will be moved from A to B, where are rings 2 and 1? On peg C of course. If you continue to follow this pattern you can visualize what the recursive algorithm is doing. This approach differs from the novice's approach in that it looks at the last disk first and the first disk last.
How about using the entity codes...
@ = %40
& = %26
So, you would have:
curl -d 'name=john&passwd=%4031%263*J' https://www.mysite.com
With plain Javascript, the simplest is:
document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};
But with this, you can only bind one handler for the event.
In addition, you could use the following to be able to potentially bind multiple handlers to the same event:
addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
In either case, keyCode
isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event
- that's a normal problem with Internet Explorer, putting the event in window.event
instead of passing it to the callback.
References:
With jQuery:
$(document).on("keypress", function (e) {
// use e.which
});
Reference:
Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e
(the event) and e.which
(the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.
Note there is a keydown
event, that is different than keypress
. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown
As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.
Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.
Here's something that might help decide:
Following @jxstanford and @tvt173, I wrote a quick function which should do the trick, regardless of string/int column names:
def flatten_cols(df):
df.columns = [
'_'.join(tuple(map(str, t))).rstrip('_')
for t in df.columns.values
]
return df
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
You have to modify the php.ini file by removing the semi-colon on the line containing extension=php_intl.dll
After this, go to the php folder of Xamp or Wamp or EasyPHP, copy every dll file containing icu*, Paste them inside your windows file.
That worked for me. Configuration : EasyPHP Dev Server, Windows 10.
Doesn't answer the question directly, but I found this question when searching for a way to, basically, not re-enter the password every single time I pull on a remote server.
Well, git
allows you to cache your credentials for a finite amount of time. It's customizable in git config
and this page explains it very well:
https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux
In a terminal, run:
$ git config --global credential.helper cache
# Set git to use the credential memory cache
To customize the cache timeout, you can do:
$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)
Your credentials will then be stored in-memory for the requested amount of time.
This is a very old, but still very useful thread. I came here recently with the same issue. I suggest protecting the sheet when appropriate and unprotecting it when the filter row (eg Row 1) is selected. My solution doesn't use password protection - I don't need it (its a safeguard, not a security feature). I can't find an event handler that recognizes selection of a filter button - so I gave the instruction to my users to first select the filter cell then click the filter button. Here's what I advocate, (I only change protection if it needs to be changed, that may or may not save time - I don't know, but it "feels" right):
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Const FilterRow = 1
Dim c As Range
Dim NotFilterRow As Boolean
Dim oldstate As Boolean
Dim ws As Worksheet
Set ws = ActiveSheet
oldstate = ws.ProtectContents
NotFilterRow = False
For Each c In Target.Cells
NotFilterRow = c.Row <> FilterRow
If NotFilterRow Then Exit For
Next c
If NotFilterRow <> oldstate Then
If NotFilterRow Then
ws.Protect
Else
ws.Unprotect
End If
End If
Set ws = Nothing
End Sub
-if gradle.properties not available then first add that file and
add
android.useDeprecatedNdk=true
-use this code in build.gradle
defaultConfig {
applicationId 'com.example.application'
minSdkVersion 16
targetSdkVersion 21
versionCode 11
versionName "1.1"
ndk {
abiFilters "armeabi"
}
}
`
The answer above is kind of correct, you can't gracefully control how much native memory a java process allocates. It depends on what your application is doing.
That said, depending on platform, you may be able to do use some mechanism, ulimit for example, to limit the size of a java or any other process.
Just don't expect it to fail gracefully if it hits that limit. Native memory allocation failures are much harder to handle than allocation failures on the java heap. There's a fairly good chance the application will crash but depending on how critical it is to the system to keep the process size down that might still suit you.
Try calling the .load() method before the .play() method on the audio or video tag... which will be HTMLAudioElement or HTMLVideoElement respectively. That was the only way it would work on the iPad for me!
npm fund [<pkg>]
This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund
With .Net Core it is now very easy:
Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d
If you're on Windows, this might work:
There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:
thanks edwardaa's answer https://stackoverflow.com/a/30701422/2227031
Another point to note is that:
if total spacing and total itemWidth are not equal to the screen width, you also need to adjust itemWidth, for example, on adapter onBindViewHolder method
Utils.init(_mActivity);
int width = 0;
if (includeEdge) {
width = ScreenUtils.getScreenWidth() - spacing * (spanCount + 1);
} else {
width = ScreenUtils.getScreenWidth() - spacing * (spanCount - 1);
}
int itemWidth = width / spanCount;
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) holder.imageViewAvatar.getLayoutParams();
// suppose the width and height are the same
layoutParams.width = itemWidth;
layoutParams.height = itemWidth;
holder.imageViewAvatar.setLayoutParams(layoutParams);
All STL container are externally represented as "sequences" with one iteration mechanism. Trees don't follow this idiom.
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
Add this in MainActivity.
Intent intent = new Intent(getApplicationContext(), Heightimage.class);
startActivity(intent);
i think this is shortest code for finding primes with eratosthenes method
def prime(r):
n = range(2,r)
while len(n)>0:
yield n[0]
n = [x for x in n if x not in range(n[0],r,n[0])]
print(list(prime(r)))
And here the solution for C#/Xamarin.Android:
var token = await FirebaseInstallations.Instance.GetToken(forceRefresh: false).AsAsync<InstallationTokenResult>();
This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.
To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell
2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.
Import-Module MSOnline
After it complete, we can use this command to check it.
PS C:\Users> Get-Module -ListAvailable -Name MSOnline*
Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.1.166.0 MSOnline {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest 1.1.166.0 MSOnlineExtended {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
More information about this issue, please refer to it.
Update:
We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.
@media print{_x000D_
body{_x000D_
visibility: hidden; /* no print*/_x000D_
}_x000D_
.print{_x000D_
_x000D_
visibility:visible; /*print*/_x000D_
}_x000D_
}
_x000D_
<body>_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="print"> <!---print--->_x000D_
<div class="print"> <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
Firstly you need to setup a media streaming server. You can use Wowza, red5 or nginx-rtmp-module. Read their documentation and setup on OS you want. All the engine are support HLS (Http Live Stream protocol that was developed by Apple). You should read documentation for config. Example with nginx-rtmp-module:
rtmp {
server {
listen 1935; # Listen on standard RTMP port
chunk_size 4000;
application show {
live on;
# Turn on HLS
hls on;
hls_path /mnt/hls/;
hls_fragment 3;
hls_playlist_length 60;
# disable consuming the stream from nginx as rtmp
deny play all;
}
}
}
server {
listen 8080;
location /hls {
# Disable cache
add_header Cache-Control no-cache;
# CORS setup
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
add_header 'Access-Control-Allow-Headers' 'Range';
# allow CORS preflight requests
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /mnt/;
}
}
After server was setup and configuration successful. you must use some rtmp encoder software (OBS, wirecast ...) for start streaming like youtube or twitchtv.
In client side (browser in your case) you can use Videojs or JWplayer to play video for end user. You can do something like below for Videojs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Streaming</title>
<link href="//vjs.zencdn.net/5.8/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.8/video.min.js"></script>
</head>
<body>
<video id="player" class="video-js vjs-default-skin" height="360" width="640" controls preload="none">
<source src="http://localhost:8080/hls/stream.m3u8" type="application/x-mpegURL" />
</video>
<script>
var player = videojs('#player');
</script>
</body>
</html>
You don't need to add others plugin like flash (because we use HLS not rtmp). This player can work well cross browser with out flash.
You Can't write JSON file while in assets. as already described assets are read-only. But you can copy assets (json file/anything else in assets ) to local storage of mobile and then edit(write/read) from local storage. More storage options like shared Preference(for small data) and sqlite database(for large data) are available.
A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like:
CREATE VIEW v_emp
AS
SELECT *
FROM emp E
INNER JOIN settings S
ON S.Id = 1 AND E.emp_id = S.Param1
I hear that this can be fixed by overwriting your /usr/share/terminfo
with one from the computer of somebody with a working install of Lion. I can't confirm whether this works or not, and unfortunately I haven't upgraded yet, so I can't provide you with that file.
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
I'm using a minSdkVersion 16 and targetSdkVersion 23.
The following is working for me, it uses
ContextCompat.getDrawable(context, R.drawable.drawable);
Instead of using:
layout.setBackgroundResource(R.drawable.ready);
Rather use:
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
getActivity()
is used in a fragment, if calling from a activity use this
.
I added the spring folder to the build path and, after clean&build, it worked.
I have similar solution but might be useful for pandas
import math
import re
from collections import Counter
import pandas as pd
WORD = re.compile(r"\w+")
def get_cosine(vec1, vec2):
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x] ** 2 for x in list(vec1.keys())])
sum2 = sum([vec2[x] ** 2 for x in list(vec2.keys())])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
if not denominator:
return 0.0
else:
return float(numerator) / denominator
def text_to_vector(text):
words = WORD.findall(text)
return Counter(words)
df=pd.read_csv('/content/drive/article.csv')
df['vector1']=df['headline'].apply(lambda x: text_to_vector(x))
df['vector2']=df['snippet'].apply(lambda x: text_to_vector(x))
df['simscore']=df.apply(lambda x: get_cosine(x['vector1'],x['vector2']),axis=1)
This method will not truncate a word in the middle.
list($output)=explode("\n",wordwrap(strip_tags($str),500),1);
echo $output. ' ... <a href="#">Read more</a>';
You can also use the following syntax:-
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
From here
android:background="@drawable/eye"
works automatically.
android:src="@drawable/eye"
was what I used with all the problems of resizing the image the the width and height of the button...
I will post the new "way" with androidx
in a short answer (because in some case you does not need custom registry or contract). If you want more informations see : https://developer.android.com/training/basics/intents/result
Important : there is actually a bug with the backward compatibility of androidx so you have to add fragment_version
in your gradle file. Otherwise you will get an exception "New result API error : Can only use lower 16 bits for requestCode".
dependencies {
def activity_version = "1.2.0-beta01"
// Java language implementation
implementation "androidx.activity:activity:$activity_version"
// Kotlin
implementation "androidx.activity:activity-ktx:$activity_version"
def fragment_version = "1.3.0-beta02"
// Java language implementation
implementation "androidx.fragment:fragment:$fragment_version"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
Now you just have to add this member variable of your activity. This use a predefined registry and generic contract.
public class MyActivity extends AppCompatActivity{
...
/**
* Activity callback API.
*/
// https://developer.android.com/training/basics/intents/result
private ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
switch (result.getResultCode()) {
case Activity.RESULT_OK:
Intent intent = result.getData();
// Handle the Intent
Toast.makeText(MyActivity.this, "Activity returned ok", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(MyActivity.this, "Activity canceled", Toast.LENGTH_SHORT).show();
break;
}
}
});
Before new API you had :
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
startActivityForResult(intent, Constants.INTENT_EDIT_REQUEST_CODE);
}
});
You may notice that the request code is now generated (and holded) by the google framework. Your code become.
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity .this, EditActivity.class);
mStartForResult.launch(intent);
}
});
Hope my answer will help some people !
Your query translates to:
SELECT name FROM users WHERE id IN ('Array');
Or something to that affect.
Try using prepared queries instead, something like:
$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
$ints = array_map(function(){ return 'i'; }, $numbers);
call_user_func_array("mysqli_stmt_bind_param", array_merge(
array($statement, implode('', $ints)), $numbers
));
$results = mysqli_stmt_execute($statement);
// do something with results
// ...
}
**
operator would be helpful here.
**
operator will unpack the dict elements and thus **{'type':'Event'}
would be treated as type='Event'
func(**{'type':'Event'})
is same as func(type='Event')
i.e the dict elements would be converted to the keyword arguments
.
FYI
*
will unpack the list elements and they would be treated as positional arguments
.
func(*['one', 'two'])
is same as func('one', 'two')
This worked for me.
def parse_data():
if request.method == "POST":
data = request.get_json()
print(data['answers'])
return render_template('output.html', data=data)
$.ajax({
type: 'POST',
url: "/parse_data",
data: JSON.stringify({values}),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(data){
// do something with the received data
}
});
function initialize() {
var location = new google.maps.LatLng(44.5403, -78.5463);
var mapCanvas = document.getElementById('map_canvas');
var map_options = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Here's what I did which worked:
yum install python-pip
pip install -U multi-mechanize
In modern browsers you could use a CSS3 & HTML5 progress Element!
progress {_x000D_
width: 40%;_x000D_
display: block; /* default: inline-block */_x000D_
margin: 2em auto;_x000D_
padding: 3px;_x000D_
border: 0 none;_x000D_
background: #444;_x000D_
border-radius: 14px;_x000D_
}_x000D_
progress::-moz-progress-bar {_x000D_
border-radius: 12px;_x000D_
background: orange;_x000D_
_x000D_
}_x000D_
/* webkit */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0) {_x000D_
progress {_x000D_
height: 25px;_x000D_
}_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
background: transparent;_x000D_
} _x000D_
progress::-webkit-progress-value { _x000D_
border-radius: 12px;_x000D_
background: orange;_x000D_
}
_x000D_
<progress max="100" value="40"></progress>
_x000D_
The best and the coolest way to add new data to the present data is
ArrayList<String> newItems = new ArrayList<String>();
newItems = getList();
int oldListItemscount = alcontainerDetails.size();
alcontainerDetails.addAll(newItems);
recyclerview.getAdapter().notifyItemChanged(oldListItemscount+1, al_containerDetails);
When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.
You can use RTRIM
or cast your value to VARCHAR
:
SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)
Or
SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
As far as I know, there are 2 standard ways you can do that.
1. @Input
Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.
Parent-Component
public inputToChild: Object;
Parent-HTML
<child [data]="inputToChild"> </child>
Child-Component: @Input() data;
ngOnChanges(changes: { [property: string]: SimpleChange }){
// Extract changes to the input property by its name
let change: SimpleChange = changes['data'];
// Whenever the data in the parent changes, this method gets triggered. You
// can act on the changes here. You will have both the previous value and the
// current value here.
}
Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.
SharedService
subject: Subject<Object>;
Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);
Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{
// Whenever the parent emits using the next method, you can receive the data
in here and act on it.})
If you are using a lot of memory and facing memory leaks, then you might want to check if you are using a large number of ArrayList
s or HashMap
s with many elements each.
An ArrayList
is implemented as a dynamic array. The source code from Sun/Oracle shows that when a new element is inserted into a full ArrayList
, a new array of 1.5 times the size of the original array is created, and the elements copied over. What this means is that you could be wasting up to 50% of the space in each ArrayList
you use, unless you call its trimToSize
method. Or better still, if you know the number of elements you are going to insert before hand, then call the constructor with the initial capacity as its argument.
I did not examine the source code for HashMap
very carefully, but at a first glance it appears that the array length in each HashMap
must be a power of two, making it another implementation of a dynamic array. Note that HashSet
is essentially a wrapper around HashMap
.
All of the answers above may work for the time being but whenever you run maven on the command line or Maven → Update project… the JDK will be reset, this was also the question as I understand it.
To fix this for good add the following code to your pom file. Remember to do a Maven → Update project… afterwards or mvn clean compile
at the command line.
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
synchronized
is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized
block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.
volatile
is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile
variables. All threads can access volatile variable value at same time.
A good example to use volatile variable : Date
variable.
Assume that you have made Date variable volatile
. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.
Have a look at this article for better understanding of volatile
concept.
Lawrence Dol cleary explained your read-write-update query
.
Regarding your other queries
When is it more suitable to declare variables volatile than access them through synchronized?
You have to use volatile
if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.
Is it a good idea to use volatile for variables that depend on input?
Answer will be same as in first query.
Refer to this article for better understanding.
You can disable them altogether by
(setq make-backup-files nil)
Select the text.
Right Click.
Plugin Commands -> Copy Text with Syntax Highlighting
Paste it into Word or whatever.
This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.Here is the best way to do it:
SELECT sys.tables.object_id, sys.tables.name as table_name, sys.columns.name as column_name, sys.indexes.name as index_name,
sys.indexes.is_unique, sys.indexes.is_primary_key
FROM sys.tables, sys.indexes, sys.index_columns, sys.columns
WHERE (sys.tables.object_id = sys.indexes.object_id AND sys.tables.object_id = sys.index_columns.object_id AND sys.tables.object_id = sys.columns.object_id
AND sys.indexes.index_id = sys.index_columns.index_id AND sys.index_columns.column_id = sys.columns.column_id)
AND sys.tables.name = 'your_table_name'
I prefer using implicit joins as it's much easier for me to understand. You can remove the object_id reference as you might not need it.
Cheers.
I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.
Hit F1 for vscode command line (command palette), then
ext install [enter] peep [enter]
You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep
, select Peep Toggle and add your binding.
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__()
and __next__()
.
The __iter__
returns the iterator object and is implicitly called
at the start of loops.
The __next__()
method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here's a simple example of a counter:
class Counter:
def __init__(self, low, high):
self.current = low - 1
self.high = high
def __iter__(self):
return self
def __next__(self): # Python 2: def next(self)
self.current += 1
if self.current < self.high:
return self.current
raise StopIteration
for c in Counter(3, 9):
print(c)
This will print:
3
4
5
6
7
8
This is easier to write using a generator, as covered in a previous answer:
def counter(low, high):
current = low
while current < high:
yield current
current += 1
for c in counter(3, 9):
print(c)
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.
David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
That would work depending on what client.get does when passed undefined as its first parameter.
Something like this would be safer:
app.get('/:key?', function(req, res, next) {
var key = req.params.key;
if (!key) {
next();
return;
}
client.get(key, function(err, reply) {
if(client.get(reply)) {
res.redirect(reply);
}
else {
res.render('index', {
link: null
});
}
});
});
There's no problem in calling next() inside the callback.
According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.
The answer is correct, however the perl documentation on how to handle deadlocks is a bit sparse and perhaps confusing with PrintError, RaiseError and HandleError options. It seems that rather than going with HandleError, use on Print and Raise and then use something like Try:Tiny to wrap your code and check for errors. The below code gives an example where the db code is inside a while loop that will re-execute an errored sql statement every 3 seconds. The catch block gets $_ which is the specific err message. I pass this to a handler function "dbi_err_handler" which checks $_ against a host of errors and returns 1 if the code should continue (thereby breaking the loop) or 0 if its a deadlock and should be retried...
$sth = $dbh->prepare($strsql);
my $db_res=0;
while($db_res==0)
{
$db_res=1;
try{$sth->execute($param1,$param2);}
catch
{
print "caught $_ in insertion to hd_item_upc for upc $upc\n";
$db_res=dbi_err_handler($_);
if($db_res==0){sleep 3;}
}
}
dbi_err_handler should have at least the following:
sub dbi_err_handler
{
my($message) = @_;
if($message=~ m/DBD::mysql::st execute failed: Deadlock found when trying to get lock; try restarting transaction/)
{
$caught=1;
$retval=0; # we'll check this value and sleep/re-execute if necessary
}
return $retval;
}
You should include other errors you wish to handle and set $retval depending on whether you'd like to re-execute or continue..
Hope this helps someone -
If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.
Setting the value in the .config file from within your program:
Is a mess;
Might not be read until the next application start.
If it is only something that needs to be done once per installation, I'd agree with the other posters and use the .config file and the dynamic setting.
Do you really need an object? What about:
$myArray[] = array("name" => "my name");
Just use a two-dimensional array.
Output (var_dump):
array(1) {
[0]=>
array(1) {
["name"]=>
string(7) "my name"
}
}
You could access your last entry like this:
echo $myArray[count($myArray) - 1]["name"];
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.
The CSS:
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}
I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.
Very smooth.
My solution if you work with the Trunk/
and Release/
workflow:
Right click on Trunk/
which you will be creating your Branch from:
Select Branch/Tag:
Type in location of your new branch, commit message, and any externals (if your repository has them):
http://caniuse.com/#search=::after
::after
and ::before
with content
are better to use as they're supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.
Is this what you're looking for?
.Modal::after{
content:url('blackCarrot.png'); /* with class ModalCarrot ??*/
position:relative; /*or absolute*/
z-index:100000; /*a number that's more than the modal box*/
left:-50px;
top:10px;
}
.ModalCarrot{
position:absolute;
left:50%;
margin-left:-8px;
top:-16px;
}
If not, can you explain a little better?
or you could use jQuery, like Joshua said:
$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");
I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :
I use a : ArrayList<BasicNameValuePair> params
and fill it this way :
params.add(new BasicNameValuePair("apikey", apikey);
I do not use any JSONObject to send params to the webservices.
Are you obliged to use the JSONObject ?
select * from [Table_Name] limit 5
You'll need to run mysql_install_db
- easiest way is if you're in the install directory:
$ cd /usr/local/Cellar/mysql/<version>/
$ mysql_install_db
Alternatively, you can feed mysql_install_db
a basedir
parameter like the following:
$ mysql_install_db --basedir="$(brew --prefix mysql)"
Recent sdk-manager's download does not contain android-support-v7-appcompat.jar But the following dir contains aar file C:\Users\madan\android-sdks\extras\android\m2repository\com\ android\support\appcompat-v7\24.2.1\appcompat-v7-24.2.1.aar This file can be imported by right-click project, import, select general, select archieve and finally select aar file. Even this does not solve the problem. Later remove 'import android.R' and add 'import android.support.v7.appcompat.*;' Follow this tutorial for other details: http://www.srccodes.com/p/article/22/android-hello-world-example-using-eclipse-ide-and-android-development-tools-adt-plugin
in kotlin :
val sharingIntent = Intent(android.content.Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
val shareBody = "Application Link : https://play.google.com/store/apps/details?id=${App.context.getPackageName()}"
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "App link")
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody)
startActivity(Intent.createChooser(sharingIntent, "Share App Link Via :"))
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
There are a couple of things that need to be adjusted in your layout:
You are nesting col
elements within form-group
elements. This should be the other way around (the form-group
should be within the col-sm-xx
element).
You should always use a row
div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12
is still on the same row with the above 3 .col-sm-4
resulting in a total of columns greater than 12, and causing the overlap problem.
Here is a fixed demo.
And an excerpt of what the problematic section HTML should become:
<fieldset>
<legend>Personal Information</legend>
<div class='row'>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_title">Title</label>
<input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_firstname">First name</label>
<input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
</div>
</div>
<div class='col-sm-4'>
<div class='form-group'>
<label for="user_lastname">Last name</label>
<input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
</div>
</div>
</div>
<div class='row'>
<div class='col-sm-12'>
<div class='form-group'>
<label for="user_email">Email</label>
<input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
</div>
</div>
</div>
</fieldset>
Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose
var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );
Here are the steps you need. Step5 is important if you want the data. Step 2 is where you can select individual tables.
EDIT stack's version isn't quite readable... here's a full-size image http://i.imgur.com/y6ZCL.jpg
Nothing of the above worked for me. But those lines solved the same problem on my WordPress site:
RewriteEngine On
RewriteCond %{HTTP:HTTPS} !on
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
This can be done neatly in one line with:
df = df.drop(df.filter(regex='Test').columns, axis=1)
$('#id option').remove();
This will clear the Drop Down list. if you want to clear to select value then $("#id option:selected").remove();
The problem is that Chrome needs to have must-revalidate
in the Cache-Control` header in order to re-check files to see if they need to be re-fetched.
You can always SHIFT-F5 and force Chrome to refresh, but if you want to fix this problem on the server, include this response header:
Cache-Control: must-revalidate
This tells Chrome to check with the server, and see if there is a newer file. IF there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.
If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.
Here is a blog post that discusses the issue further.
To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!
You want strip()
:
myphrases = [" Hello ", " Hello", "Hello ", "Bob has a cat"]
for phrase in myphrases:
print(phrase.strip())
For me my Script tag was outside the body element. Copied it just before closing the body tag. This worked
enter code here
<h1 id = 'title'>Black Jack</h1>
<h4> by Meg</h4>
<p id="text-area">Welcome to blackJack!</p>
<button id="new-button">New Game</button>
<button id="hitbtn">Hit!</button>
<button id="staybtn">Stay</button>
<script src="script.js"></script>
I think the best way is to compare with blank string
BenchmarkStringCheck1 is checking with blank string
BenchmarkStringCheck2 is checking with len zero
I check with the empty and non-empty string checking. You can see that checking with a blank string is faster.
BenchmarkStringCheck1-4 2000000000 0.29 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck1-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.31 ns/op 0 B/op 0 allocs/op
Code
func BenchmarkStringCheck1(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if s == "" {
}
}
}
func BenchmarkStringCheck2(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if len(s) == 0 {
}
}
}
Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:
string s = //{ "user" : { "id" : 12345, "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);
You'll get back something, where you can do:
var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.
Look at result
in the debugger to see, what's in there.
I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.
This did work though:
Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select
That took care of converting the cell's numerical location to what Range expects, which is the A1 format.
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }