Some js files come from the web or library, they are not written by yourself. The code they get variable like this:
var queryString = document.location.search.substring(1);
var params = PDFViewerApplication.parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;
This method makes js files unchanged(keep independence), and pass variable correctly!
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
Here's the filter that I ended up using for strftime in Jinja2 and Flask
@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
date = dateutil.parser.parse(date)
native = date.replace(tzinfo=None)
format='%b %d, %Y'
return native.strftime(format)
And then you use the filter like so:
{{car.date_of_manufacture|strftime}}
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:
{% if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') ) %}
<li>some text</li>
{% endif %}
Edit: Using line_statement_prefix = '#'
* the code would look like this:
# if ( (foo == 'foo' or bar == 'bar') and
(fooo == 'fooo' or baar == 'baar') )
<li>some text</li>
# endif
*Here's an example of how you'd specify the line_statement_prefix
in the Environment
:
from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
loader=PackageLoader('yourapplication', 'templates'),
autoescape=select_autoescape(['html', 'xml']),
line_statement_prefix='#'
)
Or using Flask:
from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
I think you shouldn't prepend themesDir
. You only pass the filename of the template to flask, it will then look in a folder called templates
relative to your python file.
I think jinja deliberately makes it difficult to run 'arbitrary' python within a template. It tries to enforce the opinion that less logic in templates is a good thing.
You can manipulate the global namespace within an Environment
instance to add references to your functions. It must be done before you load any templates. For example:
from jinja2 import Environment, FileSystemLoader
def clever_function(a, b):
return u''.join([b, a])
env = Environment(loader=FileSystemLoader('/path/to/templates'))
env.globals['clever_function'] = clever_function
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
I can suggest you a javascript oriented approach which makes it easy to work with javascript files in your project.
Create a javascript section in your jinja template file and place all variables you want to use in your javascript files in a window object:
Start.html
...
{% block scripts %}
<script type="text/javascript">
window.appConfig = {
debug: {% if env == 'development' %}true{% else %}false{% endif %},
facebook_app_id: {{ facebook_app_id }},
accountkit_api_version: '{{ accountkit_api_version }}',
csrf_token: '{{ csrf_token }}'
}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='app.js') }}"></script>
{% endblock %}
Jinja will replace values and our appConfig object will be reachable from our other script files:
App.js
var AccountKit_OnInteractive = function(){
AccountKit.init({
appId: appConfig.facebook_app_id,
debug: appConfig.debug,
state: appConfig.csrf_token,
version: appConfig.accountkit_api_version
})
}
I have seperated javascript code from html documents with this way which is easier to manage and seo friendly.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
The counter variable inside the loop is called loop.index in jinja2.
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
See http://jinja.pocoo.org/docs/templates/ for more.
you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:
{{ users|join(', ') }}
If there are up to 10 strings then you should use a list in order to iterate through all values.
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for
documentation.
Why the loop?
You could simply do this:
{% if 'priority' in data %}
<p>Priority: {{ data['priority'] }}</p>
{% endif %}
When you were originally doing your string comparison, you should have used ==
instead.
Alternative way (but it's not python style. It's JS style)
{{ files and 'Update' or 'Continue' }}
If you can't just use filter join but need to perform some operations on the array's entry:
{% for entry in array %}
User {{ entry.attribute1 }} has id {{ entry.attribute2 }}
{% if not loop.last %}, {% endif %}
{% endfor %}
{{p.User['first_name'] or 'My default string'}}
When you have a lot of variables that don't need escaping, you can use an autoescape
block:
{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}
Consider using default filter if it is what you need. For example:
{% set host = jabber.host | default(default.host) -%}
or use more fallback values with "hardcoded" one at the end like:
{% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}
Nice shorthand for Multiple variable assignments
{% set label_cls, field_cls = "col-md-7", "col-md-3" %}
As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.
You can defeat this behavior by using an object rather than a scalar for 'count':
{% set count = [1] %}
You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):
{% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}
This is possible with a bit of format conversion.
To extract the private key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
To convert the private key to a public key:
openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
To extract the public key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
You can't run PHP
in an html page ending with .html
. Unless the page is actually PHP and the extension was changed with .htaccess
from .php
to .html
What you mean is:
index.html
<html>
...
<?php echo "Hello world";?> //This is impossible
index.php //The file extension can be changed using htaccess, ex: its type stays php but will be visible to visitors as index.html
<?php echo "Hello world";?>
You can set the calendar to use only AM or PM using
calendar.set(Calendar.AM_PM, int);
0 = AM
1 = PM
Hope this helps
I have resolved this same issue by doing below steps:
File > Close Project
Import Project
Select you project via the system file popup
Check "Import project from external model" radio button and select Maven entry
And some Next buttons (select JDK, ...)
Then the project will be imported as Maven module.
Correct or Incorrect: Please execute test locally and decide for yourself!
Edit/Remove is faster in LinkedList
than ArrayList
.
ArrayList
, backed by Array
, which needs to be double the size, is worse in large volume application.
Below is the unit test result for each operation.Timing is given in Nanoseconds.
Operation ArrayList LinkedList
AddAll (Insert) 101,16719 2623,29291
Add (Insert-Sequentially) 152,46840 966,62216
Add (insert-randomly) 36527 29193
remove (Delete) 20,56,9095 20,45,4904
contains (Search) 186,15,704 189,64,981
Here's the code:
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class ArrayListVsLinkedList {
private static final int MAX = 500000;
String[] strings = maxArray();
////////////// ADD ALL ////////////////////////////////////////
@Test
public void arrayListAddAll() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
arrayList.addAll(stringList);
watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
}
@Test
public void linkedListAddAll() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
watch.start();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
watch.totalTime("Linked List addAll() = "); //2623,29291 Nanoseconds
}
//Note: ArrayList is 26 time faster here than LinkedList for addAll()
///////////////// INSERT /////////////////////////////////////////////
@Test
public void arrayListAdd() {
Watch watch = new Watch();
List<String> arrayList = new ArrayList<String>(MAX);
watch.start();
for (String string : strings)
arrayList.add(string);
watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
}
@Test
public void linkedListAdd() {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
watch.start();
for (String string : strings)
linkedList.add(string);
watch.totalTime("Linked List add() = "); //966,62216 Nanoseconds
}
//Note: ArrayList is 9 times faster than LinkedList for add sequentially
/////////////////// INSERT IN BETWEEN ///////////////////////////////////////
@Test
public void arrayListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
arrayList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
arrayList.add(insertString0);
arrayList.add(insertString1);
arrayList.add(insertString2);
arrayList.add(insertString3);
watch.totalTime("Array List add() = ");//36527
}
@Test
public void linkedListInsertOne() {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(stringList);
String insertString0 = getString(true, MAX / 2 + 10);
String insertString1 = getString(true, MAX / 2 + 20);
String insertString2 = getString(true, MAX / 2 + 30);
String insertString3 = getString(true, MAX / 2 + 40);
watch.start();
linkedList.add(insertString0);
linkedList.add(insertString1);
linkedList.add(insertString2);
linkedList.add(insertString3);
watch.totalTime("Linked List add = ");//29193
}
//Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
////////////////// DELETE //////////////////////////////////////////////////////
@Test
public void arrayListRemove() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.remove(searchString0);
arrayList.remove(searchString1);
watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
}
@Test
public void linkedListRemove() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.remove(searchString0);
linkedList.remove(searchString1);
watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
}
//Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
///////////////////// SEARCH ///////////////////////////////////////////
@Test
public void arrayListSearch() throws Exception {
Watch watch = new Watch();
List<String> stringList = Arrays.asList(strings);
List<String> arrayList = new ArrayList<String>(MAX);
arrayList.addAll(stringList);
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
arrayList.contains(searchString0);
arrayList.contains(searchString1);
watch.totalTime("Array List addAll() time = ");//186,15,704
}
@Test
public void linkedListSearch() throws Exception {
Watch watch = new Watch();
List<String> linkedList = new LinkedList<String>();
linkedList.addAll(Arrays.asList(strings));
String searchString0 = getString(true, MAX / 2 + 10);
String searchString1 = getString(true, MAX / 2 + 20);
watch.start();
linkedList.contains(searchString0);
linkedList.contains(searchString1);
watch.totalTime("Linked List addAll() time = ");//189,64,981
}
//Note: Linked List is 500 Milliseconds faster than ArrayList
class Watch {
private long startTime;
private long endTime;
public void start() {
startTime = System.nanoTime();
}
private void stop() {
endTime = System.nanoTime();
}
public void totalTime(String s) {
stop();
System.out.println(s + (endTime - startTime));
}
}
private String[] maxArray() {
String[] strings = new String[MAX];
Boolean result = Boolean.TRUE;
for (int i = 0; i < MAX; i++) {
strings[i] = getString(result, i);
result = !result;
}
return strings;
}
private String getString(Boolean result, int i) {
return String.valueOf(result) + i + String.valueOf(!result);
}
}
There is also gitclipse(based on JavaGit), but seems dead.
If you have previously installed node using brew, then you will have a bunch of extra files that you should clean up before installing node "the right way". Plus, I had to add a few settings to my startup script to make things work smoothly.
I wrote a script to make this easy.
# filename: install-nvm-npm-node
# author: Lex Sheehan
# purpose: To cleanly install NVM, NODE and NPM
# dependencies: brew
NOW=$(date +%x\ %H:%M:%S)
CR=$'\n'
REV=$(tput rev)
OFF=$(tput sgr0)
BACKUP_DIR=$HOME/backups/nvm-npm-bower-caches/$NOW
MY_NAME=$(basename $0)
NODE_VER_TO_INSTALL=$1
if [ "$NODE_VER_TO_INSTALL" == "" ]; then
NODE_VER_TO_INSTALL=v0.12.2
fi
if [ "`echo "$NODE_VER_TO_INSTALL" | cut -c1-1`" != "v" ]; then
echo """$CR""Usage: $ $MY_NAME <NODE_VERSION_TO_INSALL>"
echo "Example: $ $MY_NAME v0.12.1"
echo "Example: $ $MY_NAME $CR"
exit 1
fi
echo """$CR""First, run: $ brew update"
echo "Likely, you'll need to do what it suggests."
echo "Likely, you'll need to run: $ brew update$CR"
echo "To install latest node version, run the following command to get the latest version: $ nvm ls-remote"
echo "... and pass the version number you want as the only param to $MY_NAME. $CR"
echo "Are you ready to install the latest version of nvm and npm and node version $NODE_VER_TO_INSTALL ?$CR"
echo "Press CTL+C to exit --or-- Enter to continue..."
read x
echo """$REV""Uninstalling nvm...$CR$OFF"
# Making backups, but in all likelyhood you'll just reinstall them (and won't need these backups)
if [ ! -d "$BACKUP_DIR" ]; then
echo "Creating directory to store $HOME/.nvm .npm and .bower cache backups: $BACKUP_DIR"
mkdir -p $BACKUP_DIR
fi
set -x
mv $HOME/.nvm $BACKUP_DIR 2>/dev/null
mv $HOME/.npm $BACKUP_DIR 2>/dev/null
mv $HOME/.bower $BACKUP_DIR 2>/dev/null
{ set +x; } &>/dev/null
echo "$REV""$CR""Uninstalling node...$CR$OFF"
echo "Enter your password to remove user some node-related /usr/local directories"
set -x
sudo rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/lib/node
rm -rf /usr/local/include/node
rm -rf /usr/local/include/node_modules
rm /usr/local/bin/npm
rm /usr/local/lib/dtrace/node.d
rm -rf $HOME/.node
rm -rf $HOME/.node-gyp
rm /opt/local/bin/node
rm /opt/local/include/node
rm -rf /opt/local/lib/node_modules
rm -rf /usr/local/Cellar/nvm
brew uninstall node 2>/dev/null
{ set +x; } &>/dev/null
echo "$REV""$CR""Installing nvm...$CR$OFF"
echo "++brew install nvm"
brew install nvm
echo '$(brew --prefix nvm)/nvm.sh'
source $(brew --prefix nvm)/nvm.sh
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc):$CR$OFF"
echo "export NVM_DIR=\"\$(brew --prefix nvm)\"; [ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"$CR"
NVM_DIR="$(brew --prefix nvm)"
echo """$CR""Using nvm install node...$CR"
echo "++ nvm install $NODE_VER_TO_INSTALL"
nvm install $NODE_VER_TO_INSTALL
NODE_BINARY_PATH="`find /usr/local/Cellar/nvm -name node -type d|head -n 1`/$NODE_VER_TO_INSTALL/bin"
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc) and then restart your shell:$CR$OFF"
echo "export PATH=\$PATH:$NODE_BINARY_PATH:$HOME/.node/bin"
echo """$CR""Upgrading npm...$CR"
echo '++ install -g npm@latest'
npm install -g npm@latest
{ set +x; } &>/dev/null
echo "$REV""$CR""Insert following line in your $HOME/.npmrc file:$OFF"
echo """$CR""prefix=$HOME/.node$CR"
echo "Now, all is likley well if you can run the following without errors: npm install -g grunt-cli$CR"
echo "Other recommended global installs: bower, gulp, yo, node-inspector$CR"
I wrote a short article here that details why this is "the right way".
If you need to install iojs, do so using nvm like this:
nvm install iojs-v1.7.1
To install brew, just see its home page.
See alexpods answer for the rest.
It's as simple as is:
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");
And your some.html needs to contain something like:
<link rel="stylesheet" type="text/css" href="style.css" />
Add this code below. Once turns it off, releases the filter. Second time turns it back on without filters.
Not very elegant, but served my purpose.
ActiveSheet.ListObjects("MyTable").Range.AutoFilter
'then call it again?
ActiveSheet.ListObjects("MyTable").Range.AutoFilter
An image of how to in Android Studio 1.5.1.
Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Use java.net.URL#openStream()
with a proper URL (including the protocol!). E.g.
InputStream input = new URL("http://www.somewebsite.com/a.txt").openStream();
// ...
Similar to @Sumit Jain's solution
Date currentDate = new Date(System.currentTimeMillis() - 3600 * 1000);
or
Date currentDate = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));
Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.
Here's how you could do it if you could force people to bend to your will:
User enters: postal (zip) code
You fill: state, city (province, for Canada)
User starts to enter: streetname
You: autofill
You display: a range of allowed address numbers
User: enters the number
Done.
Here's how it is natural for people to do it:
User enters: address number
You: do nothing
User starts to enter: street name
You: autofill, drawing from a massive list of every street in the country
User enters: city
You: autofill
User enters: state/provence
You: is it worth autofilling a few chars?
You: autofill postal (zip) code, if you can (because some codes straddle cities).
Now you know why people charge $$$ to do this. :)
For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa
Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53
Just define width of the table and width for each table cell
something like
table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}
It works like a charm :o)
There is lack of support for colors starting from 00 ie "#000623" but here is the fix
function lightenDarkenColor(colorCode, amount) {
let usePound = false;
if (colorCode[0] == "#") {
colorCode = colorCode.slice(1);
usePound = true;
}
const num = parseInt(colorCode, 16);
let r = (num >> 16) + amount;
if (r > 255) {
r = 255;
} else if (r < 0) {
r = 0;
}
let b = ((num >> 8) & 0x00FF) + amount;
if (b > 255) {
b = 255;
} else if (b < 0) {
b = 0;
}
let g = (num & 0x0000FF) + amount;
if (g > 255) {
g = 255;
} else if (g < 0) {
g = 0;
}
let color = (g | (b << 8) | (r << 16)).toString(16);
while (color.length < 6){
color = 0 + color;
}
return (usePound ? '#' : '') + color;
}
Active 1st tab
$("#workflowTab").tabs({ active: 0 });
Active last tab
$("#workflowTab").tabs({ active: -1 });
Active 2nd tab
$("#workflowTab").tabs({ active: 1 });
Its work like an array
For How do I change the overall colors (background and font)?
For MAC : goto Sublime text -> Preferences -> color scheme
Here is a short and fast in-memory solution that I came up with utilizing the Table Valued Constructors introduced in SQL Server 2008:
It will return 1,000,000 rows, however you can either add/remove CROSS JOINs, or use TOP clause to modify this.
;WITH v AS (SELECT * FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) v(z))
SELECT N FROM (SELECT ROW_NUMBER() OVER (ORDER BY v1.z)-1 N FROM v v1
CROSS JOIN v v2 CROSS JOIN v v3 CROSS JOIN v v4 CROSS JOIN v v5 CROSS JOIN v v6) Nums
Note that this could be quickly calculated on the fly, or (even better) stored in a permanent table (just add an INTO
clause after the SELECT N
segment) with a primary key on the N
field for improved efficiency.
#include<stdio.h>
int main(void)
{
int mat[10][10],i,j;
printf("Enter your matrix\n");
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
scanf("%d",&mat[i][j]);
}
printf("\nHere is your matrix:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",mat[i][j]);
}
printf("\n");
}
}
We have used YUI, Chosen, and are currently using the jQuery Select2 plugin: https://select2.github.io/
It's pretty robust, the arrow is just the tip of the iceberg.
As soon as stylized selects becomes a requirement, I agree with the others, go with a plugin. Don't kill yourself reinventing the wheel.
First must be Alphabet and then dot not allowed in target string. below is code.
string input = "A_aaA";
// B
// The regular expression we use to match
Regex r1 = new Regex("^[A-Za-z][^.]*$"); //[\t\0x0020] tab and spaces.
// C
// Match the input and write results
Match match = r1.Match(input);
if (match.Success)
{
Console.WriteLine("Valid: {0}", match.Value);
}
else
{
Console.WriteLine("Not Match");
}
Console.ReadLine();
If you have a Style component that you can require from your Component, then you could have something like this at the top of the file:
const Dimensions = require('Dimensions');
const window = Dimensions.get('window');
And then you could provide fulscreen: {width: window.width, height: window.height},
in your Style component. Hope this helps
if ($("#cartContent").children().length == 0)
{
// no child
}
The PDO solution, just for a better implementation then mysql_*
:
$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url
FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
Nice feature is also that it will leave integers as integers as opposed to strings.
When you use addEventListener
, this
will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this
from within your function:
productLineSelect.addEventListener('change',getSelection,false);
function getSelection(){
var value = sel.options[this.selectedIndex].value;
alert(value);
}
If you want to pass in some other argument from the context where you call addEventListener
, you can use a closure, like this:
productLineSelect.addEventListener('change', function(){
// pass in `this` (the element), and someOtherVar
getSelection(this, someOtherVar);
},false);
function getSelection(sel, someOtherVar){
var value = sel.options[sel.selectedIndex].value;
alert(value);
alert(someOtherVar);
}
Sometimes they may give you the same results but they are meant to be used in different sense/case. The main difference is in syntax.
Minutely notice the example below. DISTINCT
is used to filter out the duplicate set of values. (6, cs, 9.1) and (1, cs, 5.5) are two different sets. So DISTINCT
is going to display both the rows while GROUP BY Branch
is going to display only one set.
SELECT * FROM student;
+------+--------+------+
| Id | Branch | CGPA |
+------+--------+------+
| 3 | civil | 7.2 |
| 2 | mech | 6.3 |
| 6 | cs | 9.1 |
| 4 | eee | 8.2 |
| 1 | cs | 5.5 |
+------+--------+------+
5 rows in set (0.001 sec)
SELECT DISTINCT * FROM student;
+------+--------+------+
| Id | Branch | CGPA |
+------+--------+------+
| 3 | civil | 7.2 |
| 2 | mech | 6.3 |
| 6 | cs | 9.1 |
| 4 | eee | 8.2 |
| 1 | cs | 5.5 |
+------+--------+------+
5 rows in set (0.001 sec)
SELECT * FROM student GROUP BY Branch;
+------+--------+------+
| Id | Branch | CGPA |
+------+--------+------+
| 3 | civil | 7.2 |
| 6 | cs | 9.1 |
| 4 | eee | 8.2 |
| 2 | mech | 6.3 |
+------+--------+------+
4 rows in set (0.001 sec)
Sometimes the results that can be achieved by GROUP BY
clause is not possible to achieved by DISTINCT
without using some extra clause or conditions. E.g in above case.
To get the same result as DISTINCT
you have to pass all the column names in GROUP BY
clause like below. So see the syntactical difference. You must have knowledge about all the column names to use GROUP BY
clause in that case.
SELECT * FROM student GROUP BY Id, Branch, CGPA;
+------+--------+------+
| Id | Branch | CGPA |
+------+--------+------+
| 1 | cs | 5.5 |
| 2 | mech | 6.3 |
| 3 | civil | 7.2 |
| 4 | eee | 8.2 |
| 6 | cs | 9.1 |
+------+--------+------+
Also I have noticed GROUP BY
displays the results in ascending order by default which DISTINCT
does not. But I am not sure about this. It may be differ vendor wise.
Source : https://dbjpanda.me/dbms/languages/sql/sql-syntax-with-examples#group-by
Since a stored procedure is created, altered and dropped using queries you actually CAN manage them using phpMyAdmin.
To create a stored procedure, you can use the following (change as necessary) :
CREATE PROCEDURE sp_test()
BEGIN
SELECT 'Number of records: ', count(*) from test;
END//
And make sure you set the "Delimiter" field on the SQL tab to //.
Once you created the stored procedure it will appear in the Routines fieldset below your tables (in the Structure tab), and you can easily change/drop it.
To use the stored procedure from PHP you have to execute a CALL query, just like you would do in plain SQL.
Sticking to the method you are using to insert it, use
list[:0] = ['foo']
http://docs.python.org/release/2.6.6/library/stdtypes.html#mutable-sequence-types
You can also use the tab character '\t'
to represent a tab, instead of "\t"
.
char c ='t';
char c =(char)9;
You can also use sets:
a = numpy.array([10, 20, 30, 40, 50, 60, 70, 80, 90])
the_index_list = [2, 3, 6]
the_big_set = set(numpy.arange(len(a)))
the_small_set = set(the_index_list)
the_delta_row_list = list(the_big_set - the_small_set)
a = a[the_delta_row_list]
I think this is better, following the good practices of passing parameters to the query:
BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();
You can see it in the documentation, Laravel 5.5.
You can also use the Laravel scout and make it easier with search. Here is the documentation.
If your script is a directory or ZIP file rather than a single python file, __main__.py
will be executed when the "script" is passed as an argument to the python interpreter.
For those stuck with legacy issues, find the line throwing the error and add {passive: true}
- eg:
this.element.addEventListener(t, e, !1)
becomes
this.element.addEventListener(t, e, { passive: true} )
You can also get the text resize events, and the zoom factor by injecting a div containing at least a non-breakable space (possibly, hidden), and regularly checking its height. If the height changes, the text size has changed, (and you know how much - this also fires, incidentally, if the window gets zoomed in full-page mode, and you still will get the correct zoom factor, with the same height / height ratio).
I think a more canonical way to do this is via:
command --feature
and
command --no-feature
argparse
supports this version nicely:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
Of course, if you really want the --arg <True|False>
version, you could pass ast.literal_eval
as the "type", or a user defined function ...
def t_or_f(arg):
ua = str(arg).upper()
if 'TRUE'.startswith(ua):
return True
elif 'FALSE'.startswith(ua):
return False
else:
pass #error condition maybe?
Install PAR::Packer from CPAN (it is free) and use pp utility.
You'll need to get those bytes
into a MemoryStream
:
Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
bmp = new Bitmap(ms);
}
That uses the Bitmap(Stream stream)
constructor overload.
UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException
will be thrown on these conditions:
stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.
Following is a work-around:
Running the shortcut will execute your batch script as administrator.
More a comment than an answer - but I cannot add comments yet: Thanks for your help, the count was the easy part. Just for others that might come here. I hope that it will save you some time.
It took me a while to get the attributes from the rows and to understand how to access them from the data() Object (that the data() is an Array and the Attributes can be read by adding them with a dot and not with brackets:
$('#button').click( function () {
for (var i = 0; i < table.rows('.selected').data().length; i++) {
console.log( table.rows('.selected').data()[i].attributeNameFromYourself);
}
} );
(by the way: I get the data for my table using AJAX and JSON)
if you want both width and the height you can try
background-size: cover !important;
but this wont distort the image but fill the div.
The following also requires the moment-duration-format plugin:
$.fn.countdown = function ( options ) {
var $target = $(this);
var defaults = {
seconds: 0,
format: 'hh:mm:ss',
stopAtZero: true
};
var settings = $.extend(defaults, options);
var eventTime = Date.now() + ( settings.seconds * 1000 );
var diffTime = eventTime - Date.now();
var duration = moment.duration( diffTime, 'milliseconds' );
var interval = 0;
$target.text( duration.format( settings.format, { trim: false }) );
var counter = setInterval(function () {
$target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
}, 1000);
};
Usage example:
$('#someDiv').countdown({
seconds: 30*60,
format: 'mm:ss'
});
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
According to Scala's documentation:
Case classes are just regular classes that are:
- Immutable by default
- Decomposable through pattern matching
- Compared by structural equality instead of by reference
- Succinct to instantiate and operate on
Another feature of the case keyword is the compiler automatically generates several methods for us, including the familiar toString, equals, and hashCode methods in Java.
Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo"
you can see it (you class only single class).
Use This And Call This In OnCreate Method In Which Activity You Want
public void popupMessage(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
alertDialogBuilder.setTitle("Connection Failed");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("internet","Ok btn pressed");
finishAffinity();
System.exit(0);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))
first you need to import Sum then ..
That's it!! Long waiting for this fix.
I've an old Android issue about double-start an activity that required (programmatically) landscape mode: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
Now Android make Landscape mode on start.
Datetimes are comparable; so you can use max(datetimes_list)
and min(datetimes_list)
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.
Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping
RewriteEngine On
RewriteRule ^(wordpress)($|/) - [L]
int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();
If it is a Maven project then sometimes re-importing of it helps:
Hope it will resolve the issue.
Two corrections:
You have to make an ArrayList
of People
objects:
ArrayList<People> preps = new ArrayList<People>();
After adding the objects to the preps, use:
Collections.sort(preps, new CompareId());
Also, add a CompareId
class as:
class CompareId implements Comparator {
public int compare(Object obj1, Object obj2) {
People t1 = (People)obj1;
People t2 = (People)obj2;
if (t1.marks > t2.marks)
return 1;
else
return -1;
}
}
in your Xcode:
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
sudo apt update && sudo apt upgrade
sudo apt-get install xorg lxde vnc4server lubuntu-desktop
sudo nano /etc/lightdm/lightdm.conf
[SeatDefaults]
allow-guest=false
user-session=LXDE
#user-session=Lubuntu
vncserver
sudo echo "lxpanel & /usr/bin/lxsession -s LXDE &" >> ~/.vnc/xstartup
sudo reboot
ssh -L 5901:localhost:5901 -i "xxx.pem" [email protected]
vncserver -geometry 1280x800
This works well with (my) German locale, should be possible to adjust it to your needs...
forfiles /p *PATH* /m *filepattern* /c "cmd /c ren @file
%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_@file"
As per your requirement you dont have to generate a html page dynamicaly. It can be done by .htaccess file .
Still this is sample code to generate HTML Page
<?php
$filename = 'test.html';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
?>
you can create any .html , .php file just change extention in file name
function call asStartOfDay()
on java.time.LocalDate
object returns a java.time.LocalDateTime
object
You could use this command:
ffmpeg -i input.wav -vn -ar 44100 -ac 2 -b:a 192k output.mp3
Explanation of the used arguments in this example:
-i
- input file
-vn
- Disable video, to make sure no video (including album cover image) is included if the source would be a video file
-ar
- Set the audio sampling frequency. For output streams it is set by default to the frequency of the corresponding input stream. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options.
-ac
- Set the number of audio channels. For output streams it is set by default to the number of input audio channels. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options. So used here to make sure it is stereo (2 channels)
-b:a
- Converts the audio bitrate to be exact 192kbit per second
Here I updated the sample code in Kotlin. Please note on Nougat and above version Uri.fromFile(file)
is not working and it crashes the app for that need to implement FileProvider which is safest way to send files from intent. For implementing this refer this answer or this article
private fun takePhotoFromCamera() {
val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
if (isDeviceSupportCamera) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
System.currentTimeMillis().toString() + ".jpg")
// fileUri = Uri.fromFile(file)
fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
}
} else {
Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
realPath = file?.path
//do what ever you want to do
}
}
}
The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:
tcp:name.cloudapp.net,1433
This is normal behaviour (among browser implementations at least). Margin does not affect the child's position in relation to its parent, unless the parent has padding, in which case most browsers will then add the child's margin to the parent's padding.
To get the behaviour you want, you need:
.child {
margin-top: 0;
}
.parent {
padding-top: 10px;
}
To deal with any type of files for my own APP, I use this configuration for CFBundleDocumentTypes:
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>IPA</string>
<key>LSItemContentTypes</key>
<array>
<string>public.item</string>
<string>public.content</string>
<string>public.data</string>
<string>public.database</string>
<string>public.composite-content</string>
<string>public.contact</string>
<string>public.archive</string>
<string>public.url-name</string>
<string>public.text</string>
<string>public.plain-text</string>
<string>public.source-code</string>
<string>public.executable</string>
<string>public.script</string>
<string>public.shell-script</string>
<string>public.xml</string>
<string>public.symlink</string>
<string>org.gnu.gnu-zip-archve</string>
<string>org.gnu.gnu-tar-archive</string>
<string>public.image</string>
<string>public.movie</string>
<string>public.audiovisual-?content</string>
<string>public.audio</string>
<string>public.directory</string>
<string>public.folder</string>
<string>com.apple.bundle</string>
<string>com.apple.package</string>
<string>com.apple.plugin</string>
<string>com.apple.application-?bundle</string>
<string>com.pkware.zip-archive</string>
<string>public.filename-extension</string>
<string>public.mime-type</string>
<string>com.apple.ostype</string>
<string>com.apple.nspboard-typ</string>
<string>com.adobe.pdf</string>
<string>com.adobe.postscript</string>
<string>com.adobe.encapsulated-?postscript</string>
<string>com.adobe.photoshop-?image</string>
<string>com.adobe.illustrator.ai-?image</string>
<string>com.compuserve.gif</string>
<string>com.microsoft.word.doc</string>
<string>com.microsoft.excel.xls</string>
<string>com.microsoft.powerpoint.?ppt</string>
<string>com.microsoft.waveform-?audio</string>
<string>com.microsoft.advanced-?systems-format</string>
<string>com.microsoft.advanced-?stream-redirector</string>
<string>com.microsoft.windows-?media-wmv</string>
<string>com.microsoft.windows-?media-wmp</string>
<string>com.microsoft.windows-?media-wma</string>
<string>com.apple.keynote.key</string>
<string>com.apple.keynote.kth</string>
<string>com.truevision.tga-image</string>
</array>
<key>CFBundleTypeIconFiles</key>
<array>
<string>Icon-76@2x</string>
</array>
</dict>
</array>
Try this:
pointer-events:none
Adding above on the specified HTML element will prevents all click, state and cursor options.
<div class="ads">
<button id='noclick' onclick='clicked()'>Try</button>
</div>
Use
datatable.select("col1='test'","col1 ASC")
Then before binding your data to the grid or repeater etc, use this
datatable.defaultview.sort()
That will solve your problem.
Check Python version: python -V
or python --version
or apt-cache policy python
you can also run whereis python
to see how many versions are installed.
`
int array[]=new int[3]; array.length;
so here we have created an array with a memory space of 3... this is how it looks actually
0th 1st 2nd ...........> Index 2 4 5 ...........> Number
So as u see the size of this array is 3 but the index of array is only up to 2 since any array starts with 0th index.
second statement' output shall be 3 since the length of the array is 3... Please don't get confused between the index value and the length of the array....
cheers!
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
It will overflow and wrap around to Long.MIN_VALUE
.
Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.
NO, you can't do it other way than so.
If someone comes looking for configuring log4j2 programmatically in Java, then this link could help: (https://www.studytonight.com/post/log4j2-programmatic-configuration-in-java-class)
Here is the basic code for configuring a Console Appender:
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.DEBUG);
// naming the logger configuration
builder.setConfigurationName("DefaultLogger");
// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("Console", "CONSOLE")
.addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
// add a layout like pattern, json etc
appenderBuilder.add(builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d %p %c [%t] %m%n"));
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
rootLogger.add(builder.newAppenderRef("Console"));
builder.add(appenderBuilder);
builder.add(rootLogger);
Configurator.reconfigure(builder.build());
This will reconfigure the default rootLogger and will also create a new appender.
To stop your program, just press Control + C.
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Here's a general solution:
def get_text_excluding_children(driver, element):
return driver.execute_script("""
return jQuery(arguments[0]).contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
""", element)
The element passed to the function can be something obtained from the find_element...()
methods (i.e. it can be a WebElement
object).
Or if you don't have jQuery or don't want to use it you can replace the body of the function above above with this:
return self.driver.execute_script("""
var parent = arguments[0];
var child = parent.firstChild;
var ret = "";
while(child) {
if (child.nodeType === Node.TEXT_NODE)
ret += child.textContent;
child = child.nextSibling;
}
return ret;
""", element)
I'm actually using this code in a test suite.
You can use the --prefer-source
flag for composer to checkout external packages with the VCS information (if any available). You can simply revert to the original state. Also if you issue the composer update
command composer will detect any changes you made locally and ask if you want to discard them.
Your .gitignore file is related to your root project (ZF2 skeleton) and it prevents the vendor dir (where your third party libs are) from committing to your own VCS. The ignore file is unrelated to the git repo's of your vendors.
Use Collections.list(iterator).stream()...
4 years later, ES6 way simpler version.
function getCookie(name) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [k,v] = el.split('=');
cookie[k.trim()] = v;
})
return cookie[name];
}
I have also created a gist to use it as a Cookie
object. e.g., Cookie.set(name,value)
and Cookie.get(name)
This read all cookies instead of scanning through. It's ok for small number of cookies.
A typedef allows the programmer to define one Objective-C type as another. For example,
typedef int Counter; defines the type Counter to be equivalent to the int type. This drastically improves code readability.
GitHub has a nice section called "Dealing with “non-fast-forward” errors"
This error can be a bit overwhelming at first, do not fear.
Simply put, git cannot make the change on the remote without losing commits, so it refuses the push.
Usually this is caused by another user pushing to the same branch. You can remedy this by fetching and merging the remote branch, or using pull to perform both at once.In other cases this error is a result of destructive changes made locally by using commands like
git commit --amend
orgit rebase
.
While you can override the remote by adding--force
to thepush
command, you should only do so if you are absolutely certain this is what you want to do.
Force-pushes can cause issues for other users that have fetched the remote branch, and is considered bad practice. When in doubt, don’t force-push.
Git cannot make changes on the remote like a fast-forward merge, which a Visual Git Reference illustrates like:
This is not exactly your case, but helps to see what "fast-forward" is (where the HEAD
of a branch is simply moved to a new more recent commit).
The "branch master->master (non-fast-forward) Already-up-to-date
" is usually for local branches which don't track their remote counter-part.
See for instance this SO question "git pull says up-to-date but git push rejects non-fast forward".
Or the two branches are connected, but in disagreement with their respective history:
See "Never-ending GIT story - what am I doing wrong here?"
This means that your subversion branch and your remote git master branch do not agree on something.
Some change was pushed/committed to one that is not in the other.
Fire upgitk --all
, and it should give you a clue as to what went wrong - look for "forks" in the history.
You can view this dump from the UNIX console.
The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.
E.g.:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"
You can view the dump from the console on the mentioned path.
This is how I got it working on httpClient 4.5 (as per Olive Tree request):
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(this.user, this.password));
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1"},
null,
new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setSSLSocketFactory(sslsf)
.build();
return httpclient;
Don't use the ['type']
parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name']
parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe
and calling it cutekittens.jpg
.
The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['file']['error']);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
case 'image/jpeg':
case 'application/pdf'
case etc....
$ok = true;
default:
die("Unknown/not permitted file type");
}
move_uploaded_file(...);
You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.
In python 3.x. you use
print("Hello, World")
In Python 2.x. you use
print "Hello, World!"
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
Collections.addAll provides the shortest (one-line) receipt
Having
String[] array = {"foo", "bar", "baz"};
Set<String> set = new HashSet<>();
You can do as below
Collections.addAll(set, array);
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
do you have sklearn? if not, do the following:
sudo pip install sklearn
After installing sklearn
from sklearn.model_selection import train_test_split
works fine
I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.
https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable
I just needed to do this, but thought Steven's solution would be slow. This should hopefully use graphics HW. Create a category on UIImage:
- (UIImage *)imageByApplyingAlpha:(CGFloat) alpha {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextSetAlpha(ctx, alpha);
CGContextDrawImage(ctx, area, self.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
CMake 3.13 on Ubuntu 16.04
This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:
$ cat CMakeLists.txt
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE )
message("MY_VARIABLE evaluates to True")
endif()
$ mkdir build && cd build
$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build
Another way is to select a column with the columns
array:
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
If all you want to do is get rid of invalid hostname errors you can just do:
HttpClient httpClient = new DefaultHttpClient();
SSLSocketFactory sf = (SSLSocketFactory)httpClient.getConnectionManager()
.getSchemeRegistry().getScheme("https").getSocketFactory();
sf.setHostnameVerifier(new AllowAllHostnameVerifier());
It is a unary "+" operator which yields a numeric expression. It would be the same as d*1
, I believe.
describe [db_name.]table_name;
for formatted output, or
show create table [db_name.]table_name;
for the SQL statement that can be used to create a table.
Just use the following code in your javaScript:
if(new Date(hireDate).getTime() > new Date().getTime())
{
//Date greater than today's date
}
Change the condition according to your requirement.Here is one link for comparision compare in java script
you can also try the more generic version which gives you the ith element
enumerable.ElementAtOrDefault(i));
hope it helps
I'll throw another method on the pile...
scipy.interpolate
's many interpolating splines are capable of providing derivatives. So, using a linear spline (k=1
), the derivative of the spline (using the derivative()
method) should be equivalent to a forward difference. I'm not entirely sure, but I believe using a cubic spline derivative would be similar to a centered difference derivative since it uses values from before and after to construct the cubic spline.
from scipy.interpolate import InterpolatedUnivariateSpline
# Get a function that evaluates the linear spline at any x
f = InterpolatedUnivariateSpline(x, y, k=1)
# Get a function that evaluates the derivative of the linear spline at any x
dfdx = f.derivative()
# Evaluate the derivative dydx at each x location...
dydx = dfdx(x)
Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:
public static String makeUrl(HttpServletRequest request)
{
return request.getRequestURL().toString() + "?" + request.getQueryString();
}
I don't know about a way to do this with any Spring MVC facilities.
If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
And then use this to get the request bound to the current Thread:
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Here is the modified script which i took from http://www.foliotek.com/devblog/sql-server-optimization-with-index-rebuilding which i found useful to post here. Although it uses a cursor and i know what is the main problem with cursors it can be easily converted to a cursor-less version.
It is well-documented and you can easily read through it and modify to your needs.
IF OBJECT_ID('tempdb..#work_to_do') IS NOT NULL
DROP TABLE tempdb..#work_to_do
BEGIN TRY
--BEGIN TRAN
use yourdbname
-- Ensure a USE statement has been executed first.
SET NOCOUNT ON;
DECLARE @objectid INT;
DECLARE @indexid INT;
DECLARE @partitioncount BIGINT;
DECLARE @schemaname NVARCHAR(130);
DECLARE @objectname NVARCHAR(130);
DECLARE @indexname NVARCHAR(130);
DECLARE @partitionnum BIGINT;
DECLARE @partitions BIGINT;
DECLARE @frag FLOAT;
DECLARE @pagecount INT;
DECLARE @command NVARCHAR(4000);
DECLARE @page_count_minimum SMALLINT
SET @page_count_minimum = 50
DECLARE @fragmentation_minimum FLOAT
SET @fragmentation_minimum = 30.0
-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function
-- and convert object and index IDs to names.
SELECT object_id AS objectid ,
index_id AS indexid ,
partition_number AS partitionnum ,
avg_fragmentation_in_percent AS frag ,
page_count AS page_count
INTO #work_to_do
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL,
'LIMITED')
WHERE avg_fragmentation_in_percent > @fragmentation_minimum
AND index_id > 0
AND page_count > @page_count_minimum;
IF CURSOR_STATUS('global', 'partitions') >= -1
BEGIN
PRINT 'partitions CURSOR DELETED' ;
CLOSE partitions
DEALLOCATE partitions
END
-- Declare the cursor for the list of partitions to be processed.
DECLARE partitions CURSOR LOCAL
FOR
SELECT *
FROM #work_to_do;
-- Open the cursor.
OPEN partitions;
-- Loop through the partitions.
WHILE ( 1 = 1 )
BEGIN;
FETCH NEXT
FROM partitions
INTO @objectid, @indexid, @partitionnum, @frag, @pagecount;
IF @@FETCH_STATUS < 0
BREAK;
SELECT @objectname = QUOTENAME(o.name) ,
@schemaname = QUOTENAME(s.name)
FROM sys.objects AS o
JOIN sys.schemas AS s ON s.schema_id = o.schema_id
WHERE o.object_id = @objectid;
SELECT @indexname = QUOTENAME(name)
FROM sys.indexes
WHERE object_id = @objectid
AND index_id = @indexid;
SELECT @partitioncount = COUNT(*)
FROM sys.partitions
WHERE object_id = @objectid
AND index_id = @indexid;
SET @command = N'ALTER INDEX ' + @indexname + N' ON '
+ @schemaname + N'.' + @objectname + N' REBUILD';
IF @partitioncount > 1
SET @command = @command + N' PARTITION='
+ CAST(@partitionnum AS NVARCHAR(10));
EXEC (@command);
--print (@command); //uncomment for testing
PRINT N'Rebuilding index ' + @indexname + ' on table '
+ @objectname;
PRINT N' Fragmentation: ' + CAST(@frag AS VARCHAR(15));
PRINT N' Page Count: ' + CAST(@pagecount AS VARCHAR(15));
PRINT N' ';
END;
-- Close and deallocate the cursor.
CLOSE partitions;
DEALLOCATE partitions;
-- Drop the temporary table.
DROP TABLE #work_to_do;
--COMMIT TRAN
END TRY
BEGIN CATCH
--ROLLBACK TRAN
PRINT 'ERROR ENCOUNTERED:' + ERROR_MESSAGE()
END CATCH
You can use Hudson Groovy builder to do this.
First Job in pipeline
Second job in pipeline
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
data 52e - Returns when username is valid but password/credential is invalid.
You probably need something like
String dn = "cn=" + userName + "," + "CN=Users," + base;
Do you have adequate permissions to your repo'?
My solution was unrelated to git
, however I was seeing the same error messages, and dirty status of submodules.
The root-cause was some files in the .git
folder were owned by root
, so git
did not have write access, therefore git
could not change the dirty state of submodules when run as my user.
Do you have the same problem?
From your repository's root folder, use find
to list files owned by root [optional]
find .git -user root
Sollution [Linux]
Change all files in the .git
folder to have you as the owner
sudo chown -R $USER:$USER .git
# alternatively, only the files listed in the above command...
sudo find .git -user root -exec chown $USER:$USER {} +
How did this happen?
In my case I built libraries in sub-modules from a docker container, the docker daemon traditionally runs as root
, so files created fall into root:root
ownership.
My user has root privileges by proxy through that service, so even though I didn't sudo
anything, my git repository still had changes owned by root
.
I hope this helps someone, git outa here.
If you are using the local server, run Django shell using python manage.py shell
. It will take you to the Django python environment and you are good to go.
From wiki page
12 (form feed, \f, ^L), to cause a printer to eject paper to the top of the next page, or a video terminal to clear the screen.
or more details here.
It seems that this symbol is rather obsolete now and the way it is processed may be(?) implementation dependent. At least for me your code gives the following output (xcode gcc 4.2, gdb console):
hello
goodbye
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
An update
Turns out now brew cask install sublime-text
installs the most up to date version (e.g. 3) by default and brew cask
is now part of the standard brew
-installation.
An object file is just what you get when you compile one (or several) source file(s).
It can be either a fully completed executable or library, or intermediate files.
The object files typically contain native code, linker information, debugging symbols and so forth.
In this way you don't need to worry about if the first array is smaller than the second one.
var arr1 = [1, 2, 3, 4, 5, 6,10],
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function array_diff(array1, array2){
var difference = $.grep(array1, function(el) { return $.inArray(el,array2) < 0});
return difference.concat($.grep(array2, function(el) { return $.inArray(el,array1) < 0}));;
}
console.log(array_diff(arr1, arr2));
In your component
let today: string;
ngOnInit() {
this.today = new Date().toISOString().split('T')[0];
}
and in your html file
<input name="date" [(ngModel)]="today" type="date" required>
Ok, thanks for the more specific info, ppl may remove their downvotes now...
What you are proposing is a very common thing to do! You want to run your web application locally without uploading it to your host yet. That's totally fine and that's what your Apache is there for. Your Apache is a web server meaning its main purpose is to serve HTML, PHP, ASP, etc. files. Some like PHP; it first sends to the interpreter and then sends the rendered file to the browser. All in all: it's just serving pages to your browser (the client).
Your web server has a root directory which is wwwroot (IIS) or htdocs (apache, xampp) or something else like public_html, www or html, etc. It depends on your OS and web server.
Now if you type http://localhost
into your browser, your browser will be directed to this webroot and the server will serve any index.html
, index.php
, etc. it can find there (in a customizable order).
If you have a project called "mytutorial" you can enter http://localhost/mytutorial
and the server will show you the index-file of your tutorial, etc. If you look at the absolute path of this tutorial folder then it's just a subfolder of your webroot, which is itself located somewhere on your harddrive, but that doesn't matter for your localhost.
So the relative path is
http://localhost/mytutorial
while the absolute path may be
c:/webservices/apache/www
or
c:/xampp/htdocs
If you're working with Dreamweaver you can simplify the testing process by setting up your local server as a testing server in your project settings. Try it! It's easy. Once it's done, you can just press the browser icon with any of your files and it will open on localhost.
string newString = url.Substring(18, (url.LastIndexOf(".") - 18))
I got this working with the method .dialog("widget")
which returns the dialog DIV itself. If you're in the dialog methods:
$(this)
.dialog("widget")
.find("button")
.addClass("ui-state-disabled") // for the style
.attr("disabled", true);
A picture's worth a thousand words:
>>> class c:
pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
This works for me:
pandas.factorize( ['B', 'C', 'D', 'B'] )[0]
Output:
[0, 1, 2, 0]
The new git-switch
command (starting in GIT 2.23) also has a flag --discard-changes
which should help you. git pull
might be necessary afterwards.
Warning: it's still considered to be experimental.
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Although this may not solve your problem, it did for me when I wanted to do a similar thing. Instead of setting the header I used the footer of the section above. What saved me was that this section was small and static in nature, so it never scrolled below the bottom of the view.
import os
print os.getcwd() # Prints the current working directory
To set the working directory:
os.chdir('c:\\Users\\uname\\desktop\\python') # Provide the new path here
The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,
def lower_wick_vec(o, l, c):
min_oc = numpy.where(o > c, c, o)
return min_oc - l
where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:
def lower_wick_df(df):
min_oc = df[['Open', 'Close']].min(axis=1)
return min_oc - l
The other three will work on columns or vectors just as they are. Then you can finish off with
def is_hammer(df):
lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"])
cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
return cl & lw
Bit operators can perform set logic on boolean vectors, &
for and
, |
for or
etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.
For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.
The safest bet is to create a class on those tables and use that. Currently getting something like this to work in all major browsers is unlikely.
On a Scientific Linux 6.7 system, the man page on rsync says:
--ignore-times don't skip files that match size and time
I have two files with identical contents, but with different creation dates:
[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron
[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd /tmp/new/usercron
With --size-only
, the two files are regarded the same:
[root@windstorm ~]# rsync -v --size-only -n /tmp/new/usercron /tmp/master/usercron
sent 29 bytes received 12 bytes 82.00 bytes/sec
total size is 1595 speedup is 38.90 (DRY RUN)
With --ignore-times
, the two files are regarded different:
[root@windstorm ~]# rsync -v --ignore-times -n /tmp/new/usercron /tmp/master/usercron
usercron
sent 32 bytes received 15 bytes 94.00 bytes/sec
total size is 1595 speedup is 33.94 (DRY RUN)
So it does not looks like --ignore-times
has any effect at all.
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
You need to tell it which index in data
to use, or double loop through all.
E.g., to get the values in the 4th index in the outside array.:
foreach($user->data[3]->values as $values)
{
echo $values->value . "\n";
}
To go through all:
foreach($user->data as $mydata)
{
foreach($mydata->values as $values) {
echo $values->value . "\n";
}
}
Like this:
for pet in pets :
print(pet)
In fact, Python only has foreach style for
loops.
I solved the same issue with the following steps
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net46" />
from package.config file.Edit the .csproj project file and removed the below settings.
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
Update-Package –reinstall
Point # 2 and 3 were given by other users and I appreciate those users. Point # 1, removing the Microsoft.CodeDom.Providers.DotNetCompilerPlatform
from package.config file is more important. Also, after running the command mentioned in point #3, the issue resolved. All unwanted packages removed and required package reference updated.
Hope this helps someone.
It is very simple way to make individual file non-arc.
Follow below steps :
Disable ARC on individual file:
Select desired files at Target/Build Phases/Compile Sources in Xcode
Select .m file which you want make it NON-ARC PRESS ENTER Type -fno-objc-arc
Non ARC file to ARC project flag : -fno-objc-arc
ARC file to non ARC project flag : -fobjc-arc
Problem comes from the fact that line breaks (\n\r
?) are not the same as HTML <br/>
tags
var text = document.forms[0].txt.value;
text = text.replace(/\r?\n/g, '<br />');
UPDATE
Since many of the comments and my own experience have show me that this <br>
solution is not working as expected here is an example of how to append a new line to a textarea
using '\r\n'
function log(text) {
var txtArea ;
txtArea = document.getElementById("txtDebug") ;
txtArea.value += text + '\r\n';
}
I decided to do this an edit, and not as a new question because this a far too popular answer to be wrong or incomplete.
This solution worked best for me. It uses jQuery and the iframe's ".load" event.
It would be worth noting that segmentation fault isn't caused by directly accessing another process memory (this is what I'm hearing sometimes), as it is simply not possible. With virtual memory every process has its own virtual address space and there is no way to access another one using any value of pointer. Exception to this can be shared libraries which are same physical address space mapped to (possibly) different virtual addresses and kernel memory which is even mapped in the same way in every process (to avoid TLB flushing on syscall, I think). And things like shmat ;) - these are what I count as 'indirect' access. One can, however, check that they are usually located long way from process code and we are usually able to access them (this is why they are there, nevertheless accessing them in a improper way will produce segmentation fault).
Still, segmentation fault can occur in case of accessing our own (process) memory in improper way (for instance trying to write to non-writable space). But the most common reason for it is the access to the part of the virtual address space that is not mapped to physical one at all.
And all of this with respect to virtual memory systems.
If this server is visible to the outside world, It's worth checking if it's having lots of requests to connect from the outside world (i.e. people trying to break into it)
Disclaimer: I haven't used Java 8 yet, only read about it.
Function<String, Integer>
doesn't throw IOException
, so you can't put any code in it that throws IOException
. If you're calling a method that expects a Function<String, Integer>
, then the lambda that you pass to that method can't throw IOException
, period. You can either write a lambda like this (I think this is the lambda syntax, not sure):
(String s) -> {
try {
return myMethod(s);
} catch (IOException ex) {
throw new RuntimeException(ex);
// (Or do something else with it...)
}
}
Or, if the method you're passing the lambda to is one you wrote yourself, you can define a new functional interface and use that as the parameter type instead of Function<String, Integer>
:
public interface FunctionThatThrowsIOException<I, O> {
O apply(I input) throws IOException;
}
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
Raymond Chen has a really good rant against using flow control macros. His best example is straight from the original Bourne shell source code:
ADDRESS alloc(nbytes)
POS nbytes;
{
REG POS rbytes = round(nbytes+BYTESPERWORD,BYTESPERWORD);
LOOP INT c=0;
REG BLKPTR p = blokp;
REG BLKPTR q;
REP IF !busy(p)
THEN WHILE !busy(q = p->word) DO p->word = q->word OD
IF ADR(q)-ADR(p) >= rbytes
THEN blokp = BLK(ADR(p)+rbytes);
IF q > blokp
THEN blokp->word = p->word;
FI
p->word=BLK(Rcheat(blokp)|BUSY);
return(ADR(p+1));
FI
FI
q = p; p = BLK(Rcheat(p->word)&~BUSY);
PER p>q ORF (c++)==0 DONE
addblok(rbytes);
POOL
}
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
Use +
for string concatenation.
"Your number is " + theNumber + "!"
Case
When (LNSEQNBR / 16384)%1 = 0 then 1
else 0
end
Here's a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is "in use", so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?
Knowing this, we can construct our associative array:
$SEARCHABLE_TABLE_COLUMNS = [
'users' => [ 'email' ],
];
Then, we can set our values that we will check:
$table = 'users';
$column = 'email';
$value = '[email protected]';
Then, we can use array_key_exists()
and in_array()
with eachother to execute a one, two step combo and then act upon the truthy
condition:
// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {
// step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this will either return the first matching record or null
$exists = DB::table($table)->where($column, '=', $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
// if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if
statements that are executed synchronously.
array_key_exists()
andin_array()
are PHP functions.
source:
The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value}
(where table
, column
, and value
are variables).
You could have:
$SEARCHABLE_TABLE_COLUMNS = [
'accounts' => [ 'account_name', 'phone', 'business_email' ],
'users' => [ 'email' ],
];
and then you could make GET requests such as:
GET /in-use/accounts/account_name/Bob's Drywall
(you may need to uri encode the last part, but usually not)
GET /in-use/accounts/phone/888-555-1337
GET /in-use/users/email/[email protected]
Notice also that no one can do:
GET /in-use/users/password/dogmeat1337
because password
is not listed in your list of allowed columns for user
.
Good luck on your journey.
You can also use a formula in excel in order to convert this type of date to a date type excel can read:
=DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))
And you get: 12/7/2016
from: Wed Dec 07 00:00:00 UTC 2016
Use: xmlhttp.setRequestHeader(key, value);
For Tomcat 8:
Linux :
Create setenv.sh and update it with following:
export SPRING_PROFILES_ACTIVE=dev
Windows:
Create setenv.bat and update it with following:
set SPRING_PROFILES_ACTIVE=dev
Solved it!!!
After searching for ages and trying all these other suggestions which didn't work, I finally found the solution for my setup.
My setup/scenario:
Solution
Remove any the folder named django in the same directory of manage.py
Thats right...as soon as I removed the folder "django" which only contained a __init__.py file...I could run the server again!
Have no idea why though
If you are on ec2 and wanted to do mvn build then use -T option which tells maven to use number of threads while doing build
eg:mvn -T 10 clean package
I allways use UPPER(text)
like UPPER('%blah%')
As wikipedia says, Median-of-Medians is theoretically o(N), but it is not used in practice because the overhead of finding "good" pivots makes it too slow.
http://en.wikipedia.org/wiki/Selection_algorithm
Here is Java source for a Quickselect algorithm to find the k'th element in an array:
/**
* Returns position of k'th largest element of sub-list.
*
* @param list list to search, whose sub-list may be shuffled before
* returning
* @param lo first element of sub-list in list
* @param hi just after last element of sub-list in list
* @param k
* @return position of k'th largest element of (possibly shuffled) sub-list.
*/
static int select(double[] list, int lo, int hi, int k) {
int n = hi - lo;
if (n < 2)
return lo;
double pivot = list[lo + (k * 7919) % n]; // Pick a random pivot
// Triage list to [<pivot][=pivot][>pivot]
int nLess = 0, nSame = 0, nMore = 0;
int lo3 = lo;
int hi3 = hi;
while (lo3 < hi3) {
double e = list[lo3];
int cmp = compare(e, pivot);
if (cmp < 0) {
nLess++;
lo3++;
} else if (cmp > 0) {
swap(list, lo3, --hi3);
if (nSame > 0)
swap(list, hi3, hi3 + nSame);
nMore++;
} else {
nSame++;
swap(list, lo3, --hi3);
}
}
assert (nSame > 0);
assert (nLess + nSame + nMore == n);
assert (list[lo + nLess] == pivot);
assert (list[hi - nMore - 1] == pivot);
if (k >= n - nMore)
return select(list, hi - nMore, hi, k - nLess - nSame);
else if (k < nLess)
return select(list, lo, lo + nLess, k);
return lo + k;
}
I have not included the source of the compare and swap methods, so it's easy to change the code to work with Object[] instead of double[].
In practice, you can expect the above code to be o(N).
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
You can simply handle the NO_DATA_FOUND
exception by setting your variable to NULL
. This way, only one query is required.
v_column my_table.column%TYPE;
BEGIN
BEGIN
select column into v_column from my_table where ...;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_column := NULL;
END;
... use v_column here
END;
you can use the Common IO library which can get you the Base name of your file and the Extension.
String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
String fileName=FilenameUtils.getBaseName(fileUrl);
String fileExtention=FilenameUtils.getExtension(fileUrl);
//this will return filename:1414240995236 and fileExtention:jpg
array hash_algos(void)
echo hash('sha384', 'Message to be hashed'.'salt');
Here is a link to reference http://php.net/manual/en/function.hash.php
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
String header = dataGridView1.Columns[i].HeaderText;
//String cellText = row.Cells[i].Text;
DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
int colWidth = column.Width; // store columns width after auto resize
colWidth += 50; // add 30 pixels to what 'colWidth' already is
this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
}
}
The problem I need to solve is to store contracts containing a few fields (address, book, num_of_days, borrower_addr, blk_data), blk_data is a transaction list (block number and transaction address). This question and answer helped me. I would like to share my code as below. Hope this helps.
- Schema definition. See blk_data.
var ContractSchema = new Schema(
{
address: {type: String, required: true, max: 100}, //contract address
// book_id: {type: String, required: true, max: 100}, //book id in the book collection
book: { type: Schema.ObjectId, ref: 'clc_books', required: true }, // Reference to the associated book.
num_of_days: {type: Number, required: true, min: 1},
borrower_addr: {type: String, required: true, max: 100},
// status: {type: String, enum: ['available', 'Created', 'Locked', 'Inactive'], default:'Created'},
blk_data: [{
tx_addr: {type: String, max: 100}, // to do: change to a list
block_number: {type: String, max: 100}, // to do: change to a list
}]
}
);
- Create a record for the collection in the MongoDB. See blk_data.
// Post submit a smart contract proposal to borrowing a specific book.
exports.ctr_contract_propose_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('req_addr', 'req_addr must not be empty.').isLength({ min: 1 }).trim(),
body('new_contract_addr', 'contract_addr must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
body('num_of_days', 'num_of_days must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data and old id.
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
cur_contract: req.body.new_contract_addr,
status: 'await_approval'
};
async.parallel({
//call the function get book model
books: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if (results.books.isNew) {
// res.render('pg_error', {
// title: 'Proposing a smart contract to borrow the book',
// c: errors.array()
// });
res.status(400).send({ errors: errors.array() });
return;
}
var contract = new Contract(
{
address: req.body.new_contract_addr,
book: req.body.book_id,
num_of_days: req.body.num_of_days,
borrower_addr: req.body.req_addr
});
var blk_data = {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
};
contract.blk_data.push(blk_data);
// Data from form is valid. Save book.
contract.save(function (err) {
if (err) { return next(err); }
// Successful - redirect to new book record.
resObj = {
"res": contract.url
};
res.status(200).send(JSON.stringify(resObj));
// res.redirect();
});
});
},
];
- Update a record. See blk_data.
// Post lender accept borrow proposal.
exports.ctr_contract_propose_accept_post = [
// Validate fields
body('book_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('contract_id', 'book_id must not be empty.').isLength({ min: 1 }).trim(),
body('tx_addr', 'tx_addr must not be empty.').isLength({ min: 1 }).trim(),
body('block_number', 'block_number must not be empty.').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
if (!errors.isEmpty()) {
// There are errors. Render form again with sanitized values/error messages.
res.status(400).send({ errors: errors.array() });
return;
}
// Create a Book object with escaped/trimmed data
var book_fields =
{
_id: req.body.book_id, // This is required, or a new ID will be assigned!
status: 'on_loan'
};
// Create a contract object with escaped/trimmed data
var contract_fields = {
$push: {
blk_data: {
tx_addr: req.body.tx_addr,
block_number: req.body.block_number
}
}
};
async.parallel({
//call the function get book model
book: function(callback) {
Book.findByIdAndUpdate(req.body.book_id, book_fields, {}).exec(callback);
},
contract: function(callback) {
Contract.findByIdAndUpdate(req.body.contract_id, contract_fields, {}).exec(callback);
},
}, function(error, results) {
if (error) {
res.status(400).send({ errors: errors.array() });
return;
}
if ((results.book.isNew) || (results.contract.isNew)) {
res.status(400).send({ errors: errors.array() });
return;
}
var resObj = {
"res": results.contract.url
};
res.status(200).send(JSON.stringify(resObj));
});
},
];
imageView.layer.cornerRadius = imageView.frame.height/2
imageView.clipToBounds = true
It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :
public function saveFormSummary(Request $request) {
...
$status = true;
return $status;
}
Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type
as follows :
public function saveFormSummary(Request $request) {
...
$status = "true";
return $status;
}
Subtract datetime.timedelta(days=1)
7 years later and this code has helped me. However, my times still were not showing up correctly.
Using Matplotlib 2.0.0 and I had to add the following bit of code from Editing the date formatting of x-axis tick labels in matplotlib by Paul H.
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
I changed the format to (%H:%M) and the time displayed correctly.
All thanks to the community.
The main problem is that:
in a constructor, the injection of the dependencies has not yet occurred*
*obviously excluding Constructor Injection
Real-world example:
public class Foo {
@Inject
Logger LOG;
@PostConstruct
public void fooInit(){
LOG.info("This will be printed; LOG has already been injected");
}
public Foo() {
LOG.info("This will NOT be printed, LOG is still null");
// NullPointerException will be thrown here
}
}
IMPORTANT:
@PostConstruct
and @PreDestroy
have been completely removed in Java 11.
To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
Here's a utility method (ES5 compatible) which only maps non null values (hides the call to reduce):
function mapNonNull(arr, cb) {_x000D_
return arr.reduce(function (accumulator, value, index, arr) {_x000D_
var result = cb.call(null, value, index, arr);_x000D_
if (result != null) {_x000D_
accumulator.push(result);_x000D_
}_x000D_
_x000D_
return accumulator;_x000D_
}, []);_x000D_
}_x000D_
_x000D_
var result = mapNonNull(["a", "b", "c"], function (value) {_x000D_
return value === "b" ? null : value; // exclude "b"_x000D_
});_x000D_
_x000D_
console.log(result); // ["a", "c"]
_x000D_
the most simple and straight forward is to create a FTP login. Here is a little and easy to understand tutorial site on stackoverflow itself, how to set things up in 2min... Setting up FTP on Amazon Cloud Server
jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post
and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.
Example:
$.post('status.ajax.php', {deviceId: id})
.done( function(msg) { ... } )
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
Prior to jQuery 1.8, the function done
was called success
and fail
was called error
.
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);
window.external is object and has no method name values
<html>
<head>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
// window.external.values(a.value, b.value, c.value, d.value, e.value);
//use alert to check its working
alert("HELLO");
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
</html>
Because you are passing three arguments to a four arguments method. Also, you are not using the passed closure.
If you want to specify the operations to be made on top of the source
contents, then use a closure. It would be something like this:
def copyAndReplaceText(source, dest, closure){
dest.write(closure( source.text ))
}
// And you can keep your usage as:
copyAndReplaceText(source, dest){
it.replaceAll('Visa', 'Passport!!!!')
}
If you will always swap strings, pass both, as your method signature already states:
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')
Example:
iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP
Log Exampe:
Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0
Other options:
LOG
Turn on kernel logging of matching packets. When this option
is set for a rule, the Linux kernel will print some
information on all matching packets
(like most IP header fields) via the kernel log (where it can
be read with dmesg or syslogd(8)). This is a "non-terminating
target", i.e. rule traversal
continues at the next rule. So if you want to LOG the packets
you refuse, use two separate rules with the same matching
criteria, first using target LOG
then DROP (or REJECT).
--log-level level
Level of logging (numeric or see syslog.conf(5)).
--log-prefix prefix
Prefix log messages with the specified prefix; up to 29
letters long, and useful for distinguishing messages in
the logs.
--log-tcp-sequence
Log TCP sequence numbers. This is a security risk if the
log is readable by users.
--log-tcp-options
Log options from the TCP packet header.
--log-ip-options
Log options from the IP packet header.
--log-uid
Log the userid of the process which generated the packet.
WMI is Windows Management Instrumentation, and it's built into all recent versions of Windows. It allows you to programmatically track things like CPU usage, disk I/O, and memory usage.
Perfmon.exe is a GUI front-end to this interface, and can monitor a process, write information to a log, and allow you to analyze the log after the fact. It's not the world's most elegant program, but it does get the job done.
I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.
Now it is part of official Design Support Library.
In your gradle:
compile 'com.android.support:design:22.2.0'
http://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html
One more way to add view from Activity
ViewGroup rootLayout = findViewById(android.R.id.content);
rootLayout.addView(view);
For Oracle, I highly recommend the free Oracle SQL Developer
http://www.oracle.com/technology/products/database/sql_developer/index.html
The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle
Cells cannot be changed from within a VBA function used as a worksheet formula. Except via this workaround...
Put this function into a new module:
Function SetRGB(x As Range, R As Byte, G As Byte, B As Byte)
On Error Resume Next
x.Interior.Color = RGB(R, G, B)
x.Font.Color = IIf(0.299 * R + 0.587 * G + 0.114 * B < 128, vbWhite, vbBlack)
End Function
Then use this formula in your sheet, for example in cell D2
:
=HYPERLINK(SetRGB(D2;A2;B2;C2);"HOVER!")
Once you hover the mouse over the cell (try it!), the background color updates to the RGB taken from cells A2
to C2
. The font color is a contrasting white or black.
iMessage Extension: For everyone that is fighting with this problem with an messages extension (or any other extension) make sure you enter in "App Store Connect" -> "General Information" -> the Bundle-ID of the application target and not the extension target. We fought 2 days to find this out.
If the web service being invoked uses windows integrated security, creating a NetworkCredential
from the current WindowsIdentity
should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.
Edit: To get the credentials for the current identity, use the following:
Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");
You can use the following
<select data-hai="whatup">
<option label="Select your city">Select your city</option>
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
<option value="queenstown">Queenstown</option>
</select>
From a powershell prompt, use the gci
cmdlet (alias for Get-ChildItem
) and -filter
option:
gci -recurse -filter "hosts"
This will return an exact match to filename "hosts
".
SteveMustafa points out with current versions of powershell you can use the -File
switch to give the following to recursively search for only files named "hosts
" (and not directories or other miscellaneous file-system entities):
gci -recurse -filter "hosts" -File
The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.
".
If you want to avoid the error messages then set the -ErrorAction
to be silent.
gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue
An additional helper is that you can set the root to search from using -Path
.
The resulting command to search explicitly search from, for example, the root of the C drive would be
gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"
Copy the following line to your application manifest file and paste before the <application>
tag.
<uses-permission android:name="android.permission.INTERNET"/>
Placing the permission below the <application/>
tag will work, but will give you warning. So take care to place it before the <application/>
tag declaration.
One way how to do it:
const troll = document.getElementById('troll');_x000D_
_x000D_
['mousedown', 'mouseup'].forEach(type => {_x000D_
if (type === 'mousedown') {_x000D_
troll.addEventListener(type, () => console.log('Mouse is down'));_x000D_
}_x000D_
else if (type === 'mouseup') {_x000D_
troll.addEventListener(type, () => console.log('Mouse is up'));_x000D_
}_x000D_
});
_x000D_
img {_x000D_
width: 100px;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<div id="troll">_x000D_
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">_x000D_
</div>
_x000D_
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
The dataframe can be changed by just doing
df.columns = df.iloc[0]
df = df[1:]
Then
df.to_csv(path, index=False)
Should do the trick.
Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.
Or, if you need to access the element that has that property and it does not use an id, you could go this route:
$("img").each(function () {
if ($(this).css("float") == "left") { $(this).addClass("left"); }
if ($(this).css("float") == "right") { $(this).addClass("right"); }
})
Using Windows 10?
https://docs.microsoft.com/en-us/windows/wsl/install-win10
/etc/apt/sources.list
(Debian 10 Buster/Bullseye)
Installs latest stable Redis (5.0.6 at time of posting)
deb https://deb.debian.org/debian bullseye main
deb https://deb.debian.org/debian bullseye-updates main
deb http://security.debian.org/debian-security/ buster/updates main
deb http://ftp.debian.org/debian bullseye-backports main
apt install redis-server
You can do that with cat and that pipe the output to less:
cat -e yourFile | less
This excerpt from man cat
explains what -e
means:
-e equivalent to -vE
-E, --show-ends
display $ at end of each line
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
Go to /etc/apache2/apache2.conf
You have to edit that file (you should have root permission). Change directory text as bellow:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Now you have to restart apache.
service apache2 restart
This might work for you:
cat <<! | sed '/aaa=\(bbb\|ccc\|ddd\)/!s/\(aaa=\).*/\1xxx/'
> aaa=bbb
> aaa=ccc
> aaa=ddd
> aaa=[something else]
!
aaa=bbb
aaa=ccc
aaa=ddd
aaa=xxx
If you need to find the max/min of a hash, you can use #max_by
or #min_by
people = {'joe' => 21, 'bill' => 35, 'sally' => 24}
people.min_by { |name, age| age } #=> ["joe", 21]
people.max_by { |name, age| age } #=> ["bill", 35]
I used this a little example and it worked.
$('#date').datetimepicker({
defaultDate: new Date()
});
I was searching about how stack works in terms of function and i found this blog its awesome and its explain concept of stack from scratch and how stack store value in stack.
Now on your answer . I will explain with python but you will get good idea how stack works in any language.
Its a program :
def hello(x):
if x==1:
return "op"
else:
u=1
e=12
s=hello(x-1)
e+=1
print(s)
print(x)
u+=1
return e
hello(3)
Source : Cryptroix
some of its topic which it cover in blog:
How Function work ?
Calling a Function
Functions In a Stack
What is Return Address
Stack
Stack Frame
Call Stack
Frame Pointer (FP) or Base Pointer (BP)
Stack Pointer (SP)
Allocation stack and deallocation of stack
StackoverFlow
What is Heap?
But its explain with python language so if you want you can take a look.
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
EDIT: this will case errors with jquery to happen, plus some other inconveniences. YOU SHOULD NOT USE IT: (perhaps if one could add a privaate method instead of a public property function, this would be OK, but don't have the time now). Community wikied
do not use:
Even though javascript's object by default doesn't have the count function, classes are easily extendable, and one can add it oneself:
Object.prototype.count = function () {
var count = 0;
for(var prop in this) {
if(this.hasOwnProperty(prop))
count = count + 1;
}
return count;
}
So that after that one can execute
var object = {'key1': 'val1', 'key2':'val2', 'key3':'val3'};
console.log(object.count()); // 3
As a conclusion, if you want count functionality in objects, you need to copy the code from code block 1, and paste it early in execution time ( before you call the count ).
Let me know if that works for you!
Regards, Pedro
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.
In some cases, static methods can be difficult to test, especially if they need to be mocked, which is why most mocking frameworks don't support them. I found this blog post to be very useful in determining how to mock static methods and classes.
Rewrite rules are pretty much written the same way with nginx: http://wiki.nginx.org/HttpRewriteModule#rewrite
Which rules are causing you trouble? I could help you translate those!
Don't use os.system
. It has been deprecated in favor of subprocess. From the docs: "This module intends to replace several older modules and functions: os.system
, os.spawn
".
Like in your case:
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt"
import subprocess
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared