You can choose:
if [[ $? -ne 0 ]]; then # -ne: not equal
if ! [[ $? -eq 0 ]]; then # -eq: equal
if [[ ! $? -eq 0 ]]; then
!
inverts the return of the following expression, respectively.
Yes you can negate the test as SiegeX has already pointed out.
However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:
[[ ":$PATH:" != *":$1:"* ]]
Use the not
boolean operator:
nyval = not myval
not
returns a boolean value (True
or False
):
>>> not 1
False
>>> not 0
True
If you must have an integer, cast it back:
nyval = int(not myval)
However, the python bool
type is a subclass of int
, so this may not be needed:
>>> int(not 0)
1
>>> int(not 1)
0
>>> not 0 == 1
True
>>> not 1 == 0
True
I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:
AND (isdelete is NULL or isdelete = 0)
Shouldn't Predicate#negate
be what you are looking for?
Packet
A packet is the unit of data that is routed between an origin and a destination on the Internet or any other packet-switched network. When any file (e-mail message, HTML file, Graphics Interchange Format file, Uniform Resource Locator request, and so forth) is sent from one place to another on the Internet, the Transmission Control Protocol (TCP) layer of TCP/IP divides the file into "chunks" of an efficient size for routing. Each of these packets is separately numbered and includes the Internet address of the destination. The individual packets for a given file may travel different routes through the Internet. When they have all arrived, they are reassembled into the original file (by the TCP layer at the receiving end).
Frame
1) In telecommunications, a frame is data that is transmitted between network points as a unit complete with addressing and necessary protocol control information. A frame is usually transmitted serial bit by bit and contains a header field and a trailer field that "frame" the data. (Some control frames contain no data.)
2) In time-division multiplexing (TDM), a frame is a complete cycle of events within the time division period.
3) In film and video recording and playback, a frame is a single image in a sequence of images that are recorded and played back.
4) In computer video display technology, a frame is the image that is sent to the display image rendering devices. It is continuously updated or refreshed from a frame buffer, a highly accessible part of video RAM.
5) In artificial intelligence (AI) applications, a frame is a set of data with information about a particular object, process, or image. An example is the iris-print visual recognition system used to identify users of certain bank automated teller machines. This system compares the frame of data for a potential user with the frames in its database of authorized users.
This program has a functions for
Find Successor
class BNode{
int data;
BNode left, right;
public BNode(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public class BST {
static BNode root;
public int add(int value){
BNode newNode, current;
newNode = new BNode(value);
if(root == null){
root = newNode;
current = root;
}
else{
current = root;
while(current.left != null || current.right != null){
if(newNode.data < current.data){
if(current.left != null)
current = current.left;
else
break;
}
else{
if(current.right != null)
current = current.right;
else
break;
}
}
if(newNode.data < current.data)
current.left = newNode;
else
current.right = newNode;
}
return value;
}
public void inorder(BNode root){
if (root != null) {
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
}
public boolean find(int value){
boolean flag = false;
BNode current;
current = root;
while(current!= null){
if(current.data == value){
flag = true;
break;
}
else if(current.data > value)
current = current.left;
else
current = current.right;
}
System.out.println("Is "+value+" present in tree? : "+flag);
return flag;
}
public void successor(int value){
BNode current;
current = root;
if(find(value)){
while(current.data != value){
if(value < current.data && current.left != null){
System.out.println("Node is: "+current.data);
current = current.left;
}
else if(value > current.data && current.right != null){
System.out.println("Node is: "+current.data);
current = current.right;
}
}
}
else
System.out.println(value+" Element is not present in tree");
}
public static void main(String[] args) {
BST b = new BST();
b.add(50);
b.add(30);
b.add(20);
b.add(40);
b.add(70);
b.add(60);
b.add(80);
b.add(90);
b.inorder(root);
b.find(30);
b.find(90);
b.find(100);
b.find(50);
b.successor(90);
System.out.println();
b.successor(70);
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style type="text/css">
body
,html
{
height: 100%;
margin: 0;
padding: 0;
color: #FFF;
}
#header
{
float: left;
width: 100%;
background: red;
}
#content
{
height: 100%;
overflow: auto;
background: blue;
}
</style>
</head>
<body>
<div id="content">
<div id="header">
Header
<p>Header stuff</p>
</div>
Content
<p>Content stuff</p>
</div>
</body>
</html>
In all sane browsers, you can put the "header" div before the content, as a sibling, and the same CSS will work. However, IE7- does not interpret the height correctly if the float is 100% in that case, so the header needs to be IN the content, as above. The overflow: auto will cause double scroll bars on IE (which always has the viewport scrollbar visible, but disabled), but without it, the content will clip if it overflows.
You can declare globals by augmenting the window interface:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
Sources:
You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
This may not be quite what you are looking for but this is what worked for what I'm doing. All of this is after my onCreate
:
boilingpointK = (TextView) findViewById(R.id.boilingpointK);
boilingpointK.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("Boiling Point K".equals(boilingpointK.getText().toString()))
boilingpointK.setText("2792");
else if ("2792".equals(boilingpointK.getText().toString()))
boilingpointK.setText("Boiling Point K");
}
});
You must setup postgresql-server-dev-X.Y, where X.Y. your's servers version, and it will install libpq-dev and other servers variables at modules for server side developing. In my case it was
apt-get install postgresql-server-dev-9.5
Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: libmysqlclient18 mysql-common Use 'apt-get autoremove' to remove them. The following extra packages will be installed:
libpq-dev Suggested packages: postgresql-doc-10 The following NEW packages will be installed: libpq-dev postgresql-server-dev-9.5
In your's case
sudo apt-get install postgresql-server-dev-X.Y
sudo apt-get install python-psycopg2
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
I understand that
std::atomic<>
makes an object atomic.
That's a matter of perspective... you can't apply it to arbitrary objects and have their operations become atomic, but the provided specialisations for (most) integral types and pointers can be used.
a = a + 12;
std::atomic<>
does not (use template expressions to) simplify this to a single atomic operation, instead the operator T() const volatile noexcept
member does an atomic load()
of a
, then twelve is added, and operator=(T t) noexcept
does a store(t)
.
Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:
1. double d = (double)5 / 20;
2. double v = (double)5 / (double) 20;
3. double v = 5 / (double) 20;
Note that casting the result won't do it. Because first division is done as per precedence rule.
double d = (double)(5 / 20); //produces 0.0
I do not think there is any problem with casting as such you are thinking about.
This is a C# Version. It's based on the idea of sort the array.
public int solution(int[] A)
{
// write your code in C# 6.0 with .NET 4.5 (Mono)
Array.Sort(A);
var max = A.Max();
if(max < 0)
return 1;
else
for (int i = 1; i < max; i++)
{
if(!A.Contains(i)) {
return i;
}
}
return max + 1;
}
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
When a source program is fed into the lexical analyzer, it begins by breaking up the characters into sequences of lexemes. The lexemes are then used in the construction of tokens, in which the lexemes are mapped into tokens. A variable called myVar would be mapped into a token stating <id, "num">, where "num" should point to the variable's location in the symbol table.
Shortly put:
An example includes:
x = a + b * 2
Which yields the lexemes: {x, =, a, +, b, *, 2}
With corresponding tokens: {<id, 0>, <=>, <id, 1>, <+>, <id, 2>, <*>, <id, 3>}
select max( 1 )
into my_if_has_data
from MY_TABLE X
where X.my_field = my_condition
and rownum = 1;
Not iterating through all records.
If MY_TABLE has no data, then my_if_has_data sets to null.
Add the following line in style.xml
<style name="Base.Theme.AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme" parent="Base.Theme.AppTheme">
</style>
Now add the following line in style-v21,
<style name="AppTheme" parent="Base.Theme.AppTheme">
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
and set the theme as android:theme="@style/AppTheme"
It will make the status bar transparent.
Well for one thing use int.TryParse instead...
int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
id = -1;
}
That assumes that "not present" should have the same result as "not an integer" of course.
EDIT: In other cases, when you're going to use request parameters as strings anyway, I think it's definitely a good idea to validate that they're present.
If you go into Configure under Home there is a "Help" note on how to:
Home directory /var/lib/jenkins Help for feature: Home directory
By default, Jenkins stores all of its data in this directory on the file system.
There are a few ways to change the Jenkins home directory:
Edit the JENKINS_HOME variable in your Jenkins configuration file (e.g. /etc/sysconfig/jenkins on Red Hat Linux).
Use your web container's admin tool to set the JENKINS_HOME environment variable.
Set the environment variable JENKINS_HOME before launching your web container, or before launching Jenkins directly from the WAR file.
Set the JENKINS_HOME Java system property when launching your web container, or when launching Jenkins directly from the WAR file.
Modify web.xml in jenkins.war (or its expanded image in your web container). This is not recommended.
This value cannot be changed while Jenkins is running. It is shown here to help you ensure that your configuration is taking effect.
The new HTTP Client shipped with Java 9 but as part of an Incubator module named
jdk.incubator.httpclient
. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.
In Java 9, you can send a GET
request like:
// GET
HttpResponse response = HttpRequest
.create(new URI("http://www.stackoverflow.com"))
.headers("Foo", "foovalue", "Bar", "barvalue")
.GET()
.response();
Then you can examine the returned HttpResponse
:
int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());
Since this new HTTP Client is in java.httpclient
jdk.incubator.httpclient
module, you should declare this dependency in your module-info.java
file:
module com.foo.bar {
requires jdk.incubator.httpclient;
}
Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the $lookup stage adds a new array field whose elements are the matching documents from the “joined” collection. The $lookup stage passes these reshaped documents to the next stage. The $lookup stage has the following syntaxes:
To perform an equality match between a field from the input documents with a field from the documents of the “joined” collection, the $lookup stage has the following syntax:
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
The operation would correspond to the following pseudo-SQL statement:
SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (SELECT <documents as determined from the pipeline>
FROM <collection to join>
WHERE <pipeline> );
I took Joe Love's answer and rewrote it using the IN
operator with sub-selects instead of =
to make the function faster (according to Hubbitus's suggestion):
create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])
returns integer as $$
declare
rx record;
rd record;
v_sql varchar;
v_subquery varchar;
v_primary_key varchar;
v_foreign_key varchar;
v_rows integer;
recnum integer;
begin
recnum := 0;
select ccu.column_name into v_primary_key
from
information_schema.table_constraints tc
join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
and tc.constraint_type='PRIMARY KEY'
and tc.table_name=p_table
and tc.table_schema=p_schema;
for rx in (
select kcu.table_name as foreign_table_name,
kcu.column_name as foreign_column_name,
kcu.table_schema foreign_table_schema,
kcu2.column_name as foreign_table_primary_key
from information_schema.constraint_column_usage ccu
join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema
join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
where ccu.table_name=p_table and ccu.table_schema=p_schema
and TC.CONSTRAINT_TYPE='FOREIGN KEY'
and tc2.constraint_type='PRIMARY KEY'
)
loop
v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;
v_subquery := 'select "'||rx.foreign_table_primary_key||'" as key from '||rx.foreign_table_schema||'."'||rx.foreign_table_name||'"
where "'||rx.foreign_column_name||'"in('||coalesce(p_keys, p_subquery)||') for update';
if p_foreign_keys @> ARRAY[v_foreign_key] then
--raise notice 'circular recursion detected';
else
p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);
recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);
p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);
end if;
end loop;
begin
if (coalesce(p_keys, p_subquery) <> '') then
v_sql := 'delete from '||p_schema||'."'||p_table||'" where "'||v_primary_key||'"in('||coalesce(p_keys, p_subquery)||')';
--raise notice '%',v_sql;
execute v_sql;
get diagnostics v_rows = row_count;
recnum := recnum + v_rows;
end if;
exception when others then recnum=0;
end;
return recnum;
end;
$$
language PLPGSQL;
It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.
boolean checkWordExistence(String word, String sentence) {
if (sentence.contains(word)) {
int start = sentence.indexOf(word);
int end = start + word.length();
boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));
return valid_left && valid_right;
}
return false;
}
Output:
checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true
P.S Make sure you have filtered out any commas or full stops beforehand.
Another alternative is KMP (Knuth–Morris–Pratt).
The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.
Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {_x000D_
if (pattern.length == 0)_x000D_
return 0; // Immediate match_x000D_
_x000D_
// Compute longest suffix-prefix table_x000D_
var lsp = [0]; // Base case_x000D_
for (var i = 1; i < pattern.length; i++) {_x000D_
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1];_x000D_
if (pattern.charAt(i) == pattern.charAt(j))_x000D_
j++;_x000D_
lsp.push(j);_x000D_
}_x000D_
_x000D_
// Walk through text string_x000D_
var j = 0; // Number of chars matched in pattern_x000D_
for (var i = 0; i < text.length; i++) {_x000D_
while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
j = lsp[j - 1]; // Fall back in the pattern_x000D_
if (text.charAt(i) == pattern.charAt(j)) {_x000D_
j++; // Next char matched, increment position_x000D_
if (j == pattern.length)_x000D_
return i - (j - 1);_x000D_
}_x000D_
}_x000D_
return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
Are you sure you're using the correct proxy as system properties?
Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
I had the same problem with openCV on Raspberry Pi... don't know if this can solve your problem, but what worked for me was
import time
import cv2
cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,1024)
time.sleep(2)
cap.set(15, -8.0)
the time you have to use can be different
The following will extends the problem a bit by removing from the first string argument any character that occurs in the second string argument.
/*
* delete one character from a string
*/
static void
_strdelchr( char *s, size_t i, size_t *a, size_t *b)
{
size_t j;
if( *a == *b)
*a = i - 1;
else
for( j = *b + 1; j < i; j++)
s[++(*a)] = s[j];
*b = i;
}
/*
* delete all occurrences of characters in search from s
* returns nr. of deleted characters
*/
size_t
strdelstr( char *s, const char *search)
{
size_t l = strlen(s);
size_t n = strlen(search);
size_t i;
size_t a = 0;
size_t b = 0;
for( i = 0; i < l; i++)
if( memchr( search, s[i], n))
_strdelchr( s, i, &a, &b);
_strdelchr( s, l, &a, &b);
s[++a] = '\0';
return l - a;
}
@Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
I prefer creating my own xml with no auto-generated tags. In this I can ignore creating the nodes with null values:
public static string ConvertToXML<T>(T objectToConvert)
{
XmlDocument doc = new XmlDocument();
XmlNode root = doc.CreateNode(XmlNodeType.Element, objectToConvert.GetType().Name, string.Empty);
doc.AppendChild(root);
XmlNode childNode;
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in properties)
{
if (prop.GetValue(objectToConvert) != null)
{
childNode = doc.CreateNode(XmlNodeType.Element, prop.Name, string.Empty);
childNode.InnerText = prop.GetValue(objectToConvert).ToString();
root.AppendChild(childNode);
}
}
return doc.OuterXml;
}
A decimal type can not contain formatting information. You can create another property, say FormattedProperty
of a string type that does what you want.
Edit:
If you have snap
or want to install it, just do:
$ sudo snap install postman
if you don't have it, install it as:
$ sudo apt update
$ sudo apt install snapd
Another way is create an script:
First create this script:
create a file install-postman.sh, inside of it add:
#!/bin/bash
cd /tmp || exit
echo "Downloading Postman ..."
wget -q https://dl.pstmn.io/download/latest/linux?arch=64 -O postman.tar.gz
tar -xzf postman.tar.gz
rm postman.tar.gz
echo "Installing to opt..."
if [ -d "/opt/Postman" ];then
sudo rm -rf /opt/Postman
fi
sudo mv Postman /opt/Postman
echo "Creating symbolic link..."
if [ -L "/usr/bin/postman" ];then
sudo rm -f /usr/bin/postman
fi
sudo ln -s /opt/Postman/Postman /usr/bin/postman
echo "Installation completed successfully."
echo "You can use Postman!"
run it in terminal with:
$ sh install-postman.sh
Then create the desktop launcher:
Postman.desktop
[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=postman
Icon=/opt/Postman/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
Put this file in your desktop if you want (don't forget give to it execution permissions). Double click, and that's it!
Forever thanks to Aviskase (github acount name).
source -> https://gist.github.com/aviskase/e642248c35e400b56e2489430952369f#file-postman-desktop
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
setBounds
is used to define the bounding rectangle of a component. This includes it's position and size.
The is used in a number of places within the framework.
For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
The problem occurred due to the Control validator. Just Add the J Query reference to your web page as follows and then add the Validation Settings in your web.config file to overcome the problem. I too faced the same problem and the below gave the solution to my problem.
Step1:
Step2 :
It will resolve your problem.
If you use the gson.JsonObject you can have something like that:
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)
Following the accepted answer, if you do not wish to customize the markup, for separation of concerns or simply because you use a CMS, the following solution works fine:
.valign {_x000D_
font-size: 0;_x000D_
}_x000D_
_x000D_
.valign > [class*="col"] {_x000D_
display: inline-block;_x000D_
float: none;_x000D_
font-size: 14px;_x000D_
font-size: 1rem;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row valign">_x000D_
<div class="col-xs-5">_x000D_
<div style="height:5em;border:1px solid #000">Big</div>_x000D_
</div>_x000D_
<div class="col-xs-5">_x000D_
<div style="height:3em;border:1px solid #F00">Small</div>_x000D_
</div>_x000D_
</div>
_x000D_
The limitation here is that you cannot inherit font size from the parent element because the row sets the font size to 0 in order to remove white space.
This is similiarly to @RobMcAfee except that I use magic number instead of 2 dimensional array.
int rand7() {
int m = 1203068;
int r = (m >> (rand5() - 1) * 5 + rand5() - 1) & 7;
return (r > 0) ? r : rand7();
}
Here is what you can try
OpenWindow.document.write(output);
call OpenWindow.init()
when the dom is ready So the parent window will have
OpenWindow.onload = function(){
OpenWindow.init('test');
}
and in the child
function init(txt){
$('#test').text(txt);
}
is working but MacOs recently has autoplay policy for user: https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/, I resolved the same issue using a button to enable sound:
ejm:
<video autoplay loop muted id="myVideo">_x000D_
<source src="amazon.mp4" type="video/mp4">_x000D_
Sorry, your browser doesn't support embedded videos..._x000D_
</video>_x000D_
_x000D_
<button class="pausee" onclick="disableMute()" type="button">Enable sound</button>_x000D_
_x000D_
<script>_x000D_
var vid = document.getElementById("myVideo");_x000D_
function disableMute() { _x000D_
vid.muted = false;_x000D_
}_x000D_
</script>
_x000D_
Facing the blank screen in Laravel 5.8. Every thing seems fine with both storage and bootstrap folder given 777 rights. On
php artisan cache:clear
It shows the problem it was the White spaces in App Name of .env file
If you're rolling your own I'd highly recommend looking at http://effbot.org/zone/element-soap.htm.
find the file pg_hba.conf
- it may be located, for example in /etc/postgresql-9.1/pg_hba.conf
.
cd /etc/postgresql-9.1/
Back it up
cp pg_hba.conf pg_hba.conf-backup
place the following line (as either the first uncommented line, or as the only one):
For all occurrence of below (local and host) , exepct replication section if you don't have any it has to be changed as follow ,no MD5 or Peer autehication should be present.
local all all trust
restart your PostgreSQL server (e.g., on Linux:)
sudo /etc/init.d/postgresql restart
If the service (daemon) doesn't start reporting in log file:
local connections are not supported by this build
you should change
local all all trust
to
host all all 127.0.0.1/32 trust
you can now connect as any user. Connect as the superuser postgres
(note, the superuser name may be different in your installation. In some systems it is called pgsql
, for example.)
psql -U postgres
or
psql -h 127.0.0.1 -U postgres
(note that with the first command you will not always be connected with local host)
Reset password ('replace my_user_name with postgres since you are resetting postgres user)
ALTER USER my_user_name with password 'my_secure_password';
Restore the old pg_hba.conf
as it is very dangerous to keep around
cp pg_hba.conf-backup pg_hba.conf
restart the server, in order to run with the safe pg_hba.conf
sudo /etc/init.d/postgresql restart
Further Reading about that pg_hba file: http://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.
From the connecting schema:
CREATE SYNONYM pi_int FOR pct.pi_int;
Then you can query pi_int
as:
SELECT * FROM pi_int;
Hi I have been using this page a lot for constraints and "how to". It took me forever to get to the point of realizing I needed:
myView.translatesAutoresizingMaskIntoConstraints = NO;
to get this example to work. Thank you Userxxx, Rob M. and especially larsacus for the explanation and code here, it has been invaluable.
Here is the code in full to get the examples above to run:
UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor redColor];
myView.translatesAutoresizingMaskIntoConstraints = NO; //This part hung me up
[self.view addSubview:myView];
//needed to make smaller for iPhone 4 dev here, so >=200 instead of 748
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-[myView(>=200)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:[myView(==200)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
SELECT DISTINCT a,b,c FROM t
is roughly equivalent to:
SELECT a,b,c FROM t GROUP BY a,b,c
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
SELECT id
FROM sales S
INNER JOIN
(
SELECT saleprice, saledate
FROM sales
GROUP BY saleprice, saledate
HAVING COUNT(*) = 1
) T
ON S.saleprice=T.saleprice AND s.saledate=T.saledate
)
Use a slice, like below:
with open('yourfile.txt') as f:
lines_after_17 = f.readlines()[17:]
If the file is too big to load in memory:
with open('yourfile.txt') as f:
for _ in range(17):
next(f)
for line in f:
# do stuff
wp-config.php
add define('FS_METHOD', 'direct');
wp-content/
, wp-content/plugins/
.wp-content/plugins
dir).Worked on version 3.2.1
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.
An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).
You can use {php}
tags
Method 1 (won't work in Smarty 3.1 or later):
{php}
$var =
$this->get_template_vars('var');
var_dump($var);
{/php}
Method 2:
{$var|@print_r}
Method 3:
{$var|@var_dump}
input.Remove(input.IndexOf(')')).Substring(input.IndexOf('(') + 1);
In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:
[mysqld]
innodb_file_per_table=1
Github documentation contains a script that replaces the committer info for all commits in a branch.
Run the following script from terminal after changing the variable values
#!/bin/sh
git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_COMMITTER_NAME="$CORRECT_NAME"
export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
export GIT_AUTHOR_NAME="$CORRECT_NAME"
export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags
Push the corrected history to GitHub:
git push --force --tags origin 'refs/heads/*'
OR if you like to push selected references of the branches then use
git push --force --tags origin 'refs/heads/develop'
If someone is facing issue using texttocolumns function in UFT. Please try using below function.
myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
Here we are using coma(,) as delimiter.
Now after running install.sh
in Mac OS
, google itself giving the information to run completion.bash.inc
and path.bash.inc
.
If you're using zsh
terminal, it'll ask you to run completion.zsh.inc
and path.zsh.inc
. Please see the image below
If you are using Windows10, PHP 7.2 and try to connect to mysql. If this error occurred
Uncaught Error: Call to undefined function mysqli() in
The do the following steps to get it correct.
Hope this helps to someone.
Here is the code with line 156, it has try and catch above it
/// <summary>
/// Execute a SQL Query statement, using the default SQL connection for the application
/// </summary>
/// <param name="query">SQL query to execute</param>
/// <returns>DataTable of results</returns>
public static DataTable Query(string query)
{
DataTable results = new DataTable();
string configConnectionString = "ApplicationServices";
System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Configuration.ConnectionStringSettings connString;
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];
if (connString != null)
{
try
{
using (SqlConnection conn = new SqlConnection(connString.ToString()))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
dataAdapter.Fill(results);
return results;
}
catch (Exception ex)
{
throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
}
}
else
{
throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
}
}
else
{
throw new SqlException(string.Format("No connection strings found in Web.config file."));
}
}
Also be sure that your file is actually a CSV file. For example, if you had an .xls file, and simply changed the file extension to .csv, the file won't import and will give the error above. To check to see if this is your problem open the file in excel and it will likely say:
"The file format and extension of 'Filename.csv' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?"
To fix the file: open the file in Excel, click "Save As", Choose the file format to save as (use .cvs), then replace the existing file.
This was my problem, and fixed the error for me.
Store them in a file outside web root.
pJosh, this might help understanding. In my case, my Team Provisioning Profile was expiring (the Provisioning Portal indicated it is managed by XCode), as well as the device testing profile for the app. (I still don't know why, but the portal had a "Renew" button next to the team profile, but it wouldn't do anything when I clicked it.)
So, I deleted the profiles about to expire, then in XCode go to Organizer (Command-Shift-2), under Library / Provisioning Profiles, I deleted the expiring ones. Then click "Refresh" at the bottom, enter my Apple ID, and it renewed the expiring ones.
Finally, on my Target, I went to Build Settings, Code Signing, and made sure to select the provisioning profile. Voila, now it builds to my device.
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
Do you have a "tmp" folder in your Magento installation directory? If not, make one and see if that helps!
EDIT: Failing that, check your upload_tmp_dir in php.ini - make sure it's set.
SELECT ROUND((6 - 3 * RAND()), 0)
Using a commit's SHA1 key, you could do the following:
First, find the commit you want for a specific file:
git log -n <# commits> <file-name>
This, based on your <# commits>
, will generate a list of commits for a specific file.
TIP: if you aren't sure what commit you are looking for, a good way to find out is using the following command: git diff <commit-SHA1>..HEAD <file-name>
. This command will show the difference between the current version of a commit, and a previous version of a commit for a specific file.
NOTE: a commit's SHA1 key is formatted in the git log -n
's list as:
commit
<SHA1 id>
Second, checkout the desired version:
If you have found the desired commit/version you want, simply use the command: git checkout <desired-SHA1> <file-name>
This will place the version of the file you specified in the staging area. To take it out of the staging area simply use the command: reset HEAD <file-name>
To revert back to where the remote repository is pointed to, simply use the command: git checkout HEAD <file-name>
There is a simple css for it:
white-space: pre;
It keeps the spaces that you add in the HTML rather than unifying them.
A null
pointer is one that points to nowhere. When you dereference a pointer p
, you say "give me the data at the location stored in "p". When p
is a null
pointer, the location stored in p
is nowhere
, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception
.
In general, it's because something hasn't been initialized properly.
That's what I got:
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a nickname!");
while (!scanner.hasNext("[a-zA-Z]{3,8}+")) {
System.out.println("Nickname should contain only Alphabetic letters! At least 3 and max 8 letters");
scanner.next();
}
String nickname = scanner.next();
System.out.println("Thank you! Got " + nickname);
Read about regex Pattern here: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
You can access Gist by visiting the following url gist.github.com. Alternatively you can access it from within your Github account (after logging in) as shown in the picture below:
Github: A hosting service that houses a web-based git repository. It includes all the fucntionality of git with additional features added in.
Gist: Is an additional feature added to github to allow the sharing of code snippets, notes, to do lists and more. You can save your Gists as secret or public. Secret Gists are hidden from search engines but visible to anyone you share the url with.
For example. If you wanted to write a private to-do list. You could write one using Github Markdown as follows:
NB: It is important to preserve the whitespace as shown above between the dash and brackets. It is also important that you save the file with the extension .md because we want the markdown to format properly. Remember to save this Gist as secret if you do not want others to see it.
The end result looks like the image below. The checkboxes are clickable because we saved this Gist with the extension .md
Let's illustrate what's happening here:
Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
... def __init__(self, x=[]):
... x.append(1)
...
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)
You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults
.
As other posters have pointed out, you probably want to use None
as a sentinel value and give each instance it's own list.
You can do the following to install java 8 on your machine. First get the link of tar
that you want to install. You can do this by:
- go to java downloads page and find the appropriate download.
- Accept the license agreement and download it.
- In the download page in your browser right click and
copy link address
.
Then in your terminal:
$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java
I needed to solve this in VB.NET. Here's what I've got that seems to work:
Private Sub ComboBox1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox_AllSites.SelectionChanged
Dim cr As System.Windows.Controls.ComboBoxItem = ComboBox1.SelectedValue
Dim currentText = cr.Content
MessageBox.Show(currentText)
End Sub
i have a similar problem. for correct formatting EditText text content to double value i use this code:
try {
String eAm = etAmount.getText().toString();
DecimalFormat dF = new DecimalFormat("0.00");
Number num = dF.parse(eAm);
mPayContext.amount = num.doubleValue();
} catch (Exception e) {
mPayContext.amount = 0.0d;
}
this is independet from current phone locale and return correct double value.
hope it's help;
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
/*.*
#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trail and error!
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
You can test the rowcount
$sqlStatement->execute( ...);
if ($sqlStatement->rowCount() > 0)
{
return true;
}
Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.
This can be used to good effect to "catch" stdout output in a GUI application.
Here's a silly example in PyQt:
import sys
from PyQt4 import QtGui
class OutputWindow(QtGui.QPlainTextEdit):
def write(self, txt):
self.appendPlainText(str(txt))
app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"
There is a hacky way to do it.
Set some boolean field to indicate whether the work was completed. Then before the block of code, set a timer to run a piece of code after your timeout. The timer will check if the block of code had finished executing, and if not, throw an exception. Otherwise it will do nothing.
The end of the block of code should, of course, set the field to true to indicate the work was done.
In the simple setup you are likely using, getchar
works with buffered input, so you have to press enter before getchar gets anything to read. Strings are not terminated by EOF
; in fact, EOF
is not really a character, but a magic value that indicates the end of the file. But EOF
is not part of the string read. It's what getchar
returns when there is nothing left to read.
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
The default behaviour is false:
By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.
The query you are after will be
SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'
First get the value from edit text in a String variable
String value = edttxt.getText().toString();
Then set that value to textView
txtview.setText(value);
Where edttxt refers to edit text field in XML file and txtview refers to textfield in XML file to show the value
You can do this:
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).
I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.
In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.
It work for me in this issue in a project of react-native:
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
244 actionable tasks: 2 executed, 242 up-to-date D8: Cannot fit requested classes in a single dex file (# fields: 67296 > 65536) com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html ....
I Did this:
Uninstall the app from my device:
The number of method references in a .dex file cannot exceed 64k API 17
Size of some float types may exceed the size of int
.
This example shows a safe conversion of any float type to int
using the int safeFloatToInt(const FloatType &num);
function:
#include <iostream>
#include <limits>
using namespace std;
template <class FloatType>
int safeFloatToInt(const FloatType &num) {
//check if float fits into integer
if ( numeric_limits<int>::digits < numeric_limits<FloatType>::digits) {
// check if float is smaller than max int
if( (num < static_cast<FloatType>( numeric_limits<int>::max())) &&
(num > static_cast<FloatType>( numeric_limits<int>::min())) ) {
return static_cast<int>(num); //safe to cast
} else {
cerr << "Unsafe conversion of value:" << num << endl;
//NaN is not defined for int return the largest int value
return numeric_limits<int>::max();
}
} else {
//It is safe to cast
return static_cast<int>(num);
}
}
int main(){
double a=2251799813685240.0;
float b=43.0;
double c=23333.0;
//unsafe cast
cout << safeFloatToInt(a) << endl;
cout << safeFloatToInt(b) << endl;
cout << safeFloatToInt(c) << endl;
return 0;
}
Result:
Unsafe conversion of value:2.2518e+15
2147483647
43
23333
Python has several XML modules built in. The simplest one for the case that you already have a string with the full HTML is xml.etree
, which works (somewhat) similarly to the lxml example you mention:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
As an alternative to using regex you could do it in Sets:
from sets import Set
allowed_chars = Set('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
if Set(my_little_sting).issubset(allowed_chars):
# your action
print True
I'm adding this by request, not because I think it directly solves the question. My solution involves a table component for displaying tables from my SQL database:
export class TableComponent<T> {
public Data: T[] = [];
public constructor(
protected type: new (value: Partial<T>) => T
) { }
protected insertRow(value: Partial<T>): void {
let row: T = new this.type(value);
this.Data.push(row);
}
}
To put this to use, assume I have a view (or table) in my database VW_MyData and I want to hit the constructor of my VW_MyData class for every entry returned from a query:
export class MyDataComponent extends TableComponent<VW_MyData> {
public constructor(protected service: DataService) {
super(VW_MyData);
this.query();
}
protected query(): void {
this.service.post(...).subscribe((json: VW_MyData[]) => {
for (let item of json) {
this.insertRow(item);
}
}
}
}
The reason this is desirable over simply assigning the returned value to Data, is say I have some code that applies a transformation to some column of VW_MyData in its constructor:
export class VW_MyData {
public RawColumn: string;
public TransformedColumn: string;
public constructor(init?: Partial<VW_MyData>) {
Object.assign(this, init);
this.TransformedColumn = this.transform(this.RawColumn);
}
protected transform(input: string): string {
return `Transformation of ${input}!`;
}
}
This allows me to perform transformations, validations, and whatever else on all my data coming in to TypeScript. Hopefully it provides some insight for someone.
Eclipse 3.4 has a Favourites section under Window->Preferences->Java->Editor->Content Assist
If you use org.junit.Assert
a lot, you might find some value to adding it there.
I had the same problem, I succeeded by adding:
new \SoapClient(URI WSDL OR NULL if non-WSDL mode, [
'cache_wsdl' => WSDL_CACHE_NONE,
'proxy_host' => 'URL PROXY',
'proxy_port' => 'PORT PROXY'
]);
Hope this help :)
I did
msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)
else
msgbox "Closing..."
The catch all for me is taking an object, encoding it, and then passing the string into a javascript script
tag. To do this you have to do some replacements.
First replace every \
with a double slash \\
and then every quote"
with a \"
.
$payload = json_encode($payload);
$payload = preg_replace("_\\\_", "\\\\\\", $payload);
$payload = preg_replace("/\"/", "\\\"", $payload);
return View::make('pages.javascript')
->with('payload', $payload)
Then in the blade template
@if(isset($payload))
<script>
window.__payload = JSON.parse("{!!$payload!!}");
</script>
@endif
This basically allows you to take an object on the php side, and then have an object on the javascript side.
Try this
String str="10,692,467,440,017.120".replaceAll(",","");
BigDecimal bd=new BigDecimal(str);
This link has more information:
https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
So are you trying to grep through older versions of the code looking to see where something last exists?
If I were doing this, I would probably use git bisect. Using bisect, you can specify a known good version, a known bad version, and a simple script that does a check to see if the version is good or bad (in this case a grep to see if the code you are looking for is present). Running this will find when the code was removed.
I believe you need quotes around the model
:
JSON.stringify({ "model": source })
The data containing the date column can be read by using the below code:
data = pd.csv(file_path,parse_dates=[date_column])
Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time()
like:
pd.date_time(data[date_column], format = '%d/%m/%y')
to change the format of date as per the requirement.
You can also use the following command:
pylint --disable=C0321 test.py
My Pylint version is 0.25.1.
This can be done using HTML5's placeHolder or using JavaScript. Checkout this post.
If the keystore is for tomcat then, after creating the keystore with the above answers, you must add a final step to create the "tomcat" alias for the key:
keytool -changealias -alias "1" -destalias "tomcat" -keystore keystore-file.jks
You can check the result with:
keytool -list -keystore keystore-file.jks -v
IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards
is AFTER the animation declaration or it will not work...
animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;
vs
animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
I would make use of the Environment.NewLine property.
Something like:
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();
Or
StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();
If you wish to have a new line after each append, you can have a look at Ben Voigt's answer.
Try this:
table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());
This will group the table by Text
and use the first row from each groups resulting in rows where Text
is distinct.
My version is a simple fast encoder (decoder) of Base64 for C++Builder.
// ---------------------------------------------------------------------------
UnicodeString __fastcall TExample::Base64Encode(void *data, int length)
{
if (length <= 0)
return L"";
static const char set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char *in = (unsigned char*)data;
char *pos, *out = pos = new char[((length - 1) / 3 + 1) << 2];
while ((length -= 3) >= 0)
{
pos[0] = set[in[0] >> 2];
pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
pos[2] = set[((in[1] & 0x0F) << 2) | (in[2] >> 6)];
pos[3] = set[in[2] & 0x3F];
pos += 4;
in += 3;
};
if ((length & 2) != 0)
{
pos[0] = set[in[0] >> 2];
if ((length & 1) != 0)
{
pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
pos[2] = set[(in[1] & 0x0F) << 2];
}
else
{
pos[1] = set[(in[0] & 0x03) << 4];
pos[2] = '=';
};
pos[3] = '=';
pos += 4;
};
UnicodeString code = UnicodeString(out, pos - out);
delete[] out;
return code;
};
// ---------------------------------------------------------------------------
int __fastcall TExample::Base64Decode(const UnicodeString &code, unsigned char **data)
{
int length;
if (((length = code.Length()) == 0) || ((length & 3) != 0))
return 0;
wchar_t *str = code.c_str();
unsigned char *pos, *out = pos = new unsigned char[(length >> 2) * 3];
while (*str != 0)
{
length = -1;
int shift = 18, bits = 0;
do
{
wchar_t s = str[++length];
if ((s >= L'A') && (s <= L'Z'))
bits |= (s - L'A') << shift;
else if ((s >= L'a') && (s <= L'z'))
bits |= (s - (L'a' - 26)) << shift;
else if (((s >= L'0') && (s <= L'9')))
bits |= (s - (L'0' - 52)) << shift;
else if (s == L'+')
bits |= 62 << shift;
else if (s == L'/')
bits |= 63 << shift;
else if (s == L'=')
{
length--;
break;
}
else
{
delete[] out;
return 0;
};
}
while ((shift -= 6) >= 0);
pos[0] = bits >> 16;
pos[1] = bits >> 8;
pos[2] = bits;
pos += length;
str += 4;
};
*data = out;
return pos - out;
};
//---------------------------------------------------------------------------
Install setuptools
and try again.
try command:
sudo apt-get install -y python-setuptools
If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):
For Xpath:
http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html
I was facing the same issue. After researching too much on Google and StackOverflow. I found a solution very simple
First, you need to set environment like this
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=example44
MAIL_ENCRYPTION=tls
[email protected]
you have to change your Gmail address and password
Now you have to on less secure apps by following this link https://myaccount.google.com/lesssecureapps
You could use the ready to use Url Rewrite Filter with a rule like this one:
<rule>
<from>^/Check_License/Dir_My_App/Dir_ABC/My_Obj_([0-9]+)$</from>
<to>/Check_License?Contact_Id=My_Obj_$1</to>
</rule>
Check the Examples for more... examples.
Simple method:
public boolean isBlank(String value) {
return (value == null || value.equals("") || value.equals("null") || value.trim().equals(""));
}
public boolean isOnlyNumber(String value) {
boolean ret = false;
if (!isBlank(value)) {
ret = value.matches("^[0-9]+$");
}
return ret;
}
It would be more correct to say that stdin
, stdout
, and stderr
are "I/O streams" rather
than files. As you've noticed, these entities do not live in the filesystem. But the
Unix philosophy, as far as I/O is concerned, is "everything is a file". In practice,
that really means that you can use the same library functions and interfaces (printf
,
scanf
, read
, write
, select
, etc.) without worrying about whether the I/O stream
is connected to a keyboard, a disk file, a socket, a pipe, or some other I/O abstraction.
Most programs need to read input, write output, and log errors, so stdin
, stdout
,
and stderr
are predefined for you, as a programming convenience. This is only
a convention, and is not enforced by the operating system.
echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER@$varRemoteHost
echo \"$varCommand\" | sudo bash
In my case the sub domain name causes the problem. Here are details
I used app_development.something.com
, here underscore(_
) sub domain is creating CORS error. After changing app_development
to app-development
it works fine.
The top voted answer is right and simplest. However, sometimes you may find that not working for some font, but working for others.(Which problem I just came across when dealing with Chinese.)
Solution is do not use "WRAP_CONTENT" only for your TextView, cause there is no extra space for drawing the line. You may set fixed height to your TextView, or use android:paddingVertical with WRAP_CONTENT.
If you know up front the data that could be populated, you can use the ClientScriptManager to resolve this issue. I had this issue when dynamically populating a drop down box using javascript on a previous user selection.
Here is some example code for overriding the render method (in VB and C#) and declaring a potential value for the dropdownlist ddCar.
In VB:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim ClientScript As ClientScriptManager = Page.ClientScript
ClientScript.RegisterForEventValidation("ddCar", "Mercedes")
MyBase.Render(writer)
End Sub
or a slight variation in C# could be:
protected override void Render(HtmlTextWriter writer)
{
Page.ClientScript.RegisterForEventValidation("ddCar", "Mercedes");
base.Render(writer);
}
For newbies: This should go in the code behind file (.vb or .cs) or if used in the aspx file you can wrap in <script>
tags.
Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.
Here is how one might go about connecting to a device:
# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0: Type: BR/EDR Bus: USB
BD Address: AA:BB:CC:DD:EE:FF ACL MTU: 1021:8 SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
00:11:22:33:44:55 My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup
This would establish a serial connection to the device.
This need is exactly why createInsecureRfcommSocketToServiceRecord()
was added to BluetoothDevice
starting in Android 2.3.3 (API Level 10) (SDK Docs)...before that there was no SDK support for this. It was designed to allow Android to connect to devices without user interfaces for entering a PIN code (like an embedded device), but it just as usable for setting up a connection between two devices without user PIN entry.
The corollary method listenUsingInsecureRfcommWithServiceRecord()
in BluetoothAdapter
is used to accept these types of connections. It's not a security breach because the methods must be used as a pair. You cannot use this to simply attempt to pair with any old Bluetooth device.
You can also do short range communications over NFC, but that hardware is less prominent on Android devices. Definitely pick one, and don't try to create a solution that uses both.
Hope that Helps!
P.S. There are also ways to do this on many devices prior to 2.3 using reflection, because the code did exist...but I wouldn't necessarily recommend this for mass-distributed production applications. See this StackOverflow.
try ps -n
in a linux terminal. This will show:
1.All processes RUNNING, their command line and their PIDs
Afterwards you will know which process to kill
this works for me because it works fine in ie8.
$('#iframe').contents().find("html").html();
but if you like to use javascript aside for jquery you may use like this
var iframe = document.getElementById('iframecontent');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var val_1 = innerDoc.getElementById('value_1').value;
You can use a sealed abstract class instead of the enumeration, for example:
sealed abstract class Constraint(val name: String, val verifier: Int => Boolean)
case object NotTooBig extends Constraint("NotTooBig", (_ < 1000))
case object NonZero extends Constraint("NonZero", (_ != 0))
case class NotEquals(x: Int) extends Constraint("NotEquals " + x, (_ != x))
object Main {
def eval(ctrs: Seq[Constraint])(x: Int): Boolean =
(true /: ctrs){ case (accum, ctr) => accum && ctr.verifier(x) }
def main(args: Array[String]) {
val ctrs = NotTooBig :: NotEquals(5) :: Nil
val evaluate = eval(ctrs) _
println(evaluate(3000))
println(evaluate(3))
println(evaluate(5))
}
}
For Ubuntu on HP (Intel processors),
Press F10 on booting the system, it will enter into system setup mode.
You will find tabs on top like Main, Security, Advanced.
Go into Advanced >> and click on System settings.
Mark the check boxes on Enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).
Back to Main, click on save changes and exit.
When you have the expression:
a % b = c
It really means there exists an integer n
that makes c
as small as possible, but non-negative.
a - n*b = c
By hand, you can just subtract 2
(or add 2
if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
Also, 3.14 % 2 * pi
is interpreted as (3.14 % 2) * pi
. I'm not sure if you meant to write 3.14 % (2 * pi)
(in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
You must to download MySQLConnection NET from here.
Then you need add MySql.Data.DLL
to MSVisualStudio like this:
C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
If you want to know more visit: enter link description here
To use in the code you must import the library:
using MySql.Data.MySqlClient;
An example with connectio to Mysql database (NO SSL MODE) by means of Click event:
using System;
using System.Windows;
using MySql.Data.MySqlClient;
namespace Deportes_WPF
{
public partial class Login : Window
{
private MySqlConnection connection;
private string server;
private string database;
private string user;
private string password;
private string port;
private string connectionString;
private string sslM;
public Login()
{
InitializeComponent();
server = "server_name";
database = "database_name";
user = "user_id";
password = "password";
port = "3306";
sslM = "none";
connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);
connection = new MySqlConnection(connectionString);
}
private void conexion()
{
try
{
connection.Open();
MessageBox.Show("successful connection");
connection.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message + connectionString);
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
conexion();
}
}
}
I had the same issue with SQL Server 2014 (Management Studio could not see the folder in which the backup file resided, when attempting to locate it for a Restore operation). This thread held the answer that solved my problem. Quote:
The SQL Server service account can be found by Start->Control Panel->Administrative Tools->Services. Double-click on the SQL Server service->Log On tab. You'll either be using the "Local System account" or "This account" to define a specific account. If you are using the Local System account, you won't be able to reference backups that are not local to the server. If, instead, you have defined the account to use, this is the account that needs to have access to the backup file location. Your ability to access the backups using your personal logon is irrelevant; it is the SQL Server account that is used, even though you are initiating the backup. Your IT people should be able to determine what rights are granted to each account.
Hope that helps someone.
This will work also:
for i in {0..9}{0..9}{0..9}{0..9}
do
echo "$i"
done
I'm using a PUTTYgen file with psftp, and I encountered this problem on my Windows Server when we were required to create new keys for a client. The private_key_name.ppk file and the open_ssh.txt file must be in the same directory for the connection to work.
I believe this can solve app.use(express.json());
You need to use AND statement in your formula
=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")
And if both conditions are met, return 1.
You could also add more conditions in your AND statement.
Always nice to have:
Dim myPath As String
Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
myPath = Application.ActiveWorkbook.FullName
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
First and major difference between trustStore and keyStore is that trustStore is used by TrustManager to determine whether remote connection should be trusted, keyStore is used from KeyManager deciding which authentication credentials should be sent to the remote host for authentication during SSL handshake.
Another difference is that keyStore theoretically contains private keys required only if you are running a Server in SSL connection or you have enabled client authentication on server side and on the other hand trustStore stores public key or certificates from CA (Certificate Authorities) which are used to trust remote party or SSL connection.
In fact you can store in the same file both private and public keys, given that the the tool to manage those file is the same (keytool), so you could use a single file for both the purposes, but you probably should not.
At least on my Mac OSX the default keyStore is ${user.home}/.keystore
, and the default trustStore is /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts
.
If you want to override them you should add the JVM parameters
-Djavax.net.ssl.keyStore /path/to/keyStore
or
-Djavax.net.ssl.trustStore /path/to/trustStore
. You might also
need to set the keyStore password in case of
java.security.UnrecoverableKeyException: Password must not be
null
, using the parameter
-Djavax.net.ssl.trustStorePassword=password
or -Djavax.net.ssl.trustStorePassword=password
Main Source:
http://javarevisited.blogspot.co.uk/2012/09/difference-between-truststore-vs-keyStore-Java-SSL.html
Though linkedHashMap doesn't provide any method to get first, last or any specific object.
But its pretty trivial to get :
Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();
Set<Integer> al = orderMap.keySet();
now using iterator on al
object ; you can get any object.
See the Wikipedia page on ANSI escapes for the full collection of sequences, including the colors.
But for one simple example (Printing in red) in Java (as you tagged this as Java) do:
System.out.println("\u001B31;1mhello world!");
The 3 indicates change color, the first 1 indicates red (green would be 2) and the second 1 indicates do it in "bright" mode.
However, if you want to print to a GUI the easiest way is to use html:
JEditorPane pane = new new JEditorPane();
pane.setText("<html><font color=\"red\">hello world!</font></html>");
For more details on this sort of thing, see the Swing Tutorial. It is also possible by using styles in a JTextPane. Here is a helpful example of code to do this easily with a JTextPane (added from helpful comment).
JTextArea is a single coloured Text component, as described here. It can only display in one color. You can set the color for the whole JTextArea like this:
JTextArea area = new JTextArea("hello world");
area.setForeground(Color.red)
In Windows, if you want to move the npm or nodejs folder in disk C to another location, but it still makes sure node and npm works well, you can create symlink like this: Open Command Prompt:
mklink /D "your_location_want_to_create_symlink" "location_of_node_npm_file"
Example:
mklink /D "C:\Users\MyUser\AppData\Roaming\npm" "D:\Nodejs Data\npm"
Now you've created a symlink for npm folder, this symlink will refer to D:\Nodejs Data\npm
Everything will work well.
this is the solution to close menu when click on anchor then apply this line in list item
data-target="#sidenav-collapse-main" data-toggle="collapse"
the real example that work for me is below
<li class="nav-item" data-target="#sidenav-collapse-main" data-
toggle="collapse" >
<a class="nav-link" routerLinkActive="active" routerLink="/admin/users">
<i class="ni ni-single-02 text-orange"></i> Users
</a>
</li>
splice will remove array element(s) by index. Use grep, as in your example, to search and remove.
It all depends really, if you're using the DataGrid from the WPF Toolkit then there is a built in sort, even a multi-column sort which is very useful. Check more out here:
Alternatively, if you're using a different control that doesn't support sorting, i'd recommend the following methods:
Followed by:
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
One way to get this error in Eclipse :
A
in src/test/java
.B
in src/main/java
that uses class A
.Result : Eclipse will compile the code, but maven will give "Cannot find symbol".
Underlying cause : Eclipse is using a combined build path for the main and test trees. Unfortunately, it does not support using different build paths for different parts of an Eclipse project, which is what Maven requires.
Solution :
The best way is you should destroy the slick slider after reinitializing it.
function slickCarousel() {
$('.skills_section').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 1
});
}
function destroyCarousel() {
if ($('.skills_section').hasClass('slick-initialized')) {
$('.skills_section').slick('destroy');
}
}
$.ajax({
type: 'get',
url: '/public/index',
dataType: 'script',
data: data_send,
success: function() {
destroyCarousel()
slickCarousel();
}
});
You can create a single function that calls both of those, and then use it in the event.
function myFunction(){
pay();
cls();
}
And then, for the button:
<input id="btn" type="button" value="click" onclick="myFunction();"/>
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
There is a great solution for this problem ,You can use the Merge Keyword of Sql
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Product Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
You can check this before following, below is the sample
IF OBJECT_ID ('dbo.TargetTable') IS NOT NULL
DROP TABLE dbo.TargetTable
GO
CREATE TABLE dbo.TargetTable
(
Id INT NOT NULL,
Name VARCHAR (255) NOT NULL,
CONSTRAINT PK_TargetTable PRIMARY KEY (Id)
)
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unknown')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Mapping')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Update')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Message')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Switch')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('Unmatched')
GO
INSERT INTO dbo.TargetTable (Name)
VALUES ('ProductMessage')
GO
Merge MyTargetTable hba
USING (SELECT Id = 8, Name = 'Listing Message') temp
ON temp.Id = hba.Id
WHEN NOT matched THEN
INSERT (Id, Name) VALUES (temp.Id, temp.Name);
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
Using Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
Another way is to use an array as a type, e.g.:
Video[] videoArray = gson.fromJson(json, Video[].class);
This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:
List<Video> videoList = Arrays.asList(videoArray);
IMHO this is much more readable.
In Kotlin this looks like this:
Gson().fromJson(jsonString, Array<Video>::class.java)
To convert this array into List, just use .toList()
method
You can use ROW_NUMBER()
function to get what you want:
SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20
Per the deferred PEP 396 (Module Version Numbers), there is a proposed way to do this. It describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet:
3) When a module (or package) includes a version number, the version SHOULD be available in the
__version__
attribute.4) For modules which live inside a namespace package, the module SHOULD include the
__version__
attribute. The namespace package itself SHOULD NOT include its own__version__
attribute.5) The
__version__
attribute's value SHOULD be a string.
If they are unsorted, you can't do much but look at each one, which is O(N), and when you're done you'll know the minimum.
Pseudo-code:
small = <biggest value> // such as std::numerical_limits<int>::max
for each element in array:
if (element < small)
small = element
A better way reminded by Ben to me was to just initialize small with the first element:
small = element[0]
for each element in array, starting from 1 (not 0):
if (element < small)
small = element
The above is wrapped in the algorithm header as std::min_element.
If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.
That's as good as it gets with arrays.
Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?
It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/
I've created the boot entry that disables HyperV and it's working
I had the same requirement in my development so I did research on this. I have read many articles and tried many solutions during last two days like jQuery.tabNext() plugin.
I had some trouble with IE11 (all IE version has this bug). When an input text followed by non text input the selection was not cleared. So I have created my own tabNext() method based on @Sarfraz solution suggestion. I was also thinking on how it should behave (only circle in the current form or maybe through the full document). I still did not take care of the tabindex property mostly because I am using it occasionally. But I will not forget it.
In order to my contribution can be useful for everybody easily I have created jsfiddle example here https://jsfiddle.net/mkrivan/hohx4nes/
I include also the JavaScript part of the example here:
function clearSelection() {
if (document.getSelection) { // for all new browsers (IE9+, Chrome, Firefox)
document.getSelection().removeAllRanges();
document.getSelection().addRange(document.createRange());
console.log("document.getSelection");
} else if (window.getSelection) { // equals with the document.getSelection (MSDN info)
if (window.getSelection().removeAllRanges) { // for all new browsers (IE9+, Chrome, Firefox)
window.getSelection().removeAllRanges();
window.getSelection().addRange(document.createRange());
console.log("window.getSelection.removeAllRanges");
} else if (window.getSelection().empty) { // maybe for old Chrome
window.getSelection().empty();
console.log("window.getSelection.empty");
}
} else if (document.selection) { // IE8- deprecated
document.selection.empty();
console.log("document.selection.empty");
}
}
function focusNextInputElement(node) { // instead of jQuery.tabNext();
// TODO: take the tabindex into account if defined
if (node !== null) {
// stay in the current form
var inputs = $(node).parents("form").eq(0).find(":input:visible:not([disabled]):not([readonly])");
// if you want through the full document (as TAB key is working)
// var inputs = $(document).find(":input:visible:not([disabled]):not([readonly])");
var idx = inputs.index(node) + 1; // next input element index
if (idx === inputs.length) { // at the end start with the first one
idx = 0;
}
var nextInputElement = inputs[idx];
nextInputElement.focus(); // handles submit buttons
try { // if next input element does not support select()
nextInputElement.select();
} catch (e) {
}
}
}
function tabNext() {
var currentActiveNode = document.activeElement;
clearSelection();
focusNextInputElement(currentActiveNode);
}
function stopReturnKey(e) {
var e = (e) ? e : ((event) ? event : null);
if (e !== null) {
var node = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : null);
if (node !== null) {
var requiredNode = $(node).is(':input')
// && !$(node).is(':input[button]')
// && !$(node).is(':input[type="submit"]')
&& !$(node).is('textarea');
// console.log('event key code ' + e.keyCode + '; required node ' + requiredNode);
if ((e.keyCode === 13) && requiredNode) {
try {
tabNext();
// clearSelection();
// focusNextInputElement(node);
// jQuery.tabNext();
console.log("success");
} catch (e) {
console.log("error");
}
return false;
}
}
}
}
document.onkeydown = stopReturnKey;
I left commented rows as well so my thinking can be followed.
In WebStart and the new 6u10 PlugIn you can use the FileOpenService, even without security permissions. For obvious reasons, you only get the file contents, not the file path.
It might be easier with vlookup. Try this:
=IFERROR(VLOOKUP(D2,G:H,2,0),"")
The IFERROR()
is for no matches, so that it throws ""
in such cases.
VLOOKUP
's first parameter is the value to 'look for' in the reference table, which is column G and H.
VLOOKUP
will thus look for D2
in column G and return the value in the column index 2
(column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.
The last parameter is 0
(or equivalently FALSE
) to mean an exact match. That's what you need as opposed to approximate match.
This Statement used in Angular2 Beta version.....
Hereafter use let instead of #
let keyword is used to declare local variable
Converting anything to a string should either 1) allocate the resultant string or 2) pass in a char *
destination and size. Sample code below:
Both work for all int
including INT_MIN
. They provide a consistent output unlike snprintf()
which depends on the current locale.
Method 1: Returns NULL
on out-of-memory.
#define INT_DECIMAL_STRING_SIZE(int_type) ((CHAR_BIT*sizeof(int_type)-1)*10/33+3)
char *int_to_string_alloc(int x) {
int i = x;
char buf[INT_DECIMAL_STRING_SIZE(int)];
char *p = &buf[sizeof buf - 1];
*p = '\0';
if (i >= 0) {
i = -i;
}
do {
p--;
*p = (char) ('0' - i % 10);
i /= 10;
} while (i);
if (x < 0) {
p--;
*p = '-';
}
size_t len = (size_t) (&buf[sizeof buf] - p);
char *s = malloc(len);
if (s) {
memcpy(s, p, len);
}
return s;
}
Method 2: It returns NULL
if the buffer was too small.
static char *int_to_string_helper(char *dest, size_t n, int x) {
if (n == 0) {
return NULL;
}
if (x <= -10) {
dest = int_to_string_helper(dest, n - 1, x / 10);
if (dest == NULL) return NULL;
}
*dest = (char) ('0' - x % 10);
return dest + 1;
}
char *int_to_string(char *dest, size_t n, int x) {
char *p = dest;
if (n == 0) {
return NULL;
}
n--;
if (x < 0) {
if (n == 0) return NULL;
n--;
*p++ = '-';
} else {
x = -x;
}
p = int_to_string_helper(p, n, x);
if (p == NULL) return NULL;
*p = 0;
return dest;
}
[Edit] as request by @Alter Mann
(CHAR_BIT*sizeof(int_type)-1)*10/33+3
is at least the maximum number of char
needed to encode the some signed integer type as a string consisting of an optional negative sign, digits, and a null character..
The number of non-sign bits in a signed integer is no more than CHAR_BIT*sizeof(int_type)-1
. A base-10 representation of a n
-bit binary number takes up to n*log10(2) + 1
digits. 10/33
is slightly more than log10(2)
. +1 for the sign char
and +1 for the null character. Other fractions could be used like 28/93.
Method 3: If one wants to live on the edge and buffer overflow is not a concern, a simple C99 or later solution follows which handles all int
.
#include <limits.h>
#include <stdio.h>
static char *itoa_simple_helper(char *dest, int i) {
if (i <= -10) {
dest = itoa_simple_helper(dest, i/10);
}
*dest++ = '0' - i%10;
return dest;
}
char *itoa_simple(char *dest, int i) {
char *s = dest;
if (i < 0) {
*s++ = '-';
} else {
i = -i;
}
*itoa_simple_helper(s, i) = '\0';
return dest;
}
int main() {
char s[100];
puts(itoa_simple(s, 0));
puts(itoa_simple(s, 1));
puts(itoa_simple(s, -1));
puts(itoa_simple(s, 12345));
puts(itoa_simple(s, INT_MAX-1));
puts(itoa_simple(s, INT_MAX));
puts(itoa_simple(s, INT_MIN+1));
puts(itoa_simple(s, INT_MIN));
}
Sample output
0
1
-1
12345
2147483646
2147483647
-2147483647
-2147483648
destroy
or something similar may come to the CLI, but it is not a primary focus at this time. So you will need to do this manually.
Delete the component directory (assuming you didn't use --flat
) and then remove it from the NgModule
in which it is declared.
If you are unsure of what to do, I suggest you have a "clean" app meaning no current git
changes. Then generate a component and see what is changed in the repo so you can backtrack from there what you will need to do to delete a component.
If you're just experimenting about what you want to generate, you can use the --dry-run
flag to not produce any files on disk, just see the updated file list.
Just found this answer from another link,
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
I worked it around through this "hiding" div ...
<div STYLE="position:absolute;display:none;"><INPUT type='file' id='file1' name='files[]'></div>
This is an old question but the topic is very important and always current. In case anyone wants to go beyond simple getters/setters i have wrote an article about superpowered properties in python with support for slots, observability and reduced boilerplate code.
from objects import properties, self_properties
class Car:
with properties(locals(), 'meta') as meta:
@meta.prop(read_only=True)
def brand(self) -> str:
"""Brand"""
@meta.prop(read_only=True)
def max_speed(self) -> float:
"""Maximum car speed"""
@meta.prop(listener='_on_acceleration')
def speed(self) -> float:
"""Speed of the car"""
return 0 # Default stopped
@meta.prop(listener='_on_off_listener')
def on(self) -> bool:
"""Engine state"""
return False
def __init__(self, brand: str, max_speed: float = 200):
self_properties(self, locals())
def _on_off_listener(self, prop, old, on):
if on:
print(f"{self.brand} Turned on, Runnnnnn")
else:
self._speed = 0
print(f"{self.brand} Turned off.")
def _on_acceleration(self, prop, old, speed):
if self.on:
if speed > self.max_speed:
print(f"{self.brand} {speed}km/h Bang! Engine exploded!")
self.on = False
else:
print(f"{self.brand} New speed: {speed}km/h")
else:
print(f"{self.brand} Car is off, no speed change")
This class can be used like this:
mycar = Car('Ford')
# Car is turned off
for speed in range(0, 300, 50):
mycar.speed = speed
# Car is turned on
mycar.on = True
for speed in range(0, 350, 50):
mycar.speed = speed
This code will produce the following output:
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Car is off, no speed change
Ford Turned on, Runnnnnn
Ford New speed: 0km/h
Ford New speed: 50km/h
Ford New speed: 100km/h
Ford New speed: 150km/h
Ford New speed: 200km/h
Ford 250km/h Bang! Engine exploded!
Ford Turned off.
Ford Car is off, no speed change
More info about how and why here: https://mnesarco.github.io/blog/2020/07/23/python-metaprogramming-properties-on-steroids
Basically sudo expects, an executable (command) to follow & you are providing with a .
Hence the error.
Try this way $ sudo setup.sh
In Windows 10 you might also want to delete Windows Explorer's override for file extension association:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice
in addition to the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
change mentioned in other answers.
This worked for me. Hope it helps someone. :)
SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
this.resultsList.remove((int) info.id);
adapter.notifyDataSetChanged();
Although my experience with DFD diagrams is limited I can tell you that a DFD shows you how the data moves (flows) between the various modules. Furthermore a DFD can be partitioned in levels, that is in the Initial Level you see the system (say, a System to Rent a Movie) as a whole (called the Context Level). That level could be broken down into another Level that contains activities (say, rent a movie, return a movie) and how the data flows into those activities (could be a name, number of days, whatever). Now you can make a sublevel for each activity detailing the many tasks or scenarios of those activities. And so on, so forth. Remember that the data is always passing between levels.
Now as for the flowchart just remember that a flowchart describes an algorithm!
Here's another straightforward alternative.
> which(strsplit(string, "")[[1]]=="2")
[1] 4 24
The functions* quit()
, exit()
, and sys.exit()
function in the same way: they raise the SystemExit
exception. So there is no real difference, except that sys.exit()
is always available but exit()
and quit()
are only available if the site
module is imported.
The os._exit()
function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork()
call.
Use exit()
or quit()
in the REPL.
Use sys.exit()
in scripts, or raise SystemExit()
if you prefer.
Use os._exit()
for child processes to exit after a call to os.fork()
.
All of these can be called without arguments, or you can specify the exit status, e.g., exit(1)
or raise SystemExit(1)
to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256)
on many systems this will get truncated and your process will actually exit with status 0.
* Actually, quit()
and exit()
are callable instance objects, but I think it's okay to call them functions.
Please use the below code. It will help you to get the incoming number with other call details.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
private static final int MISSED_CALL_TYPE = 0;
private TextView txtcall;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtcall = (TextView) findViewById(R.id.call);
StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
}
managedCursor.close();
txtcall.setText(sb);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and in your manifest request for following permissions:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_LOGS"/>
I couln't find the SOAP
section in phpinfo()
so I had to install it.
For information the SOAP
extension requires the libxml
PHP extension. This means that passing in --enable-libxml
is also required according to http://php.net/manual/en/soap.requirements.php
From WHM panel
Install SOAP 0.13.0
WARNING: "pear/HTTP_Request" is deprecated in favor of "pear/HTTP_Request2"
install ok: channel://pear.php.net/SOAP-0.13.0
Install HTTP_Request2 (optional)
install ok: channel://pear.php.net/HTTP_Request2
Restart Services » HTTP Server (Apache)
From shell command
1.pear install SOAP
2.reboot
I ran into this problem: I'd get the error
C:\projects\Android\android-sdk-windows-1.5_r1\tools\lib>ddms
02:03:07 E/ddms: shutting down due to uncaught exception
02:03:07 E/ddms: no swt-win32-3550 or swt-win32 in swt.library.path, java.library.path or the jar file
java.lang.UnsatisfiedLinkError: no swt-win32-3550 or swt-win32 in swt.library.path, java.library.path or the j
ar file
at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
at org.eclipse.swt.internal.Library.loadLibrary(Unknown Source)
at org.eclipse.swt.internal.C.<clinit>(Unknown Source)
at org.eclipse.swt.graphics.FontData.<init>(Unknown Source)
at com.android.ddms.PrefsDialog.setDefaults(PrefsDialog.java:221)
at com.android.ddms.PrefsDialog.init(PrefsDialog.java:150)
at com.android.ddms.Main.main(Main.java:74)
I got this solved by copying the swt file from eclipse into the tools
directory. If you search in the directory you have Eclipse installed there is an SWT dll, named something like swt-win32-<4-digits>.dll
(mine was named swt-win32-3740.dll
): I copied that into the tools directory, and everything worked after that.
In short
window.onload
is not supported by IE 6-8document.onload
is not supported by any modern browser (event is never fired)window.onload = () => console.log('window.onload works'); // fired
document.onload = () => console.log('document.onload works'); // not fired
_x000D_
My first idea was to do this:
chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"
for char in chars:
count = check_string.count(char)
if count > 1:
print char, count
This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:
count = {}
for s in check_string:
if s in count:
count[s] += 1
else:
count[s] = 1
for key in count:
if count[key] > 1:
print key, count[key]
This ensures that you only go through the string once, instead of 26 times.
Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.
Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.
Try using this command to allow a port
sudo ufw allow 1701
To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:
nc -l 1701
Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.
Try to close all connections to your database first:
use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER
Taken from here
class Program
{
static void Main(string[] args)
{
String unicodeString =
"This Unicode string contains two characters " +
"with codes outside the traditional ASCII code range, " +
"Pi (\u03a0) and Sigma (\u03a3).";
Console.WriteLine("Original string:");
Console.WriteLine(unicodeString);
UnicodeEncoding unicodeEncoding = new UnicodeEncoding();
byte[] utf16Bytes = unicodeEncoding.GetBytes(unicodeString);
char[] chars = unicodeEncoding.GetChars(utf16Bytes, 2, utf16Bytes.Length - 2);
string s = new string(chars);
Console.WriteLine();
Console.WriteLine("Char Array:");
foreach (char c in chars) Console.Write(c);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("String from Char Array:");
Console.WriteLine(s);
Console.ReadKey();
}
}
Starting with MongoDB v3.4 (released in 2016), the $lookup
aggregation pipeline stage can also work directly with an array. There is no need for $unwind
any more.
This was tracked in SERVER-22881.
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
os provides you with a lot of these capabilities:
import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in) #gets you a list of all files and directories under dir_in
the listdir will throw an exception if the input path is invalid.
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
If you choose not to extend from Controller
classes, you can create new ContentResult
:
[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
Return string content with media type text/html
:
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<div>Hello World</div>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
I wrote a pypi/github package for this question because I needed a solution as well.
https://github.com/bucknerns/logtail
Install:
pip install logtail
Usage: tails changed files
logtail <log dir> [<glob match: default=*.log>]
Usage2: Opens latest changed file in editor
editlatest <log dir> [<glob match: default=*.log>]
In Workbook events:
Private Sub Workbook_Open()
RunEveryTwoMinutes
End Sub
In a module:
Sub RunEveryTwoMinutes()
//Add code here for whatever you want to happen
Application.OnTime Now + TimeValue("00:02:00"), "RunEveryTwoMinutes"
End Sub
If you only want the first piece of code to execute after the workbook opens then just add a delay of 2 minutes into the Workbook_Open
event
getElementsByClassName
is a function on the DOM Document. It is neither a jQuery nor a jqLite function.
Don't add the period before the class name when using it:
var result = document.getElementsByClassName("multi-files");
Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):
var wrappedResult = angular.element(result);
If you want to select from the element
in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0]
instead of element
:
link: function (scope, element, attrs) {
var elementResult = element[0].getElementsByClassName('multi-files');
}
Alternatively you can use the document.querySelector
function (need the period here if selecting by class):
var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);
When you loop in an array like you did, your for variable(in this example i
) is current element of your array.
For example if your ar
is [1,5,10]
, the i
value in each iteration is 1
, 5
, and 10
.
And because your array length is 3, the maximum index you can use is 2. so when i = 5
you get IndexError
.
You should change your code into something like this:
for i in ar:
theSum = theSum + i
Or if you want to use indexes, you should create a range from 0 ro array length - 1
.
for i in range(len(ar)):
theSum = theSum + ar[i]
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
after that you can do like:
var new_countries = countries.join(',')
after:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: new_countries,
...
This thing work as JSON string format.
You can use Process.GetProcesses()
to get the currently running processes, then Process.Kill()
to kill a process.
One big advantage of MATLAB over R is the quality of MATLAB documentation. R, being open source, suffers in this respect, a feature common to many open source projects.
R is, however, a very useful environment and language. It is widely used in the bioinformatics community and has many packages useful in this domain.
An alternative to R is Octave (http://www.gnu.org/software/octave/) which is very similar to MATLAB, it can run MATLAB scripts.
If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.
Some ways you can alter content to make a table more narrow:
white-space: nowrap
on any of the content (or the old nowrap
attribute,
, a nobr
element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down.If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.
Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker
It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.
The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
For symfony 4 users:
$query = $request->query->get('query');
//Inside the folder,
svn cleanup
svn update
//If are viewing any conflicts,
svn revert --depth infinity conflicted_filename
svn update conflicted_filename
svn update
I don't believe there's a way to query the mouse position, but you can use a mousemove
handler that just stores the information away, so you can query the stored information.
jQuery(function($) {
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
// ELSEWHERE, your code that needs to know the mouse position without an event
if (currentMousePos.x < 10) {
// ....
}
});
But almost all code, other than setTimeout
code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...
you just need to use word boundary (\b
) instead of ^
and $
:
\bgarp\b
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
An object technically is a dictionary.
var myMappings = {
mykey1: 'myValue',
mykey2: 'myValue'
};
var myVal = myMappings['myKey1'];
alert(myVal); // myValue
You can even loop through one.
for(var key in myMappings) {
var myVal = myMappings[key];
alert(myVal);
}
There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:
myMappings['mykey3'] = 'my value';
And ContainsKey:
if (myMappings.hasOwnProperty('myKey3')) {
alert('key already exists!');
}
I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/