You are looking for CHAR_LENGTH()
to get the number of characters in a string.
For multi-byte charsets LENGTH()
will give you the number of bytes the string occupies, while CHAR_LENGTH()
will return the number of characters.
Show this "long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text long text "
to
long text long text long ...
function cutString(text){
var wordsToCut = 5;
var wordsArray = text.split(" ");
if(wordsArray.length>wordsToCut){
var strShort = "";
for(i = 0; i < wordsToCut; i++){
strShort += wordsArray[i] + " ";
}
return strShort+"...";
}else{
return text;
}
};
SELECT MAX(LEN(Desc)) as MaxLen FROM table
You have to figure out if the string is ascii encoded or encoded with a multi-byte format.
In the former case, you can just use strlen
.
In the latter case you need to find the number of bytes per character.
the strlen documentation gives an example of how to do it : http://www.php.net/manual/en/function.strlen.php#72274
You can try RuneCountInString
from the utf8 package.
returns the number of runes in p
that, as illustrated in this script: the length of "World" might be 6 (when written in Chinese: "??"), but its rune count is 2:
package main
import "fmt"
import "unicode/utf8"
func main() {
fmt.Println("Hello, ??", len("??"), utf8.RuneCountInString("??"))
}
Phrozen adds in the comments:
Actually you can do len()
over runes by just type casting.
len([]rune("??"))
will print 2
. At leats in Go 1.3.
And with CL 108985 (May 2018, for Go 1.11), len([]rune(string))
is now optimized. (Fixes issue 24923)
The compiler detects len([]rune(string))
pattern automatically, and replaces it with for r := range s call.
Adds a new runtime function to count runes in a string. Modifies the compiler to detect the pattern
len([]rune(string))
and replaces it with the new rune counting runtime function.RuneCount/lenruneslice/ASCII 27.8ns ± 2% 14.5ns ± 3% -47.70% RuneCount/lenruneslice/Japanese 126ns ± 2% 60 ns ± 2% -52.03% RuneCount/lenruneslice/MixedLength 104ns ± 2% 50 ns ± 1% -51.71%
Stefan Steiger points to the blog post "Text normalization in Go"
What is a character?
As was mentioned in the strings blog post, characters can span multiple runes.
For example, an 'e
' and '?´?´' (acute "\u0301") can combine to form 'é' ("e\u0301
" in NFD). Together these two runes are one character.The definition of a character may vary depending on the application.
For normalization we will define it as:
- a sequence of runes that starts with a starter,
- a rune that does not modify or combine backwards with any other rune,
- followed by possibly empty sequence of non-starters, that is, runes that do (typically accents).
The normalization algorithm processes one character at at time.
Using that package and its Iter
type, the actual number of "character" would be:
package main
import "fmt"
import "golang.org/x/text/unicode/norm"
func main() {
var ia norm.Iter
ia.InitString(norm.NFKD, "école")
nc := 0
for !ia.Done() {
nc = nc + 1
ia.Next()
}
fmt.Printf("Number of chars: %d\n", nc)
}
Here, this uses the Unicode Normalization form NFKD "Compatibility Decomposition"
Oliver's answer points to UNICODE TEXT SEGMENTATION as the only way to reliably determining default boundaries between certain significant text elements: user-perceived characters, words, and sentences.
For that, you need an external library like rivo/uniseg, which does Unicode Text Segmentation.
That will actually count "grapheme cluster", where multiple code points may be combined into one user-perceived character.
package uniseg
import (
"fmt"
"github.com/rivo/uniseg"
)
func main() {
gr := uniseg.NewGraphemes("!")
for gr.Next() {
fmt.Printf("%x ", gr.Runes())
}
// Output: [1f44d 1f3fc] [21]
}
Two graphemes, even though there are three runes (Unicode code points).
You can see other examples in "How to manipulate strings in GO to reverse them?"
? alone is one grapheme, but, from unicode to code points converter, 4 runes:
Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.
string = input("Enter the string : ")
print("The string length is : ",len(string))
OUTPUT : -
Enter the string : viral
The string length is : 5
And now for something completely different. The following assumes arial font, and makes a wild guess based on a linear interpolation of character vs width.
// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.
// see https://p2p.wrox.com/access/32197-calculate-character-widths.html
static int picaSize(String s)
{
// the following characters are sorted by width in Arial font
String lookup = " .:,;'^`!|jl/\\i-()JfIt[]?{}sr*a\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW";
int result = 0;
for (int i = 0; i < s.length(); ++i)
{
int c = lookup.indexOf(s.charAt(i));
result += (c < 0 ? 60 : c) * 7 + 200;
}
return result;
}
Interesting, but perhaps not very practical.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
For MongoDB 3.6 and newer:
The $expr
operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP
operator to check the length of the string as follows:
db.usercollection.find({
"name": { "$exists": true },
"$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] }
})
For MongoDB 3.4 and newer:
You can also use the aggregation framework with the $redact
pipeline operator that allows you to proccess the logical condition with the $cond
operator and uses the special operations $$KEEP
to "keep" the document where the logical condition is true or $$PRUNE
to "remove" the document where the condition was false.
This operation is similar to having a $project
pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match
, except that $redact
uses a single pipeline stage which is more efficient.
As for the logical condition, there are String Aggregation Operators that you can use $strLenCP
operator to check the length of the string. If the length is $gt
a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.
Consider running the following aggregate operation which demonstrates the above concept:
db.usercollection.aggregate([
{ "$match": { "name": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$gt": [ { "$strLenCP": "$name" }, 40] },
"$$KEEP",
"$$PRUNE"
]
}
},
{ "$limit": 2 }
])
If using $where
, try your query without the enclosing brackets:
db.usercollection.find({$where: "this.name.length > 40"}).limit(2);
A better query would be to to check for the field's existence and then check the length:
db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2);
or:
db.usercollection.find({name: {$exists: true}, $where: "this.name.length >
40"}).limit(2);
MongoDB evaluates non-$where
query operations before $where
expressions and non-$where
query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where
will be much slower compared to that. It's recommended to use JavaScript expressions and the $where
operator as a last resort when you can't structure the data in any other way, or when you are dealing with a
small subset of data.
A different and faster approach that avoids the use of the $where
operator is the $regex
operator. Consider the following pattern which searches for
db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2);
Note - From the docs:
If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.
A regular expression is a “prefix expression” if it starts with a caret
(^)
or a left anchor(\A)
, followed by a string of simple symbols. For example, the regex/^abc.*/
will be optimized by matching only against the values from the index that start withabc
.Additionally, while
/^a/, /^a.*/,
and/^a.*$/
match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however,/^a.*/
, and/^a.*$/
are slower./^a/
can stop scanning after matching the prefix.
36, and the GUID will only use 0-9A-F (hexidecimal!).
12345678-1234-1234-1234-123456789012
That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.
You will need two more in length if you want to store the braces.
Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.
Several answers here have addressed that .length()
gives the wrong results with multibyte characters, but there are 11 answers and none of them have provided a solution.
First of all, it's important to know what you mean by "length". For a motivating example, consider the string "Z??????a???????_l?`?¨???????g????????o???¯????????" (note that some languages, notably Thai, actually use combining diacritical marks, so this isn't just useful for 15-year-old memes, but obviously that's the most important use case). Assume it is encoded in UTF-8. There are 3 ways we can talk about the length of this string:
00000000: 5acd a5cd accc becd 89cc b3cc ba61 cc92 Z............a..
00000010: cc92 cd8c cc8b cdaa ccb4 cd95 ccb2 6ccd ..............l.
00000020: a4cc 80cc 9acc 88cd 9ccc a8cd 8ecc b0cc ................
00000030: 98cd 89cc 9f67 cc92 cd9d cd85 cd95 cd94 .....g..........
00000040: cca4 cd96 cc9f 6fcc 90cd afcc 9acc 85cd ......o.........
00000050: aacc 86cd a3cc a1cc b5cc a1cc bccd 9a ...............
LATIN CAPITAL LETTER Z
COMBINING LEFT ANGLE BELOW
COMBINING DOUBLE LOW LINE
COMBINING INVERTED BRIDGE BELOW
COMBINING LATIN SMALL LETTER I
COMBINING LATIN SMALL LETTER R
COMBINING VERTICAL TILDE
LATIN SMALL LETTER A
COMBINING TILDE OVERLAY
COMBINING RIGHT ARROWHEAD BELOW
COMBINING LOW LINE
COMBINING TURNED COMMA ABOVE
COMBINING TURNED COMMA ABOVE
COMBINING ALMOST EQUAL TO ABOVE
COMBINING DOUBLE ACUTE ACCENT
COMBINING LATIN SMALL LETTER H
LATIN SMALL LETTER L
COMBINING OGONEK
COMBINING UPWARDS ARROW BELOW
COMBINING TILDE BELOW
COMBINING LEFT TACK BELOW
COMBINING LEFT ANGLE BELOW
COMBINING PLUS SIGN BELOW
COMBINING LATIN SMALL LETTER E
COMBINING GRAVE ACCENT
COMBINING DIAERESIS
COMBINING LEFT ANGLE ABOVE
COMBINING DOUBLE BREVE BELOW
LATIN SMALL LETTER G
COMBINING RIGHT ARROWHEAD BELOW
COMBINING LEFT ARROWHEAD BELOW
COMBINING DIAERESIS BELOW
COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW
COMBINING PLUS SIGN BELOW
COMBINING TURNED COMMA ABOVE
COMBINING DOUBLE BREVE
COMBINING GREEK YPOGEGRAMMENI
LATIN SMALL LETTER O
COMBINING SHORT STROKE OVERLAY
COMBINING PALATALIZED HOOK BELOW
COMBINING PALATALIZED HOOK BELOW
COMBINING SEAGULL BELOW
COMBINING DOUBLE RING BELOW
COMBINING CANDRABINDU
COMBINING LATIN SMALL LETTER X
COMBINING OVERLINE
COMBINING LATIN SMALL LETTER H
COMBINING BREVE
COMBINING LATIN SMALL LETTER A
COMBINING LEFT ANGLE ABOVE
Z with some s**t
a with some s**t
l with some s**t
g with some s**t
o with some s**t
There are C++ classes for ICU, but they require converting to UTF-16. You can use the C types and macros directly to get some UTF-8 support:
#include <memory>
#include <iostream>
#include <unicode/utypes.h>
#include <unicode/ubrk.h>
#include <unicode/utext.h>
//
// C++ helpers so we can use RAII
//
// Note that ICU internally provides some C++ wrappers (such as BreakIterator), however these only seem to work
// for UTF-16 strings, and require transforming UTF-8 to UTF-16 before use.
// If you already have UTF-16 strings or can take the performance hit, you should probably use those instead of
// the C functions. See: http://icu-project.org/apiref/icu4c/
//
struct UTextDeleter { void operator()(UText* ptr) { utext_close(ptr); } };
struct UBreakIteratorDeleter { void operator()(UBreakIterator* ptr) { ubrk_close(ptr); } };
using PUText = std::unique_ptr<UText, UTextDeleter>;
using PUBreakIterator = std::unique_ptr<UBreakIterator, UBreakIteratorDeleter>;
void checkStatus(const UErrorCode status)
{
if(U_FAILURE(status))
{
throw std::runtime_error(u_errorName(status));
}
}
size_t countGraphemes(UText* text)
{
// source for most of this: http://userguide.icu-project.org/strings/utext
UErrorCode status = U_ZERO_ERROR;
PUBreakIterator it(ubrk_open(UBRK_CHARACTER, "en_us", nullptr, 0, &status));
checkStatus(status);
ubrk_setUText(it.get(), text, &status);
checkStatus(status);
size_t charCount = 0;
while(ubrk_next(it.get()) != UBRK_DONE)
{
++charCount;
}
return charCount;
}
size_t countCodepoints(UText* text)
{
size_t codepointCount = 0;
while(UTEXT_NEXT32(text) != U_SENTINEL)
{
++codepointCount;
}
// reset the index so we can use the structure again
UTEXT_SETNATIVEINDEX(text, 0);
return codepointCount;
}
void printStringInfo(const std::string& utf8)
{
UErrorCode status = U_ZERO_ERROR;
PUText text(utext_openUTF8(nullptr, utf8.data(), utf8.length(), &status));
checkStatus(status);
std::cout << "UTF-8 string (might look wrong if your console locale is different): " << utf8 << std::endl;
std::cout << "Length (UTF-8 bytes): " << utf8.length() << std::endl;
std::cout << "Length (UTF-8 codepoints): " << countCodepoints(text.get()) << std::endl;
std::cout << "Length (graphemes): " << countGraphemes(text.get()) << std::endl;
std::cout << std::endl;
}
void main(int argc, char** argv)
{
printStringInfo(u8"Hello, world!");
printStringInfo(u8"????????????");
printStringInfo(u8"\xF0\x9F\x90\xBF");
printStringInfo(u8"Z??????a???????_l?`?¨???????g????????o???¯????????");
}
This prints:
UTF-8 string (might look wrong if your console locale is different): Hello, world!
Length (UTF-8 bytes): 13
Length (UTF-8 codepoints): 13
Length (graphemes): 13
UTF-8 string (might look wrong if your console locale is different): ????????????
Length (UTF-8 bytes): 36
Length (UTF-8 codepoints): 12
Length (graphemes): 10
UTF-8 string (might look wrong if your console locale is different):
Length (UTF-8 bytes): 4
Length (UTF-8 codepoints): 1
Length (graphemes): 1
UTF-8 string (might look wrong if your console locale is different): Z??????a???????_l?`?¨???????g????????o???¯????????
Length (UTF-8 bytes): 95
Length (UTF-8 codepoints): 50
Length (graphemes): 5
Boost.Locale wraps ICU, and might provide a nicer interface. However, it still requires conversion to/from UTF-16.
met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.
Using your example provided
#KISS (Keep it simple stupid)
size=${#myvar}
echo $size
HTML
<div class="selector">Text mates</div>
SCRIPT
alert(jQuery('.selector').text().length);
RESULT
10
In MySQL, this works if there are multiple '=' characters in the string
SUBSTRING(supplier_reference FROM (LOCATE('=',supplier_reference)+1))
It returns the substring after(+1) having found the the first =
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
As a followup here's how I got it to work:
@Override public Long getNextExternalId() {
BigDecimal seq =
(BigDecimal)((List)em.createNativeQuery("select col_msd_external_id_seq.nextval from dual").getResultList()).get(0);
return seq.longValue();
}
You can use a regular expression that matches zeroes at the beginning of the string:
s = s.replace(/^0+/, '');
using bootstrap 4 and SCSS check out this link here for full details
https://getbootstrap.com/docs/4.0/getting-started/theming/
in a nutshell...
open up lib/bootstrap/scss/_navbar.scss and find the statements that create these variables
.navbar-nav {
.nav-link {
color: $navbar-light-color;
@include hover-focus() {
color: $navbar-light-hover-color;
}
&.disabled {
color: $navbar-light-disabled-color;
}
}
so now you need to override
$navbar-light-color
$navbar-light-hover-color
$navbar-light-disabled-color
create a new scss file _localVariables.scss and add the following (with your colors)
$navbar-light-color : #520b71
$navbar-light-hover-color: #F3EFE6;
$navbar-light-disabled-color: #F3EFE6;
@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";
and on your other scss pages just add
@import "_localVariables";
instead of
@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";
Try this
SELECT * FROM messages where id in (SELECT max(id) FROM messages GROUP BY from_id ) order by id desc
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
Python working a bit differently to JavaScript for example, the value you are concatenating needs to be same type, both int or str...
So for example the code below throw an error:
print( "Alireza" + 1980)
like this:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print( "Alireza" + 1980)
TypeError: can only concatenate str (not "int") to str
To solve the issue, just add str to your number or value like:
print( "Alireza" + str(1980))
And the result as:
Alireza1980
Yes! You can Debug Android Application While you are developing them follow these steps.. Make sure that you have PC suite of the mobile manufacturer. For Example:if you are using samsung you should have samsung kies
1.Enable USB debugging on your device:Settings > Applications > Development > USB debugging
2.Enable Unknownresources:Settings>Unknowresoures
3.Connect your device to PC
4.Select your Application Right click it: RunAS>Run configurations>Choose Device>Target Select your device Run.
You can also without using debugging cable.For that you need to install Airdroid in your device.After installing enter the link in your browser and Drag and Drop .apk file.
Happy Coding!
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -Uri $url -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured:
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
Or you could use something like the following. Pay attention to "\n":
/**
* Created by mona on 3/26/16.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {
public static void main (String[] args) throws java.io.IOException {
File newFile = new File("tweet.txt");
FileWriter fileWriter = new FileWriter(newFile);
fileWriter.write("Mona Jalal");
fileWriter.append("\nMona Mona");
fileWriter.close();
FileReader fileReader = new FileReader(newFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
bufferedReader.close();
}
}
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
window.print();
unless you mean a custom looking popup.
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
Capturing lambdas cannot be converted to function pointers, as this answer pointed out.
However, it is often quite a pain to supply a function pointer to an API that only accepts one. The most often cited method to do so is to provide a function and call a static object with it.
static Callable callable;
static bool wrapper()
{
return callable();
}
This is tedious. We take this idea further and automate the process of creating wrapper
and make life much easier.
#include<type_traits>
#include<utility>
template<typename Callable>
union storage
{
storage() {}
std::decay_t<Callable> callable;
};
template<int, typename Callable, typename Ret, typename... Args>
auto fnptr_(Callable&& c, Ret (*)(Args...))
{
static bool used = false;
static storage<Callable> s;
using type = decltype(s.callable);
if(used)
s.callable.~type();
new (&s.callable) type(std::forward<Callable>(c));
used = true;
return [](Args... args) -> Ret {
return Ret(s.callable(std::forward<Args>(args)...));
};
}
template<typename Fn, int N = 0, typename Callable>
Fn* fnptr(Callable&& c)
{
return fnptr_<N>(std::forward<Callable>(c), (Fn*)nullptr);
}
And use it as
void foo(void (*fn)())
{
fn();
}
int main()
{
int i = 42;
auto fn = fnptr<void()>([i]{std::cout << i;});
foo(fn); // compiles!
}
This is essentially declaring an anonymous function at each occurrence of fnptr
.
Note that invocations of fnptr
overwrite the previously written callable
given callables of the same type. We remedy this, to a certain degree, with the int
parameter N
.
std::function<void()> func1, func2;
auto fn1 = fnptr<void(), 1>(func1);
auto fn2 = fnptr<void(), 2>(func2); // different function
You need spaces around the operator =~
i="test" if [[ $i =~ "200[78]" ]]; then echo "OK" else echo "not OK" fi
Make sure you switch the SHELL first:
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
RUN [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
RUN Invoke-WebRequest -UseBasicParsing -Uri 'https://github.com/git-for-windows/git/releases/download/v2.25.1.windows.1/Git-2.25.1-64-bit.exe' -OutFile 'outfile.exe'
You could try letting the stream throw an exception on failure:
std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);
try {
f.open(fileName);
}
catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
e.what()
, however, does not seem to be very helpful:
strerror(errno)
gives "No such file or directory."If e.what()
does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition
(C++11 only):
catch (std::ios_base::failure& e) {
if ( e.code() == std::make_error_condition(std::io_errc::stream) )
std::cerr << "Stream error!\n";
else
std::cerr << "Unknown failure opening file.\n";
}
In Swift 3.0
extension String
{
func trim() -> String
{
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
And you can call
let result = " Hello World ".trim() /* result = "Hello World" */
Another solution would be dictdiffer
(https://github.com/inveniosoftware/dictdiffer).
import dictdiffer
a_dict = {
'a': 'foo',
'b': 'bar',
'd': 'barfoo'
}
b_dict = {
'a': 'foo',
'b': 'BAR',
'c': 'foobar'
}
for diff in list(dictdiffer.diff(a_dict, b_dict)):
print diff
A diff is a tuple with the type of change, the changed value, and the path to the entry.
('change', 'b', ('bar', 'BAR'))
('add', '', [('c', 'foobar')])
('remove', '', [('d', 'barfoo')])
Try using the success()
call back
$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
$scope.Documents = result;
});
But now since Documents
is an array and not a promise, remove the ()
<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
<input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
</span>
<span>{{document.Name}}</span>
</li>
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
widget['bg'] = '#000000'
or
widget['background'] = '#000000'
would also work as hex-valued colors are also accepted.
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
put set -o pipefail at start of any script, to return any failure
incase you do, and the test fails but the tee doesnt. By default $? just takes the last commands success, in this case the "tee" command
test | tee /tmp/dump
[ $? -ne 0 ] && echo "failed"
// a wrapper closure around executing a string
// can take either a string or a list of strings (for arguments with spaces)
// prints all output, complains and halts on error
def runCommand = { strList ->
assert ( strList instanceof String ||
( strList instanceof List && strList.each{ it instanceof String } ) \
)
def proc = strList.execute()
proc.in.eachLine { line -> println line }
proc.out.close()
proc.waitFor()
print "[INFO] ( "
if(strList instanceof List) {
strList.each { print "${it} " }
} else {
print strList
}
println " )"
if (proc.exitValue()) {
println "gave the following error: "
println "[ERROR] ${proc.getErrorStream()}"
}
assert !proc.exitValue()
}
I would recommend to call the script like this
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>
The js and css files must be treat differently
Put
jquery
as the first before otherJS scripts
at the bottom of<BODY>
tag
HTTP/1.1 specification
suggests that browsers download no more than two components in parallel per hostname. <head>
tags and let the rest including the jquery
to be called on the bottom <body>
tag.Put
CSS style
on top of<HEAD>
tag after the other more priority tags
HEAD
makes pages appear to be loading faster. This is because putting style sheets in the HEAD
allows the page to render progressively.css
sheets, it is better to put them all on the <head>
tag but let the style that shall be immediately rendered to be put in <style>
tags inside <HEAD>
and the rest in <body>
.You may also find other suggestion when you test your page like on Google PageSpeed Insight
When creating the chart object you need to save the instance in a variable.
var currentChart = new Chart(ctx, ...);
And before loading new data, you need to destroy it:
currentChart.destroy();
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
And if you want to add a row, you can use a dictionary:
df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)
which gives you:
age height name
0 9 2 Zed
Here is a guide on how to use cntlm
cntlm is an NTLM/NTLMv2 authenticating HTTP proxy
It takes the address of your proxy and opens a listening socket, forwarding each request to the parent proxy
Using cntlm we make it possible to run tools like choro, pip3, apt-get
from a command line
pip3 install requests
choco install git
The main advantage of cntlm is password protection.
With cntlm you can use password hashes.
So NO PLAINTEXT PASSWORD in %HTTP_PROXY%
and %HTTPS_PROXY%
environment variables
You can get the latest cntlm release from sourceforge
My username is zezulinsky
My domain is local
When I run commands I use zezulinsky@local
Place your username when you run commands
Run a command
cntlm -u zezulinsky@local -H
Enter your password:
Password:
As a result you are getting hashed password:
PassLM AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Run a command
cntlm -u zezulinsky@local -M http://google.com
Enter your password
Password:
The result output
Config profile 1/4... OK (HTTP code: 301)
----------------------------[ Profile 0 ]------
Auth NTLMv2
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
------------------------------------------------
Note! check that PassNTLMv2 hash is the same The resulting hash is the same for both commands
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Place generated hashes into the cntlm.ini
configuration file
C:\Program Files (x86)\Cntlm\cntlm.ini
Here is how your cntlm.ini
should look like
Username zezulinsky
Domain local
PassLM AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2 46738B2E607F9093296AA4C319C3A259
Proxy PROXYSERVER:8080
NoProxy localhost, 127.0.0.*
Listen 3128
It is important to add a newline at the end of the cntlm.ini
configuration file
HTTPS_PROXY=http://localhost:3128
HTTP_PROXY=http://localhost:3128
Stop all the processes named cntlm.exe
with process explorer
Run the command
cntlm -u zezulinsky@local -H
The output looks like
cygwin warning:
MS-DOS style path detected: C:\Program Files (x86)\Cntlm\cntlm.ini
Preferred POSIX equivalent is: /Cntlm/cntlm.ini
CYGWIN environment variable option "nodosfilewarning" turns off this warning.
Consult the user's guide for more details about POSIX paths:
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
section: local, Username = 'zezulinsky'
section: local, Domain = 'local'
section: local, PassLM = 'AB7D42F42QQQQ407552C4BCA4AEBFB11'
section: local, PassNT = 'PE78D847E35FA7FA59710D1231AAAF99'
section: local, PassNTLMv2 = '46738B2E607F9093296AA4C319C3A259'
section: local, Proxy = 'PROXYSERVER:8080'
section: local, NoProxy = 'localhost, 10.*, 127.0.0.*
section: local, Listen = '3128'
Default config file opened successfully
cntlm: Proxy listening on 127.0.0.1:3128
Adding no-proxy for: 'localhost'
Adding no-proxy for: '10.*'
Adding no-proxy for: '127.0.0.*'
cntlm: Workstation name used: MYWORKSTATION
cntlm: Using following NTLM hashes: NTLMv2(1) NT(0) LM(0)
cntlm: PID 1234: Cntlm ready, staying in the foreground
Open a new cmd and run a command:
pip3 install requests
You should have requests python package installed
Congrats, now you have cntlm installed and configured
If you're using SQL Server it would be something like this:
DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90
The difference between memcpy
and memmove
is that
in memmove
, the source memory of specified size is copied into buffer and then moved to destination. So if the memory is overlapping, there are no side effects.
in case of memcpy()
, there is no extra buffer taken for source memory. The copying is done directly on the memory so that when there is memory overlap, we get unexpected results.
These can be observed by the following code:
//include string.h, stdio.h, stdlib.h
int main(){
char a[]="hare rama hare rama";
char b[]="hare rama hare rama";
memmove(a+5,a,20);
puts(a);
memcpy(b+5,b,20);
puts(b);
}
Output is:
hare hare rama hare rama
hare hare hare hare hare hare rama hare rama
A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class ImageButton extends Button {
public void updateImages(final Image selected, final Image unselected) {
final ImageView iv = new ImageView(selected);
this.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(unselected);
}
});
iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(selected);
}
});
super.setGraphic(iv);
}
}
I tried this:
if(capital !== null){
//Capital has something
}
If you are looking to do your own ORM or generate code from a given table, then this might be what you are looking form:
declare @table varchar(100) = 'mytable';
with cte as
(
select
tc.CONSTRAINT_SCHEMA
, tc.CONSTRAINT_TYPE
, tc.TABLE_NAME
, ccu.COLUMN_NAME
, IS_NULLABLE
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, NUMERIC_PRECISION
from
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu on tc.TABLE_NAME=ccu.TABLE_NAME and tc.TABLE_SCHEMA=ccu.TABLE_SCHEMA
inner join information_schema.COLUMNS c on ccu.COLUMN_NAME=c.COLUMN_NAME and ccu.TABLE_NAME=c.TABLE_NAME and ccu.TABLE_SCHEMA=c.TABLE_SCHEMA
where
tc.table_name=@table
and
ccu.CONSTRAINT_NAME=tc.CONSTRAINT_NAME
union
select TABLE_SCHEMA,'COLUMN', TABLE_NAME, COLUMN_NAME, IS_NULLABLE, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@table
and COLUMN_NAME not in (select COLUMN_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = @table)
)
select
cast(iif(CONSTRAINT_TYPE='PRIMARY KEY',1,0) as bit) PrimaryKey
,cast(iif(CONSTRAINT_TYPE='FOREIGN KEY',1,0) as bit) ForeignKey
,cast(iif(CONSTRAINT_TYPE='COLUMN',1,0) as bit) NotKey
,COLUMN_NAME
,cast(iif(is_nullable='NO',0,1) as bit) IsNullable
, DATA_TYPE
, CHARACTER_MAXIMUM_LENGTH
, NUMERIC_PRECISION
from
cte
order by
case CONSTRAINT_TYPE
when 'PRIMARY KEY' then 1
when 'FOREIGN KEY' then 2
else 3 end
, COLUMN_NAME
Here is what the result would look like:
<table cellspacing=0 border=1>_x000D_
<tr>_x000D_
<td style=min-width:50px>PrimaryKey</td>_x000D_
<td style=min-width:50px>ForeignKey</td>_x000D_
<td style=min-width:50px>NotKey</td>_x000D_
<td style=min-width:50px>COLUMN_NAME</td>_x000D_
<td style=min-width:50px>IsNullable</td>_x000D_
<td style=min-width:50px>DATA_TYPE</td>_x000D_
<td style=min-width:50px>CHARACTER_MAXIMUM_LENGTH</td>_x000D_
<td style=min-width:50px>NUMERIC_PRECISION</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>LectureNoteID</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>LectureId</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>NoteTypeID</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>Body</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>nvarchar</td>_x000D_
<td style=min-width:50px>-1</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>1</td>_x000D_
<td style=min-width:50px>DisplayOrder</td>_x000D_
<td style=min-width:50px>0</td>_x000D_
<td style=min-width:50px>int</td>_x000D_
<td style=min-width:50px>NULL</td>_x000D_
<td style=min-width:50px>10</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
Basically like this,
<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>
Use a Comparator:
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
@Override
public int compare(CustomObject left, CustomObject right) {
return left.getId() - right.getId(); // use your logic
}
};
Collections.sort(list, comparator); // use the comparator as much as u want
System.out.println(list);
Additionally, if CustomObject
implements Comparable
, then just use Collections.sort(list)
List<CustomObject> list = getCustomObjectList();
Collections.sort(list, (left, right) -> left.getId() - right.getId());
System.out.println(list);
Much simplier
List<CustomObject> list = getCustomObjectList();
list.sort((left, right) -> left.getId() - right.getId());
System.out.println(list);
Simplest
List<CustomObject> list = getCustomObjectList();
list.sort(Comparator.comparing(CustomObject::getId));
System.out.println(list);
Obviously the initial code can be used for JDK 8 too.
HAVING
operates on aggregates. Since COUNT
is an aggregate function, you can't use it in a WHERE
clause.
Here's some reading from MSDN on aggregate functions.
I have edited the function for you,
void readFile()
{
ifstream file;
file.open ("program.txt");
if (!file.is_open()) return;
string word;
while (file >> word)
{
cout<< word << '\n';
}
}
Just add /g
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
to
// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
/g
means global
Leeroy & Richard Parnaby-King:
UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement
function forceDownload(url, fileName){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function(){
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
var tag = document.createElement('a');
tag.href = imageUrl;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
}
xhr.send();
}
:ls
for list of open buffers
:bp
previous buffer:bn
next buffer:bn
(n
a number) move to n'th buffer:b <filename-part>
with tab-key providing auto-completion (awesome !!)In some versions of vim, bn
and bp
are actually bnext
and bprevious
respectively. Tab auto-complete is helpful in this case.
Or when you are in normal mode, use ^
to switch to the last file you were working on.
Plus, you can save sessions of vim
:mksession! ~/today.ses
The above command saves the current open file buffers and settings to ~/today.ses
. You can load that session by using
vim -S ~/today.ses
No hassle remembering where you left off yesterday. ;)
I solved this problem in the following way:
You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.
Also, I don't think you can use NOW()
as default value in OrderDate. Try to use the following:
OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Using Merlyn's solution caused other applications to be killed like firefox. These processes were using the same port, but not as a listener:
eg:
netstat -a -n -o | findstr :8085
TCP 0.0.0.0:8085 0.0.0.0:0 LISTENING 6568
TCP 127.0.0.1:49616 127.0.0.1:8085 TIME_WAIT 0
TCP 127.0.0.1:49618 127.0.0.1:8085 TIME_WAIT 0
Therefore, can excluded these by adding "LISTENING" to the findstr as follows:
FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8085.*LISTENING') DO TaskKill.exe /PID %%P
Use this script, it is previous version of jquery. Solved my problem.
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
int average_in_int = ( (Double) Math.ceil( sum/count ) ).intValue();
You can just "call" your model with an array of the correct shape:
model(np.array([[6.7, 3.3, 5.7, 2.5]]))
Full example:
from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np
X, y = load_iris(return_X_y=True)
model = Sequential([
Dense(16, activation='relu'),
Dense(32, activation='relu'),
Dense(1)])
model.compile(loss='mean_absolute_error', optimizer='adam')
history = model.fit(X, y, epochs=10, verbose=0)
print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))
<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>
Add the following code to your Startup.Auth.cs file under the static constructor:
UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
The UserManagerFactory setting line of code is what you use to associate your custom DataContext with the UserManager. Once you have done that, then you can get an instance of the UserManager in your ApiController and the UserManager.UpdateAsync(user) method will work because it is using your DataContext to save the extra properties you've added to your custom application user.
Below is a solution for WINDOWS ONLY
In cases where the application (like Tomcat) is started as a windows service, the System.getProperty("user.name") or System.getenv().get("USERNAME") return the user who started the service and not the current logged in user name.
Also in Java 9 the NTSystem etc classes will not be accessible
So workaround for windows: You can use wmic, so you have to run the below command
wmic ComputerSystem get UserName
If available, this will return output of the form:
UserName
{domain}\{logged-in-user-name}
Note: For windows you need to use cmd /c as a prefix, so below is a crude program as an example:
Process exec = Runtime.getRuntime().exec("cmd /c wmic ComputerSystem get UserName".split(" "));
System.out.println(exec.waitFor());
try (BufferedReader bw = new BufferedReader(new InputStreamReader(exec.getInputStream()))) {
System.out.println(bw.readLine() + "\n" + bw.readLine()+ "\n" + bw.readLine());
}
you are showing your popup too early. You may post a delayed runnable for showatlocation in Onresume , Give it a try
Edit: This post seems to have the same problem answered Problems creating a Popup Window in Android Activity
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.Rows("2:2").Select
ActiveWindow.FreezePanes = True
This is the easiest way to freeze the top row. The rule for FreezePanes
is it will freeze the upper left corner from the cell you selected. For example, if you highlight C10, it will freeze between columns B and C, rows 9 and 10. So when you highlight Row 2, it actually freeze between Rows 1 and 2 which is the top row.
Also, the .SplitColumn
or .SplitRow
will split your window once you unfreeze it which is not the way I like.
A simple solution that springs to mind is to have a String
block of spaces:
String indent = " "; // 20 spaces.
When printing out a string, compute the actual indent and add it to the end:
String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);
This will mediate the number of spaces to the string, and put them all in the same column.
Probably Timerconcept
new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
}.start();
or
Method 2 ::
Program the timer
Add a new variable of int named time. Set it to 0. Add the following code to onCreate function in MainActivity.java.
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
Go into the run method and add the following code.
//We must use this function in order to change the text view text
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(time));
time += 1;
}
});
This theme required awhile to find results and reasons:
using MaiaDB 5.4. via SuSE-LINUX tumblweed
some files in the appointed directory havn't been necessary in any direct relation with mariadb. I.e: I placed some hints, a text-file, some bakup-copys somewhere in the same appointed directory for mysql mariadb and this caused endless error-messages and blocking the server from starting. Mariadb appears to be very sensible and hostile with the presence of other files not beeing database files(comments,backups,experimantal files etc) .
using libreoffice as client then there already this generated much problems with the creation and working on a database and caused some crashes.The crashes eventually produced bad tables.
May be because of that or may be because of the presence of not yet deleted but unusable tables !! the mysql mariadb server crashed and didn't want to do it' job not even start.
Error message always same : "Table 'some.table' doesn't exist in engine"
But when it started then tables appeared as normal, but it was unpossible to work on them.
So what to do without a more precise Error Message ?? The unusable tables showed up with: "CHECK TABLE" or on the command line of the system with "mysqlcheck " So I deleted by filemanager or on the system-level as root or as allowed user all the questionable files and then problem was solved.
Proposal: the Error Message could be a bit more precisely for example: "corrupted tables" (which can be found by CHECK TABLE, but only if the server is running) or by mysqlcheck even whe server is not running - but here are other disturbing files like hints/bakups a.s.o not visible.
ANYWAY it helped a lot to have backup-copies of the original database-files on a backup volume. This helped to check out and test it again and again until solution was found.
Good luck all - Herbert
For nan of type float
>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False
When one gets the error 'sub-query returns more than 1 row', the database is actually telling you that there is an unresolvable circular reference. It's a bit like using a spreadsheet and saying cell A1 = B1 and then saying B1 = A1. This error is typically associated with a scenario where one needs to have a double nested sub-query. I would recommend you look up a thing called a 'cross-tab query' this is the type of query one normally needs to solve this problem. It's basically an outer join (left or right) nested inside a sub-query or visa versa. One can also solve this problem with a double join (also considered to be a type of cross-tab query) such as below:
CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_GET_VEHICLES_IN`(
IN P_email VARCHAR(150),
IN P_credentials VARCHAR(150)
)
BEGIN
DECLARE V_user_id INT(11);
SET V_user_id = (SELECT user_id FROM users WHERE email = P_email AND credentials = P_credentials LIMIT 1);
SELECT vehicles_in.vehicle_id, vehicles_in.make_id, vehicles_in.model_id, vehicles_in.model_year,
vehicles_in.registration, vehicles_in.date_taken, make.make_label, model.model_label
FROM make
LEFT OUTER JOIN vehicles_in ON vehicles_in.make_id = make.make_id
LEFT OUTER JOIN model ON model.make_id = make.make_id AND vehicles_in.model_id = model.model_id
WHERE vehicles_in.user_id = V_user_id;
END
In the code above notice that there are three tables in amongst the SELECT clause and these three tables show up after the FROM clause and after the two LEFT OUTER JOIN clauses, these three tables must be distinct amongst the FROM and LEFT OUTER JOIN clauses to be syntactically correct.
It is noteworthy that this is a very important construct to know as a developer especially if you're writing periodical report queries and it's probably the most important skill for any complex cross referencing, so all developers should study these constructs (cross-tab and double join).
Another thing I must warn about is: If you are going to use a cross-tab as a part of a working system and not just a periodical report, you must check the record count and reconfigure the join conditions until the minimum records are returned, otherwise large tables and cross-tabs can grind your server to a halt. Hope this helps.
select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''
I had to move domain, username, password from
client.ClientCredentials.UserName.UserName = domain + "\\" + username; client.ClientCredentials.UserName.Password = password
to
client.ClientCredentials.Windows.ClientCredential.UserName = username; client.ClientCredentials.Windows.ClientCredential.Password = password; client.ClientCredentials.Windows.ClientCredential.Domain = domain;
There are 2 major ways to create/intialize an array in swift.
var myArray = [Double]()
This would create an array of Doubles.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
This would create an array of 5 doubles, all initialized with the value of 2.0.
My version:
Function Test-RegistryValue($Key, $Name)
{
(Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}
I had the same problem, made all the workarounds you advised: still the same error. I updated Eclipse via "Help / Check for updates" and now everything is ok. This update brought a completely new version of the Android SDK Manager.
To change the directory for target dll/exe, use this in your pro file:
CONFIG(debug, debug|release) {
DESTDIR = build/debug
} else {
DESTDIR = build/release
}
You might also want to change directories for other build targets like object files and moc files (check qmake variable reference for details or qmake CONFIG() function reference).
Select the package that will be refactored. Refactor ? Move ? "Move xxx to new package".
You can use ScriptEngine, example:
public class Main {
public static void main(String[] args) {
StringBuffer javascript = null;
ScriptEngine runtime = null;
try {
runtime = new ScriptEngineManager().getEngineByName("javascript");
javascript = new StringBuffer();
javascript.append("1 + 1");
double result = (Double) runtime.eval(javascript.toString());
System.out.println("Result: " + result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
I'm adding this solution for people who make the same mistake as I did.
In most cases: rename your project file 'serial.py' and delete serial.pyc if exists, then you can do simple 'import serial' without attribute error.
Problem occurs when you import 'something' when your python file name is 'something.py'.
return string.Join(", ", strings.ToArray());
In .Net 4, there's a new overload for string.Join
that accepts IEnumerable<string>
. The code would then look like:
return string.Join(", ", strings);
For fellow Xamarians, the Xamarin.iOS/C# version of the answer would look like the following:
public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
CGContext currentContext = UIGraphics.GetCurrentContext();
currentContext.SaveState();
currentContext.SetShadow(new CGSize(-15, 20), 5);
base.DrawRect(area, formatter);
currentContext.RestoreState();
}
The main difference is that you acquire an instance of CGContext
on which you directly call the appropriate methods.
I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
In a helper class (HelperMethods) I created the following method:
public static List<string> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
}
When you call this helper you will get the list of item descriptions.
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
/* how to use
MyEnum x = MyEnum.NeedMoreCoffee;
string description = x.GetDescription();
*/
}
From here
You should be referencing a copy of the library that you copied to your development workspace—you should not reference the library directly from the Android SDK directory.
I faced this error because I referenced the original copy from SDK directory. Make sure that you first copy the library to android workspace and only reference it. In eclipse you can do it by checking "Copy projects into workspace" while importing the project.
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
Extracts myArchive.tar to /destinationDirectory
Commands:
cd /destinationDirectory
pax -rv -f myArchive.tar -s ',^/,,'
The simplest way to connect is through an OdbcConnection using code like this
using System.Data.Odbc;
using(OdbcConnection myConnection = new OdbcConnection())
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
}
where myConnectionString is something like this
myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;
In alternative you could create a DSN and then use that DSN in your connection string
now your connectionString could be written in this way
myConnectionString = "DSN=myDSN;"
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
Kotlin? Here we go:
android {
// ... (compileSdkVersion, buildToolsVersion, etc)
defaultConfig {
// ... (applicationId, miSdkVersion, etc)
kapt {
arguments {
arg("room.schemaLocation", "$projectDir/schemas")
}
}
}
buildTypes {
// ... (buildTypes, compileOptions, etc)
}
}
//...
Don't forget about plugin:
apply plugin: 'kotlin-kapt'
For more information about kotlin annotation processor please visit: Kotlin docs
str[a:b]
tl;dr: use a colon :
instead of a comma in between the two indices a
and b
in str[a:b]
When working with strings and slice notation (a common sequence operation), it can happen that a TypeError
is raised, pointing out that the indices must be integers, even if they obviously are.
>>> my_string = "hello world"
>>> my_string[0,5]
TypeError: string indices must be integers
We obviously passed two integers for the indices to the slice notation, right? So what is the problem here?
This error can be very frustrating - especially at the beginning of learning Python - because the error message is a little bit misleading.
We implicitly passed a tuple of two integers (0 and 5) to the slice notation when we called my_string[0,5]
because 0,5
(even without the parentheses) evaluates to the same tuple as (0,5)
would do.
A comma ,
is actually enough for Python to evaluate something as a tuple:
>>> my_variable = 0,
>>> type(my_variable)
<class 'tuple'>
So what we did there, this time explicitly:
>>> my_string = "hello world"
>>> my_tuple = 0, 5
>>> my_string[my_tuple]
TypeError: string indices must be integers
Now, at least, the error message makes sense.
We need to replace the comma ,
with a colon :
to separate the two integers correctly:
>>> my_string = "hello world"
>>> my_string[0:5]
'hello'
A clearer and more helpful error message could have been something like:
TypeError: string indices must be integers (not tuple)
A good error message shows the user directly what they did wrong and it would have been more obvious how to solve the problem.
[So the next time when you find yourself responsible for writing an error description message, think of this example and add the reason or other useful information to error message to let you and maybe other people understand what went wrong.]
:
to separate its indices (and step range, e.g. str[from:to:step]
),
(e.g. t = 1,
)Cheers and happy programming
winklerrr
[I know this question was already answered and this wasn't exactly the question the thread starter asked, but I came here because of the above problem which leads to the same error message. At least it took me quite some time to find that little typo.
So I hope that this will help someone else who stumbled upon the same error and saves them some time finding that tiny mistake.]
no javascript or third party 'tools' necessary, use this:
<iframe src="https://www.google.com/maps/embed/v1/place?key=<YOUR API KEY>&q=71.0378379,-110.05995059999998"></iframe>
the place parameter provides the marker
there are a few options for the format of the 'q' parameter
make sure you have Google Maps Embed API and Static Maps API enabled in your APIs, or google will block the request
for more information check here
As the update to the other answer suggests, the workaround of installing the old openssl101 brew will no longer work. For a right-now workaround, see this comment on dotnet/cli#3964.
The most relevant part of the issue copied here:
I looked into the other option that was suggested for setting the rpath on the library. I think the following is a better solution that will only effect this specific library.
sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib /usr/local/share/dotnet/shared/Microsoft.NETCore.App/1.0.0/System.Security.Cryptography.Native.dylib
and/or if you have NETCore 1.0.1 installed perform the same command for 1.0.1 as well:
sudo install_name_tool -add_rpath /usr/local/opt/openssl/lib /usr/local/share/dotnet/shared/Microsoft.NETCore.App/1.0.1/System.Security.Cryptography.Native.dylib
In effect, rather than telling the operating system to always use the homebrew version of SSL and potentially causing something to break, we're telling dotnet how to find the correct library.
Also importantly, it looks like Microsoft are aware of the issue and and have both a) a somewhat immediate plan to mitigate as well as b) a long-term solution (probaby bundling OpenSSL with dotnet).
Another thing to note: /usr/local/opt/openssl/lib
is where the brew is linked by default:
13:22 $ ls -l /usr/local/opt/openssl
lrwxr-xr-x 1 ben admin 26 May 15 14:22 /usr/local/opt/openssl -> ../Cellar/openssl/1.0.2h_1
If for whatever reason you install the brew and link it in a different location, then that path is the one you should use as an rpath.
Once you've update the rpath of the System.Security.Cryptography.Native.dylib libray, you'll need to restart your interactive session (i.e., close your console and start another one).
Why not just:
import seaborn as sns
sns.barplot(list(D.keys()), list(D.values()))
You can add a random (or datetime string) as query string to the url that points to your script. Like so:
<script type="text/javascript" src="test.js?q=123"></script>
Every time you refresh the page you need to make sure the value of 'q' is changed.
As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.
This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...
function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}
The simple answer to this is to use this:
ALTER TABLE MEN DROP COLUMN Lname;
More than one column can be specified like this:
ALTER TABLE MEN DROP COLUMN Lname, secondcol, thirdcol;
From SQL Server 2016 it is also possible to only drop the column only if it exists. This stops you getting an error when the column doesn't exist which is something you probably don't care about.
ALTER TABLE MEN DROP COLUMN IF EXISTS Lname;
There are some prerequisites to dropping columns. The columns dropped can't be:
If any of the above are true you need to drop those associations first.
Also, it should be noted, that dropping a column does not reclaim the space from the hard disk until the table's clustered index is rebuilt. As such it is often a good idea to follow the above with a table rebuild command like this:
ALTER TABLE MEN REBUILD;
Finally as some have said this can be slow and will probably lock the table for the duration. It is possible to create a new table with the desired structure and then rename like this:
SELECT
Fname
-- Note LName the column not wanted is not selected
INTO
new_MEN
FROM
MEN;
EXEC sp_rename 'MEN', 'old_MEN';
EXEC sp_rename 'new_MEN', 'MEN';
DROP TABLE old_MEN;
But be warned there is a window for data loss of inserted rows here between the first select and the last rename command.
If i understood correct try this one
$headers = "Bcc: [email protected]";
or
$headers = "Cc: [email protected]";
With iPhone-X, height of top bar (navigation bar + status bar) is changed (increased).
Try this if you want exact height of top bar (both navigation bar + status bar):
UPDATE
iOS 13
As the statusBarFrame
was deprecated in iOS13
you can use this:
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Objective-C
CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
(self.navigationController.navigationBar.frame.size.height ?: 0.0));
Swift 4
let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
For ease, try this UIViewController extension
extension UIViewController {
/**
* Height of status bar + navigation bar (if navigation bar exist)
*/
var topbarHeight: CGFloat {
return UIApplication.shared.statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
}
}
Swift 3
let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
Rather than trying to output to the console, Log
will output to LogCat which you can find in Eclipse by going to: Window->Show View->Other…->Android->LogCat
Have a look at the reference for Log
.
The benefits of using LogCat are that you can print different colours depending on your log type, e.g.: Log.d
prints blue, Log.e
prints orange. Also you can filter by log tag, log message, process id and/or by application name. This is really useful when you just want to see your app's logs and keep the other system stuff separate.
Use
s.length()
The following was once suggested in one of the answers, but its very inefficient
textMessage.getText().toString().length()
Yes you can - see ConfigurationManager
The ConfigurationManager class includes members that enable you to perform the following tasks:
- Read and write configuration files as a whole.
Learn to use the docs, they should be your first port-of call for a question like this.
It is much easier and reliable to convert html to pdf server side. We are using Google Puppeteer. It is well maintained with wrappers for any server side language of your choosing. Puppeteer uses headless Chrome to generate screenshots and/or PDF files. It will save you a LOT of headache especially if you need to generate complex PDF files with tables, images, graphs, multiple pages and so
If your C/C++ code is portable to *nix, few things are better than Valgrind.
You can use the XML out format, for example:
svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +
Example: using the revision number
working=`svn info --xml | grep 'revision' | head -1 | grep -Eo "[0-9]+" | xargs expr -1 +`
svn diff -r $working:HEAD --summarize --xml
# Patrick Burwell's Ping Script - [email protected] #
$Output= @() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
){# If true then run...
$Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
}
else{#If false then run...
$Output+= "$name," #Fills the array with the #false response
Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
}
}
#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments
The docs mention train_test_split is just a convenience function on top of shuffle split.
I just rearranged some of their code to make my own example. Note the actual solution is the middle block of code. The rest is imports, and setup for a runnable example.
from sklearn.model_selection import ShuffleSplit
from sklearn.utils import safe_indexing, indexable
from itertools import chain
import numpy as np
X = np.reshape(np.random.randn(20),(10,2)) # 10 training examples
y = np.random.randint(2, size=10) # 10 labels
seed = 1
cv = ShuffleSplit(random_state=seed, test_size=0.25)
arrays = indexable(X, y)
train, test = next(cv.split(X=X))
iterator = list(chain.from_iterable((
safe_indexing(a, train),
safe_indexing(a, test),
train,
test
) for a in arrays)
)
X_train, X_test, train_is, test_is, y_train, y_test, _, _ = iterator
print(X)
print(train_is)
print(X_train)
Now I have the actual indexes: train_is, test_is
To check the size of all of the directories within a directory, you can use:
du -h --max-depth=1
Below is mine, inspired by shacker's get_all_fields
.
It gets a dict of one model instance, if encounter relation field, then asign the field value a dict recursively.
def to_dict(obj, exclude=[]):
"""???? dict, ?????? model instance ??.
"""
tree = {}
for field in obj._meta.fields + obj._meta.many_to_many:
if field.name in exclude or \
'%s.%s' % (type(obj).__name__, field.name) in exclude:
continue
try :
value = getattr(obj, field.name)
except obj.DoesNotExist:
value = None
if type(field) in [ForeignKey, OneToOneField]:
tree[field.name] = to_dict(value, exclude=exclude)
elif isinstance(field, ManyToManyField):
vs = []
for v in value.all():
vs.append(to_dict(v, exclude=exclude))
tree[field.name] = vs
elif isinstance(field, DateTimeField):
tree[field.name] = str(value)
elif isinstance(field, FileField):
tree[field.name] = {'url': value.url}
else:
tree[field.name] = value
return tree
This function is mainly used to dump a model instance to json data:
def to_json(self):
tree = to_dict(self, exclude=('id', 'User.password'))
return json.dumps(tree, ensure_ascii=False)
Error message suggests that the client has closed the connection while the server is still trying to write out a response.
Refer to this link for more details:
The MSDN documentation for environment variables tells you what to do:
To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string "Environment". This allows applications, such as the shell, to pick up your updates.
You will of course need admin rights to do this. I know of no way to broadcast a windows message from Windows batch so you'll need to write a small program to do this.
Good solution to extend native functionality by extensions
import UIKit
extension UIImage {
convenience init?(url: URL?) {
guard let url = url else { return nil }
do {
self.init(data: try Data(contentsOf: url))
} catch {
print("Cannot load image from url: \(url) with error: \(error)")
return nil
}
}
}
Convenience initializer is failable and accepts optional URL
– approach is safe.
imageView.image = UIImage(url: URL(string: "some_url.png"))
With guava it's even simpler:
boolean isPartOfMyEnum(String myString){
return Lists.newArrayList(MyEnum.values().toString()).contains(myString);
}
The Multipart File Upload worked after following code modification to Upload using RestTemplate
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
ResponseEntity<String> result = template.get().exchange(
contextPath.get() + path, HttpMethod.POST, requestEntity,
String.class);
And adding MultipartFilter to web.xml
<filter>
<filter-name>multipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>multipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Initialize instance:
private String imagePath;
private List<String> imagePathList;
In onActivityResult You have to write this, If-else 2 block. One for single image and another for multiple image.
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && data != null){
imagePathList = new ArrayList<>();
if(data.getClipData() != null){
int count = data.getClipData().getItemCount();
for (int i=0; i<count; i++){
Uri imageUri = data.getClipData().getItemAt(i).getUri();
getImageFilePath(imageUri);
}
}
else if(data.getData() != null){
Uri imgUri = data.getData();
getImageFilePath(imgUri);
}
}
Most important part, Get Image Path from uri:
public void getImageFilePath(Uri uri) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String image_id = filePath[filePath.length - 1];
Cursor cursor = getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
if (cursor!=null) {
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
imagePathList.add(imagePath);
cursor.close();
}
}
Hope this can help you.
I faced 'google is not defined' several time. Probably Google Script has some problem not to be loaded well with FF-addon BTW. FF has restart option ( like window reboot ) Help > restart with Add-ons Disabled
Your calculation is likely the culprit. Try using:
bmi = weight / Math.pow(height / 100.0, 2.0);
Because both height
and 100
are integers, you were likely getting the wrong answer when dividing. However, 100.0
is a double. I suggest you make weight
a double as well. Also, the ^
operator is not for powers. Use the Math.pow()
method instead.
Assuming the renderDetailItem method has the following signature...
(rowData, sectionID, rowID, highlightRow)
Try doing this...
<TouchableHighlight key={rowID} underlayColor='#dddddd'>
INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).
You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).
To Store "Country + area + number separately". You can try using a VARCHAR(20), this allows you the ability to store international phone numbers properly, should that need arise.
in ubuntu or windows
Remove the ; from ;extension=pdo_mysql or extension=php_pdo_mysql.dll and add extension=pdo_mysql.so
restart xampp or wampp
install sudo apt-get install php-mysql
and
php artisan migrate
exit(0)
means Program(Process) terminate normally successfully..
exit(1)
means program(process) terminate normally unsuccessfully..
If you want to observe this thing you must know signal handling and process management in Unix ...
know about sigaction
, watipid()
..for()...such....API...........
Ensure your WAMP Server (or XAMP) is working, i.e. the wamp icon should be green.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
This can be improved by using the directive designed for that task.
ErrorDocument 403 /specific_page.html
Order Allow,Deny
Allow from 111.222.333.444
Where 111.222.333.444 is your static IP address.
When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.
http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
You can try
//ios
shadowOpacity: 0.3,
shadowRadius: 3,
shadowOffset: {
height: 0,
width: 0
},
//android
elevation: 1
In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.
A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.
<span align="center" style="border:1px solid red;">
This is some text in a div element!
</span>
However, the align attribute is deprecated. You should use the CSS text-align
property on the container.
<div style="text-align: center;">
<span style="border:1px solid red;">
This is some text in a div element!
</span>
</div>
No Problem You can use onClick()
function easily without using any other interference of language,
<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>
I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
This replaces double spaces in one space until you have no double spaces any more
I was getting this error by saving an object to the shared preferences as a gson converted string. The gson String was no good, so retrieving and deserializing the object was not actually working correctly. This meant any subsequent accesses to the object resulted in this error. Scary :)
I use ImageProcessorCore, mostly because it works .Net Core.
And it have more option such as converting types, cropping images and more
This can be due to system cannot find firefox installed location on path.
Try following code, which should work.
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver","<location of geckodriver>\\geckodriver.exe");
I really like the concise and functional code provided by azrafe7. So, I have changed it a little bit to convert it to an extension method:
public static class StringExtensions
{
public static string RemoveDiacritics(this string text)
{
const string SINGLEBYTE_LATIN_ASCII_ENCODING = "ISO-8859-8";
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
return Encoding.ASCII.GetString(
Encoding.GetEncoding(SINGLEBYTE_LATIN_ASCII_ENCODING).GetBytes(text));
}
}
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
A WAR (Web Archive) is a module that gets loaded into a Web container of a Java Application Server. A Java Application Server has two containers (runtime environments) - one is a Web container and the other is a EJB container.
The Web container hosts Web applications based on JSP or the Servlets API - designed specifically for web request handling - so more of a request/response style of distributed computing. A Web container requires the Web module to be packaged as a WAR file - that is a special JAR file with a web.xml
file in the WEB-INF
folder.
An EJB container hosts Enterprise java beans based on the EJB API designed to provide extended business functionality such as declarative transactions, declarative method level security and multiprotocol support - so more of an RPC style of distributed computing. EJB containers require EJB modules to be packaged as JAR files - these have an ejb-jar.xml
file in the META-INF
folder.
Enterprise applications may consist of one or more modules that can either be Web modules (packaged as a WAR file), EJB modules (packaged as a JAR file), or both of them. Enterprise applications are packaged as EAR files - these are special JAR files containing an application.xml
file in the META-INF
folder.
Basically, EAR files are a superset containing WAR files and JAR files. Java Application Servers allow deployment of standalone web modules in a WAR file, though internally, they create EAR files as a wrapper around WAR files. Standalone web containers such as Tomcat and Jetty do not support EAR files - these are not full-fledged Application servers. Web applications in these containers are to be deployed as WAR files only.
In application servers, EAR files contain configurations such as application security role mapping, EJB reference mapping and context root URL mapping of web modules.
Apart from Web modules and EJB modules, EAR files can also contain connector modules packaged as RAR files and Client modules packaged as JAR files.
Replace [True | False (default)]
Effect
1. Replace the directive element.
Dependency:
1. When replace: true, the template or templateUrl must be required.
Perhaps not the best options but just another way is to read the Windows Registry in the host machine, on elevated PowerShell prompt you can do something like this:
#Get SQL instance's Port number using Windows Registry:
$instName = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances[0]
$tcpPort = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instName\MSSQLServer\SuperSocketNetLib\Tcp").TcpPort
Write-Host The SQL Instance: `"$instName`" is listening on `"$tcpPort`" "TcpPort."
Ensure to run this PowerShell script in the Host Server (that hosts your SQL instance / SQL Server installation), which means you have to first RDP into the SQL Server/Box/VM, then run this code.
HTH
I would use your suggested code, but with a slight simplification:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();
Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.
This code example assumes (as Maarten points out below) that you've configured your java.security
file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");
.
For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.
I'm new to python too. Here is something that looks like will do what you want to
axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`
I believe this decides the size of the canvas.
> I have a .key file which is PEM formatted private key file.
> ...
> Here's some asn1parse of the .key file...
That it appears OK with asn1parse
leads me to believe its not PEM encoded.
Is there anything more I can try?
Because it appears to be ASN.1, try:
$ openssl rsa -in server.key -inform DER -modulus -noout
Notice the -inform DER
to switch between encodings.
Here a JScript variant of JohnB's answer
// Below the MSDN page for MapNetworkDrive Method with link and in case if Microsoft breaks it like every now and then the path to the documentation of now.
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
// MSDN Library -> Web Development -> Scripting -> JScript and VBScript -> Windows Scripting -> Windows Script Host -> Reference (Windows Script Host) -> Methods (Windows Script Host) -> MapNetworkDrive Method
var WshNetwork = WScript.CreateObject('WScript.Network');
function localNameInUse(localName) {
var driveIterator = WshNetwork.EnumNetworkDrives();
for (var i=0, l=driveIterator.length; i < l; i += 2) {
if (driveIterator.Item(i) == localName) {
return true;
}
}
return false;
}
function mount(localName, remoteName) {
if (localNameInUse(localName)) {
WScript.Echo('"' + localName + '" drive letter already in use.');
} else {
WshNetwork.MapNetworkDrive(localName, remoteName);
}
}
function unmount(localName) {
if (localNameInUse(localName)) {
WshNetwork.RemoveNetworkDrive(localName);
}
}
I would go with the System.Environment.NewLine
or a StringBuilder
Then you could add lines with a string builder like this:
StringBuilder sb = new StringBuilder();
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text += sb.ToString();
or NewLine like this:
textbox1.Text += System.Environment.NewLine + "brown";
Better:
StringBuilder sb = new StringBuilder(textbox1.Text);
sb.AppendLine("brown");
sb.AppendLine("brwn");
textbox1.Text = sb.ToString();
Following query can be used to get all privileges of one user .. Just provide user name in first query and you will get all privileges to that
WITH users AS (SELECT 'SCHEMA_USER' usr FROM dual), Roles AS (SELECT granted_role FROM dba_role_privs rp JOIN users ON rp.GRANTEE = users.usr UNION SELECT granted_role FROM role_role_privs WHERE role IN (SELECT granted_role FROM dba_role_privs rp JOIN users ON rp.GRANTEE = users.usr)), tab_privilage AS (SELECT OWNER, TABLE_NAME, PRIVILEGE FROM role_tab_privs rtp JOIN roles r ON rtp.role = r.granted_role UNION SELECT OWNER, TABLE_NAME, PRIVILEGE FROM Dba_Tab_Privs dtp JOIN Users ON dtp.grantee = users.usr), sys_privileges AS (SELECT privilege FROM dba_sys_privs dsp JOIN users ON dsp.grantee = users.usr) SELECT * FROM tab_privilage ORDER BY owner, table_name --SELECT * FROM sys_privileges
You should use
import Dan.Vik;
This makes the class visible and the its public methods available.
I saw different answers and came up with a class helper:
using System;
using System.Web.Mvc;
namespace MyMvcApp.Helpers {
public class LocationHelper {
public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
bool result = false;
string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);
if(viewContext == null) return false;
if(String.IsNullOrEmpty(actionName)) return false;
if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
result = true;
}
return result;
}
}
}
So in View (or master/layout) you can use it like so (Razor syntax):
<div id="menucontainer">
<ul id="menu">
<li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
@:class="selected"
}>@Html.ActionLink("Home", "Index", "Home")</li>
<li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
@:class="selected"
}>@Html.ActionLink("Logon", "Logon", "Account")</li>
<li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
@:class="selected"
}>@Html.ActionLink("About", "About", "Home")</li>
</ul>
</div>
Hope it helps.
If you are using Swift 3x and UITextView, maybe the NSForegroundColorAttributeName won't work (it didn't work for me no matter what approach I tried).
So, after some digging around I found a solution.
//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red
You can specify config file location with VM argument -Dlog4j.configuration="file:/C:/workspace3/local/log4j.properties"
In addition to the brilliant answers already provided, there are noticeable differences when it comes to extending types vs interfaces. I recently run into a couple of cases where an interface can't do the job:
You can use IPython's %pdb
magic. Just call %pdb
in IPython and when an error occurs, you're automatically dropped to ipdb
. While you don't have the stepping immediately, you're in ipdb
afterwards.
This makes debugging individual functions easy, as you can just load a file with %load
and then run a function. You could force an error with an assert
at the right position.
%pdb
is a line magic. Call it as %pdb on
, %pdb 1
, %pdb off
or %pdb 0
. If called without argument it works as a toggle.
If you mean by literally putting one on the top of the other, one on the top (Same X, Y positions, but different Z position), try using the z-index
CSS attribute. This should work (untested)
<div>
<div style='z-index: 1'>1</div>
<div style='z-index: 2'>2</div>
<div style='z-index: 3'>3</div>
<div style='z-index: 4'>4</div>
</div>
This should show 4 on the top of 3, 3 on the top of 2, and so on. The higher the z-index is, the higher the element is positioned on the z-axis. I hope this helped you :)
Assuming you have a Request object available, you can use:
string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
If it's not available, you can get to it via the context:
var request = HttpContext.Current.Request
I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy
and JoinColumn
were not working).
I think you were trying to do a bi-directional relationships.
First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post
side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:
(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private List<Post> posts;
}
public class Post {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;
}
By doing so, the table for Post
will have a column user_id
which store the relationship. Hibernate is getting the relationship by the user
in Post
(Instead of posts
in User
. You will notice the difference if you have Post
's user
but missing User
's posts
).
You have mentioned mappedBy
and JoinColumn
is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.
Edit:
Just a bit extra information on the use of mappedBy
as it is usually confusing at first. In mappedBy
, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.
According to the documentation return false;
should do the job.
We can break the $.each() loop [..] by making the callback function return false.
Return false in the callback:
function callback(indexInArray, valueOfElement) {
var booleanKeepGoing;
this; // == valueOfElement (casted to Object)
return booleanKeepGoing; // optional, unless false
// and want to stop looping
}
BTW, continue
works like this:
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
In Selenium Python it is:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
def get_selected_value_from_drop_down(self):
try:
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
return select.first_selected_option.get_attribute("value")
except NoSuchElementException, e:
print "Element not found "
print e
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C:
drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Only stopped containers can be listed using:
docker ps --filter "status=exited"
or
docker ps -f "status=exited"
Yes, you need the full path.
log = open(os.path.join(root, f), 'r')
Is the quick fix. As the comment pointed out, os.walk
decends into subdirs so you do need to use the current directory root rather than indir
as the base for the path join.
You can even use this one. worked well for me
$("#registerform").attr("action", "register.php?btnsubmit=Save")
$('#registerform').submit();
this will submit btnsubmit =Save as GET value to register.php form.
If you are fine using a graphical tool this works very well:
gitk <file>
gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!
<ion-col size="12">
<ion-card class="box-shadow ion-text-center background-size"
*ngIf="data != null"
[ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">
</ion-card>
As said already in the comments you can use the csv
library in python. csv means comma separated values which seems exactly your case: a label and a value separated by a comma.
Being a category and value type I would rather use a dictionary type instead of a list of tuples.
Anyway in the code below I show both ways: d
is the dictionary and l
is the list of tuples.
import csv
file_name = "test.txt"
try:
csvfile = open(file_name, 'rt')
except:
print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l = list()
for row in csvReader:
d[row[1]] = row[0]
l.append((row[0], row[1]))
print(d)
print(l)
To create a new branch (locally):
With the commit hash (or part of it)
git checkout -b new_branch 6e559cb
or to go back 4 commits from HEAD
git checkout -b new_branch HEAD~4
Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch
For discarding the last three commits, see Lunaryorn's answer below.
For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==
From the jQuery API Document
While JavaScript provides the
load
event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to.ready()
is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the
load
event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.
Add this to your .pro file
QMAKE_CXXFLAGS += -std=c++11
or
CONFIG += c++11
Add position: relative
to .outside
. (https://developer.mozilla.org/en-US/docs/CSS/position)
Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.
The "initial container" would be <body>
, but adding the above makes .outside
positioned.
There are two ways you can do this. You can use the throw the values into a hash for a lookup table, as suggested by the other posts. ( I'll add just another idiom. )
my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;
But if it's data of mostly word characters and not too many meta, you can dump it into a regex alternation:
use English qw<$LIST_SEPARATOR>;
my $regex_str = do {
local $LIST_SEPARATOR = '|';
"(?:@bad_params)";
};
# $front_delim and $back_delim being any characters that come before and after.
my $regex = qr/$front_delim$regex_str$back_delim/;
This solution would have to be tuned for the types of "bad values" you're looking for. And again, it might be totally inappropriate for certain types of strings, so caveat emptor.
Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.
From the documentation:
Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred.
Example:
'just sittin on the dock of the bay'.truncate(20)
Output:
just sitting on...
You can do this with jQuery's .attr
function, which will set attributes. Removing them is done via the .removeAttr
function.
//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);
//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");
I faced the same problem. I had to turn off my firewall, then it worked.
You could also open the port: http://windows.microsoft.com/en-in/windows/open-port-windows-firewall#1TC=windows-7
Another option is:
SELECT *
FROM TABLE
WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
its working with this code
text-align: justify; text-align-last: center;
Adding further...
Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)
So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.
But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.
So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.
So they always have to use the relative addressing mode and hence fpic option.
If you want something slightly more general, you can use the arguments variable like so:
function tryMe (param1, param2) {
alert(param1 + " and " + param2);
}
function callbackTester (callback) {
callback (arguments[1], arguments[2]);
}
callbackTester (tryMe, "hello", "goodbye");
But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)
Use the following to evaluate an expression (constant 0 evaluates to false).
#if 0
...
#endif
My problem was solved that way:
Your username is probably restricted, You must grant full access to the user.
The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.
<select id="test" name="form_select" onchange="showDiv()">
<option value="0">No</option>
<option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
<script>
function showDiv(){
getSelectValue = document.getElementById("test").value;
if(getSelectValue == "1"){
document.getElementById("hidden_div").style.display="block";
}else{
document.getElementById("hidden_div").style.display="none";
}
}
</script>
Andy's response worked for me by escaping $path:
git submodule foreach "(git checkout master; git pull; cd ..; git add \$path; git commit -m 'Submodule Sync')"
As Jon Skeet mentioned you can do it with a List<Track>
instead. The Track class would look something like this:
public class Track {
public int TrackID { get; set; }
public string Name { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public int PlayCount { get; set; }
public int SkipCount { get; set; }
}
And to create a track list as a List<Track>
you simply do this:
var trackList = new List<Track>();
Adding tracks can be as simple as this:
trackList.add( new Track {
TrackID = 1234,
Name = "I'm Gonna Be (500 Miles)",
Artist = "The Proclaimers",
Album = "Finest",
PlayCount = 10,
SkipCount = 1
});
Accessing tracks can be done with the indexing operator:
Track firstTrack = trackList[0];
Hope this helps.
UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID
Two good examples are regarding how you manage templates and use progressive enhancements with it. You just need a few lightweight pieces of JavaScript code to make it work perfectly.
I strongly recommend that you watch and read these articles:
Pick up any language and try to remember how you would manage your HTML file templates and what you had to do to update a single CSS class name in your DOM structure (for instance, a user clicked on a menu item and you want that marked as "selected" and update the content of the page).
With Node.js it is as simple as doing it in client-side JavaScript code. Get your DOM node and apply your CSS class to that. Get your DOM node and innerHTML your content (you will need some additional JavaScript code to do this. Read the article to know more).
Another good example, is that you can make your web page compatible both with JavaScript turned on or off with the same piece of code. Imagine you have a date selection made in JavaScript that would allow your users to pick up any date using a calendar. You can write (or use) the same piece of JavaScript code to make it work with your JavaScript turned ON or OFF.
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);
I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.
If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.
How about keeping all .php-files except for index.php above the web root? No need for any rewrite rules or programmatic kludges.
Adding the includes-folder to your include path will then help to keep things simple, no need to use absolute paths etc.
Here is a jsfiddle so you can see an example of this working.
HTML code:
<div class="circle"></div>
CSS code:
.circle {_x000D_
/*This creates a 1px solid red border around your element(div) */_x000D_
border:1px solid red;_x000D_
background-color: #FFFFFF;_x000D_
height: 100px;_x000D_
/* border-radius 50% will make it fully rounded. */_x000D_
border-radius: 50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius: 50%;_x000D_
width: 100px;_x000D_
}
_x000D_
<div class='circle'></div>
_x000D_
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
I'm surprised that this hasn't shown up yet:
In [34]: sentence = "I really like python, it's pretty awesome.".split()
In [35]: N = 4
In [36]: grams = [sentence[i:i+N] for i in xrange(len(sentence)-N+1)]
In [37]: for gram in grams: print gram
['I', 'really', 'like', 'python,']
['really', 'like', 'python,', "it's"]
['like', 'python,', "it's", 'pretty']
['python,', "it's", 'pretty', 'awesome.']
Best way to copy all files from one folder to another using PHP
<?php
$src = "/home/www/example.com/source/folders/123456"; // source folder or file
$dest = "/home/www/example.com/test/123456"; // destination folder or file
shell_exec("cp -r $src $dest");
echo "<H2>Copy files completed!</H2>"; //output when done
?>
In Windows 10 if in the prompt command the path where you start sqlite is
C:\users\USER_NAME
You can find it in the user home folder.
The .db
file is stored where you start the sqlite command.
I hope this solve the issue
The object viewer in Acrobat is good but Windjack Solution's PDF Canopener allows better inspection with an eyedropper for selecting objects on page. Also permits modifications to be made to PDF.
You're missing quotes for $_GET['sel']
- fixing this might help solving your issue sooner :)
I was experiencing the same issue in IE11. None of these answers solved my issue. After digging a bit, I noticed that the browser was running in Enterprise mode. (verify by hitting F12 and click the emulation tab, look for browser profile dropdown) The setting was locked, not allowing me to change the setting.
I was able to change the profile to Desktop after deleting CurrentVersion from the following registry key:
HKEY_CURRENT_USER\Software\Policies\Microsoft\Internet Explorer\Main\EnterpriseMode
After changing the mode to Desktop the answers on this post will work.
Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.
Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!
e.g.
# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command
~$ cd ~/working/directory
~$ scp -r [email protected]:/work/datasets/images/test/\{t1,t2,t3\} .
PS: Motivated by this great answer: scp or sftp copy multiple files with single command
Based on the comments, this also works fine in Git Bash on Windows
You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Using "Or" instead of "And" would help here, i think
I tried many different ways and this way is the only one worked for me
//check all images on the page
$('img').each(function(){
var img = new Image();
img.onload = function() {
console.log($(this).attr('src') + ' - done!');
}
img.src = $(this).attr('src');
});
You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/
An easy way to add buttons to Comment
or Un-Comment
a code block is:
You can use SpicyTaco.AutoGrid - a modified version of StackPanel
:
<st:StackPanel Orientation="Horizontal" MarginBetweenChildren="10" Margin="10">
<Button Content="Info" HorizontalAlignment="Left" st:StackPanel.Fill="Fill"/>
<Button Content="Cancel"/>
<Button Content="Save"/>
</st:StackPanel>
First button will be fill.
You can install it via NuGet:
Install-Package SpicyTaco.AutoGrid
I recommend taking a look at SpicyTaco.AutoGrid. It's very useful for forms in WPF instead of DockPanel
, StackPanel
and Grid
and solve problem with stretching very easy and gracefully. Just look at readme on GitHub.
<st:AutoGrid Columns="160,*" ChildMargin="3">
<Label Content="Name:"/>
<TextBox/>
<Label Content="E-Mail:"/>
<TextBox/>
<Label Content="Comment:"/>
<TextBox/>
</st:AutoGrid>
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
var today = new Date().toISOString().split('T')[0];
$("#datePicker").val(today);
Above code will work.
You can resize and then use imagejpeg()
Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.
imagejpeg($tn, $save, 75);
Here is a simple code snippet:
function getIndexOfSubStr(str, searchToken, preIndex, output) {
var result = str.match(searchToken);
if (result) {
output.push(result.index +preIndex);
str=str.substring(result.index+searchToken.length);
getIndexOfSubStr(str, searchToken, preIndex, output)
}
return output;
}
var str = "my name is 'xyz' and my school name is 'xyz' and my area name is 'xyz' ";
var searchToken ="my";
var preIndex = 0;
console.log(getIndexOfSubStr(str, searchToken, preIndex, []));
_x000D_
Map default.aspx as HttpHandler route and redirect to CreateThings.aspx from within the HttpHandler.
<add verb="GET" path="default.aspx" type="RedirectHandler"/>
Make sure Default.aspx does not exists physically at your application root. If it exists physically the HttpHandler will not be given any chance to execute. Physical file overrides HttpHandler mapping.
Moreover you can re-use this for pages other than default.aspx.
<add verb="GET" path="index.aspx" type="RedirectHandler"/>
//RedirectHandler.cs in your App_Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for RedirectHandler
/// </summary>
public class RedirectHandler : IHttpHandler
{
public RedirectHandler()
{
//
// TODO: Add constructor logic here
//
}
#region IHttpHandler Members
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Redirect("CreateThings.aspx");
context.Response.End();
}
#endregion
}