Declare list item components as final outside your setOnClickListener or whatever you want to apply on your list item like this:
final View yourView;
final TextView yourTextView;
And in overriding onClick or whatever method you use, just set colors as needed like this:
yourView.setBackgroundColor(Color.WHITE/*or whatever RGB suites good contrast*/);
yourTextView.setTextColor(Color.BLACK/*or whatever RGB suites good contrast*/);
Or without the final declaration, if let's say you implement an onClick() for a custom adapter to populate a list, this is what I used in getView() for my setOnClickListener/onClick():
//reset color for all list items in case any item was previously selected
for(int i = 0; i < parent.getChildCount(); i++)
{
parent.getChildAt(i).setBackgroundColor(Color.BLACK);
TextView text=(TextView) parent.getChildAt(i).findViewById(R.id.item);
text.setTextColor(Color.rgb(0,178,178));
}
//highlight currently selected item
parent.getChildAt(position).setBackgroundColor(Color.rgb(0,178,178));
TextView text=(TextView) parent.getChildAt(position).findViewById(R.id.item);
text.setTextColor(Color.rgb(0,178,178));
None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.
This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreach
loop on the .SelectedItems
, casting each item as a DataRowView
:
if (listView1.SelectedItems.Count > 0)
{
foreach (DataRowView drv in listView1.SelectedItems)
{
string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
// ... do something with these values before they are replaced
// by the next run of the loop that will get the next row
}
}
This will work, whether you have 1 item or many. It's funny that MSDN says to use ListView.SelectedListViewItemCollection
to capture listView1.SelectedItems
and iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'
.
ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType()
, and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.
Check out this tutorial on how to use the RecyclerView to do what you are looking for.
You can use __CLASS__
within a class to get the name.
If you have access to ECMA 5 you can use the some method.
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
Just for fun, here's my version of a pad function:
function pad(num, len) {
return Array(len + 1 - num.toString().length).join('0') + num;
}
It also won't truncate numbers longer than the padding length
for(int i = 0; i < getArray.size(); i++){
Object object = getArray.get(i);
// now do something with the Object
}
You need to check for the type:
The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]
In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names()
to retrieve the individual keys.
Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
If you are using vscodevim extension, then you can harness the power of vim keyboard moves. When you are on a line that you would like to bookmark, in normal mode, you can type:
m {a-z A-Z}
for a possible 52 bookmarks within a file. Small letter alphabets are for bookmarks within a single file. Capital letters preserve their marks across files.
To navigate to a bookmark from within any file, you then need to hit ' {a-z A-Z}
. I don't think these bookmarks stay across different VSCode sessions though.
More vim shortcuts here.
try
sudo dnf update
and then
sudo dnf install gcc-c++
You can generate a random alphanumeric string with:
lpad(conv(floor(rand()*pow(36,8)), 10, 36), 8, 0);
You can use it in a BEFORE INSERT
trigger and check for a duplicate in a while loop:
CREATE TABLE `vehicles` (
`plate` CHAR(8) NULL DEFAULT NULL,
`data` VARCHAR(50) NOT NULL,
UNIQUE INDEX `plate` (`plate`)
);
DELIMITER //
CREATE TRIGGER `vehicles_before_insert` BEFORE INSERT ON `vehicles`
FOR EACH ROW BEGIN
declare str_len int default 8;
declare ready int default 0;
declare rnd_str text;
while not ready do
set rnd_str := lpad(conv(floor(rand()*pow(36,str_len)), 10, 36), str_len, 0);
if not exists (select * from vehicles where plate = rnd_str) then
set new.plate = rnd_str;
set ready := 1;
end if;
end while;
END//
DELIMITER ;
Now just insert your data like
insert into vehicles(col1, col2) values ('value1', 'value2');
And the trigger will generate a value for the plate
column.
That works this way if the column allows NULLs. If you want it to be NOT NULL you would need to define a default value
`plate` CHAR(8) NOT NULL DEFAULT 'default',
You can also use any other random string generating algorithm in the trigger if uppercase alphanumerics isn't what you want. But the trigger will take care of uniqueness.
These days it shouldn't be a problem to use a C++11 compiler which includes a C99/C++11 math library. But then the question becomes: which rounding function do you pick?
C99/C++11 round()
is often not actually the rounding function you want. It uses a funky rounding mode that rounds away from 0 as a tie-break on half-way cases (+-xxx.5000
). If you do specifically want that rounding mode, or you're targeting a C++ implementation where round()
is faster than rint()
, then use it (or emulate its behaviour with one of the other answers on this question which took it at face value and carefully reproduced that specific rounding behaviour.)
round()
's rounding is different from the IEEE754 default round to nearest mode with even as a tie-break. Nearest-even avoids statistical bias in the average magnitude of numbers, but does bias towards even numbers.
There are two math library rounding functions that use the current default rounding mode: std::nearbyint()
and std::rint()
, both added in C99/C++11, so they're available any time std::round()
is. The only difference is that nearbyint
never raises FE_INEXACT.
Prefer rint()
for performance reasons: gcc and clang both inline it more easily, but gcc never inlines nearbyint()
(even with -ffast-math
)
I put some test functions on Matt Godbolt's Compiler Explorer, where you can see source + asm output (for multiple compilers). For more about reading compiler output, see this Q&A, and Matt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”,
In FP code, it's usually a big win to inline small functions. Especially on non-Windows, where the standard calling convention has no call-preserved registers, so the compiler can't keep any FP values in XMM registers across a call
. So even if you don't really know asm, you can still easily see whether it's just a tail-call to the library function or whether it inlined to one or two math instructions. Anything that inlines to one or two instructions is better than a function call (for this particular task on x86 or ARM).
On x86, anything that inlines to SSE4.1 roundsd
can auto-vectorize with SSE4.1 roundpd
(or AVX vroundpd
). (FP->integer conversions are also available in packed SIMD form, except for FP->64-bit integer which requires AVX512.)
std::nearbyint()
:
-msse4.1
.-msse4.1 -ffast-math
, and only on gcc 5.4 and earlier. Later gcc never inlines it (maybe they didn't realize that one of the immediate bits can suppress the inexact exception? That's what clang uses, but older gcc uses the same immediate as for rint
when it does inline it)std::rint
:
-msse4.1
-msse4.1
. (Without SSE4.1, inlines to several instructions)-ffast-math -msse4.1
.std::round
:
-ffast-math -msse4.1
, requiring two vector constants.std::floor
/ std::ceil
/ std::trunc
-msse4.1
-msse4.1
-ffast-math -msse4.1
int
/ long
/ long long
:You have two options here: use lrint
(like rint
but returns long
, or long long
for llrint
), or use an FP->FP rounding function and then convert to an integer type the normal way (with truncation). Some compilers optimize one way better than the other.
long l = lrint(x);
int i = (int)rint(x);
Note that int i = lrint(x)
converts float
or double
-> long
first, and then truncates the integer to int
. This makes a difference for out-of-range integers: Undefined Behaviour in C++, but well-defined for the x86 FP -> int instructions (which the compiler will emit unless it sees the UB at compile time while doing constant propagation, then it's allowed to make code that breaks if it's ever executed).
On x86, an FP->integer conversion that overflows the integer produces INT_MIN
or LLONG_MIN
(a bit-pattern of 0x8000000
or the 64-bit equivalent, with just the sign-bit set). Intel calls this the "integer indefinite" value. (See the cvttsd2si
manual entry, the SSE2 instruction that converts (with truncation) scalar double to signed integer. It's available with 32-bit or 64-bit integer destination (in 64-bit mode only). There's also a cvtsd2si
(convert with current rounding mode), which is what we'd like the compiler to emit, but unfortunately gcc and clang won't do that without -ffast-math
.
Also beware that FP to/from unsigned
int / long is less efficient on x86 (without AVX512). Conversion to 32-bit unsigned on a 64-bit machine is pretty cheap; just convert to 64-bit signed and truncate. But otherwise it's significantly slower.
x86 clang with/without -ffast-math -msse4.1
: (int/long)rint
inlines to roundsd
/ cvttsd2si
. (missed optimization to cvtsd2si
). lrint
doesn't inline at all.
x86 gcc6.x and earlier without -ffast-math
: neither way inlines
-ffast-math
: (int/long)rint
rounds and converts separately (with 2 total instructions of SSE4.1 is enabled, otherwise with a bunch of code inlined for rint
without roundsd
). lrint
doesn't inline.x86 gcc with -ffast-math
: all ways inline to cvtsd2si
(optimal), no need for SSE4.1.
AArch64 gcc6.3 without -ffast-math
: (int/long)rint
inlines to 2 instructions. lrint
doesn't inline
-ffast-math
: (int/long)rint
compiles to a call to lrint
. lrint
doesn't inline. This may be a missed optimization unless the two instructions we get without -ffast-math
are very slow.You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
A complete solution for anyone that might need it, I've used this with good results so far
JS:
$(".btn-popover-container").each(function() {
var btn = $(this).children(".popover-btn");
var titleContainer = $(this).children(".btn-popover-title");
var contentContainer = $(this).children(".btn-popover-content");
var title = $(titleContainer).html();
var content = $(contentContainer).html();
$(btn).popover({
html: true,
title: title,
content: content,
placement: 'right'
});
});
HTML:
<div class="btn-popover-container">
<button type="button" class="btn btn-link popover-btn">Button Name</button>
<div class="btn-popover-title">
Popover Title
</div>
<div class="btn-popover-content">
<form>
Or Other content..
</form>
</div>
</div>
CSS:
.btn-popover-container {
display: inline-block;
}
.btn-popover-container .btn-popover-title, .btn-popover-container .btn-popover-content {
display: none;
}
Try with this jQuery code that normalize Bootstrap carousel slide heights
function carouselNormalization() {
var items = $('#carousel-example-generic .item'), //grab all slides
heights = [], //create empty array to store height values
tallest; //create variable to make note of the tallest slide
if (items.length) {
function normalizeHeights() {
items.each(function() { //add heights to array
heights.push($(this).height());
});
tallest = Math.max.apply(null, heights); //cache largest value
items.each(function() {
$(this).css('min-height', tallest + 'px');
});
};
normalizeHeights();
$(window).on('resize orientationchange', function() {
tallest = 0, heights.length = 0; //reset vars
items.each(function() {
$(this).css('min-height', '0'); //reset min-height
});
normalizeHeights(); //run it again
});
}
}
/**
* Wait until all the assets have been loaded so a maximum height
* can be calculated correctly.
*/
window.onload = function() {
carouselNormalization();
}
_x000D_
I dont know if its too late, but i thought it would help someone else.
I wanted the same badly...found it eventually.
Maybe its not perfect,but to me its adequate(for my little dictionary app).
http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip
Its not a dump file, but a MYSQL .sql script file
The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table
I made the steps 1, 2, 3 and the 7. and I put the folder with the class files in the project build path (right click, properties, java build path, libraries, add class folder, create new folder, advanced>>, link to folder in the file system, browse,...) then restart eclipse.
Bash supports a concept called "Positional Parameters". These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.
Positional parameters are referred to by the names $0
, $1
, $2
... and so on. $0
is the name of the script itself, $1
is the first argument to the script, $2
the second, etc. $*
represents all of the positional parameters, except for $0
(i.e. starting with $1
).
An example:
#!/bin/bash
FILE="$1"
externalprogram "$FILE" <other-parameters>
For get all table size in one database you can use this query :
Exec sys.sp_MSforeachtable ' sp_spaceused "?" '
And you can change it to insert all of result into temp table and after that select from temp table.
Insert into #TempTable Exec sys.sp_MSforeachtable ' sp_spaceused "?" '
Select * from #TempTable
If you don't "care" about the data you can just do something like:
search_params = params[:search].valid_encoding? ? params[:search].gsub(/\W+/, '') : "nothing"
I just used valid_encoding?
to get passed it. Mine is a search field, and so i was finding the same weirdness over and over so I used something like: just to have the system not break. Since i don't control the user experience to autovalidate prior to sending this info (like auto feedback to say "dummy up!") I can just take it in, strip it out and return blank results.
Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.
In case the container is its own iterator, you can inherit from
collections.Iterator
. You only need to implement the next
method then.
An example is:
>>> from collections import Iterator
>>> class MyContainer(Iterator):
... def __init__(self, *data):
... self.data = list(data)
... def next(self):
... if not self.data:
... raise StopIteration
... return self.data.pop()
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
4.0
3
two
1
While you are looking at the collections
module, consider inheriting from Sequence
, Mapping
or another abstract base class if that is more appropriate. Here is an example for a Sequence
subclass:
>>> from collections import Sequence
>>> class MyContainer(Sequence):
... def __init__(self, *data):
... self.data = list(data)
... def __getitem__(self, index):
... return self.data[index]
... def __len__(self):
... return len(self.data)
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
1
two
3
4.0
NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.
1) Login to phpMyAdmin 2) From the home screen click on "More settings" (middle bottom of screen for me) 3) Click the "Features" tab/button towards the top of the screen. 4) For 20 days set the "Login cookie validity" setting to 1728000 5) Apply.
@VonC's answer to a duplicate question:
If, as commented, Paraminko does not support PPK key, the official solution, as seen here, would be to use PuTTYgen.
But you can also use the Python library CkSshKey to make that same conversion directly in your program.
See "Convert PuTTY Private Key (ppk) to OpenSSH (pem)"
import sys import chilkat key = chilkat.CkSshKey() # Load an unencrypted or encrypted PuTTY private key. # If your PuTTY private key is encrypted, set the Password # property before calling FromPuttyPrivateKey. # If your PuTTY private key is not encrypted, it makes no diffference # if Password is set or not set. key.put_Password("secret") # First load the .ppk file into a string: keyStr = key.loadText("putty_private_key.ppk") # Import into the SSH key object: success = key.FromPuttyPrivateKey(keyStr) if (success != True): print(key.lastErrorText()) sys.exit() # Convert to an encrypted or unencrypted OpenSSH key. # First demonstrate converting to an unencrypted OpenSSH key bEncrypt = False unencryptedKeyStr = key.toOpenSshPrivateKey(bEncrypt) success = key.SaveText(unencryptedKeyStr,"unencrypted_openssh.pem") if (success != True): print(key.lastErrorText()) sys.exit()
jQuery Form Validation Custom Error Message -tutsmake
$(document).ready(function(){_x000D_
$("#registration").validate({_x000D_
// Specify validation rules_x000D_
rules: {_x000D_
firstname: "required",_x000D_
lastname: "required",_x000D_
email: {_x000D_
required: true,_x000D_
email: true_x000D_
}, _x000D_
phone: {_x000D_
required: true,_x000D_
digits: true,_x000D_
minlength: 10,_x000D_
maxlength: 10,_x000D_
},_x000D_
password: {_x000D_
required: true,_x000D_
minlength: 5,_x000D_
}_x000D_
},_x000D_
messages: {_x000D_
firstname: {_x000D_
required: "Please enter first name",_x000D_
}, _x000D_
lastname: {_x000D_
required: "Please enter last name",_x000D_
}, _x000D_
phone: {_x000D_
required: "Please enter phone number",_x000D_
digits: "Please enter valid phone number",_x000D_
minlength: "Phone number field accept only 10 digits",_x000D_
maxlength: "Phone number field accept only 10 digits",_x000D_
}, _x000D_
email: {_x000D_
required: "Please enter email address",_x000D_
email: "Please enter a valid email address.",_x000D_
},_x000D_
},_x000D_
_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
.error{_x000D_
color: red;_x000D_
}_x000D_
label,_x000D_
input,_x000D_
button {_x000D_
border: 0;_x000D_
margin-bottom: 3px;_x000D_
display: block;_x000D_
width: 100%;_x000D_
}_x000D_
.common_box_body {_x000D_
padding: 15px;_x000D_
border: 12px solid #28BAA2;_x000D_
border-color: #28BAA2;_x000D_
border-radius: 15px;_x000D_
margin-top: 10px;_x000D_
background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
<h2>Registration</h2>_x000D_
<form action="#" name="registration" id="registration">_x000D_
_x000D_
<label for="firstname">First Name</label>_x000D_
<input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
_x000D_
<label for="lastname">Last Name</label>_x000D_
<input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
_x000D_
<label for="phone">Phone</label>_x000D_
<input type="text" name="phone" id="phone" placeholder="8889988899"><br> _x000D_
_x000D_
<label for="email">Email</label>_x000D_
<input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
_x000D_
<label for="password">Password</label>_x000D_
<input type="password" name="password" id="password" placeholder=""><br>_x000D_
_x000D_
<input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
None of the answers worked with fish
shell (it doesn't have the variables $$
or $0
).
This works for me (tested on sh
, bash
, fish
, ksh
, csh
, true
, tcsh
, and zsh
; openSUSE 13.2):
ps | tail -n 4 | sed -E '2,$d;s/.* (.*)/\1/'
This command outputs a string like bash
. Here I'm only using ps
, tail
, and sed
(without GNU extesions; try to add --posix
to check it). They are all standard POSIX commands. I'm sure tail
can be removed, but my sed
fu is not strong enough to do this.
It seems to me, that this solution is not very portable as it doesn't work on OS X. :(
This is an old question but a solution for those using Excel 2016 or newer is you can remove the need for nested if structures by using the new IFS( condition1, return1 [,condition2, return2] ...)
conditional.
I have formatted it to make it visually clearer on how to use it for the case of this question:
=IFS(
ISERROR(SEARCH("String1",A1))=FALSE,"Something1",
ISERROR(SEARCH("String2",A1))=FALSE,"Something2",
ISERROR(SEARCH("String3",A1))=FALSE,"Something3"
)
Since SEARCH
returns an error if a string is not found I wrapped it with an ISERROR(...)=FALSE
to check for truth and then return the value wanted. It would be great if SEARCH
returned 0 instead of an error for readability, but thats just how it works unfortunately.
Another note of importance is that IFS
will return the match that it finds first and thus ordering is important. For example if my strings were Surf, Surfing, Surfs
as String1,String2,String3
above and my cells string was Surfing
it would match on the first term instead of the second because of the substring being Surf
. Thus common denominators need to be last in the list. My IFS
would need to be ordered Surfing, Surfs, Surf
to work correctly (swapping Surfing
and Surfs
would also work in this simple example), but Surf
would need to be last.
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
In most situations the best solution is to rely on the so-called "user site" location (see the PEP for details) by running:
pip install --user package_name
Below is a more "manual" way from my original answer, you do not need to read it if the above solution works for you.
With easy_install you can do:
easy_install --prefix=$HOME/local package_name
which will install into
$HOME/local/lib/pythonX.Y/site-packages
(the 'local' folder is a typical name many people use, but of course you may specify any folder you have permissions to write into).
You will need to manually create
$HOME/local/lib/pythonX.Y/site-packages
and add it to your PYTHONPATH
environment variable (otherwise easy_install will complain -- btw run the command above once to find the correct value for X.Y).
If you are not using easy_install
, look for a prefix option, most install scripts let you specify one.
With pip you can use:
pip install --install-option="--prefix=$HOME/local" package_name
All the above answers assumes the earth is a sphere. However, a more accurate approximation would be that of an oblate spheroid.
a= 6378.137#equitorial radius in km
b= 6356.752#polar radius in km
def Distance(lat1, lons1, lat2, lons2):
lat1=math.radians(lat1)
lons1=math.radians(lons1)
R1=(((((a**2)*math.cos(lat1))**2)+(((b**2)*math.sin(lat1))**2))/((a*math.cos(lat1))**2+(b*math.sin(lat1))**2))**0.5 #radius of earth at lat1
x1=R*math.cos(lat1)*math.cos(lons1)
y1=R*math.cos(lat1)*math.sin(lons1)
z1=R*math.sin(lat1)
lat2=math.radians(lat2)
lons2=math.radians(lons2)
R1=(((((a**2)*math.cos(lat2))**2)+(((b**2)*math.sin(lat2))**2))/((a*math.cos(lat2))**2+(b*math.sin(lat2))**2))**0.5 #radius of earth at lat2
x2=R*math.cos(lat2)*math.cos(lons2)
y2=R*math.cos(lat2)*math.sin(lons2)
z2=R*math.sin(lat2)
return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5
Have you considered using the "xcopy" command?
The xcopy command will do all that for you.
You can also drag a tap gesture recogniser to the image view in Storyboard
. Then create an action by ctrl + drag
to the code.
Configurations above didn't work for me. I tried a lot of combinations of keys, this one work fine:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>mydomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
The various primitive wrappers, e.g., Integer
are immutable so there's really not a more concise way to do what you're asking unless you can do it with something like AtomicLong. I can give that a go in a minute and update. BTW, Hashtable is a part of the Collections Framework.
You could use \r\n
, or System.Environment.NewLine
.
Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.
An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.
Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.
Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.
After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.
Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).
Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.
Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.
Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).
I was using the $('div').attr('style', '');
technique and it wasn't working in IE8.
I outputted the style attribute using alert()
and it was not stripping out inline styles.
.removeAttr
ended up doing the trick in IE8.
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...
The correct way when you want to remove all kinds of whitespaces (based on this SO answer) is:
extension String {
var stringByRemovingWhitespaces: String {
let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
return components.joinWithSeparator("")
}
}
extension String {
func removingWhitespaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
}
This answer was posted when the question was about removing all whitespaces, the question was edited to only mention leading whitespaces. If you only want to remove leading whitespaces use the following:
extension String {
func removingLeadingSpaces() -> String {
guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
return self
}
return String(self[index...])
}
}
The top answer to this question seemed a bit buggy when I tried it -- here's my solution which I've found to be more robust:
boolean_arg=""
arg_with_value=""
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-b|--boolean-arg)
boolean_arg=true
shift
;;
-a|--arg-with-value)
arg_with_value="$2"
shift
shift
;;
-*)
echo "Unknown option: $1"
exit 1
;;
*)
arg_num=$(( $arg_num + 1 ))
case $arg_num in
1)
first_normal_arg="$1"
shift
;;
2)
second_normal_arg="$1"
shift
;;
*)
bad_args=TRUE
esac
;;
esac
done
# Handy to have this here when adding arguments to
# see if they're working. Just edit the '0' to be '1'.
if [[ 0 == 1 ]]; then
echo "first_normal_arg: $first_normal_arg"
echo "second_normal_arg: $second_normal_arg"
echo "boolean_arg: $boolean_arg"
echo "arg_with_value: $arg_with_value"
exit 0
fi
if [[ $bad_args == TRUE || $arg_num < 2 ]]; then
echo "Usage: $(basename "$0") <first-normal-arg> <second-normal-arg> [--boolean-arg] [--arg-with-value VALUE]"
exit 1
fi
If you're using Owl Carousel 2
, then you should use the following:
$(".category-wrapper").owlCarousel({
items : 4,
loop : true,
margin : 30,
nav : true,
smartSpeed :900,
navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
});
Educated guess: You have a ISO-8859-1 encoded pound sign in a UTF-8 encoded page.
Make sure your data is in the right encoding and everything will work fine.
You can use kill-port. In firstly, kill exist port and in secondly create server and listen.
const kill = require('kill-port')
kill(port, 'tcp')
.then((d) => {
/**
* Create HTTP server.
*/
server = http.createServer(app);
server.listen(port, () => {
console.log(`api running on port:${port}`);
});
})
.catch((e) => {
console.error(e);
})
That is nice question :)
When you have situation with 1 cell (A1), it is important to identify if second declared cell is not empty (sh.Range("A1").End(xlDown)
). If it is true it means your range got out of control :) Look at code below:
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Arkusz1")
Dim k As Long
If IsEmpty(sh.Range("A1").End(xlDown)) = True Then
k = 1
Else
k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
End If
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
I just solved this and wanted to share. This works with Bootstrap 4. It works with img
but I didn't test it with video
. Here is the HAML and SCSS
HAML
.container
.detail-img.d-flex.align-items-center
%img{src: 'http://placehold.it/1000x700'}
SCSS
.detail-img { // simulate background: center/cover
max-height: 400px;
overflow: hidden;
img {
width: 100%;
}
}
/* simulate background: center/cover */_x000D_
.center-cover { _x000D_
max-height: 400px;_x000D_
overflow: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.center-cover img {_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="center-cover d-flex align-items-center">_x000D_
<img src="http://placehold.it/1000x700">_x000D_
</div>_x000D_
</div>
_x000D_
Not possible with standard unix commands. You might have luck with a file recovery utility. Also, be aware, using rm changes the table of contents to mark those blocks as available to be overwritten, so simply using your computer right now risks those blocks being overwritten permanently. If it's critical data, you should turn off the computer before the file sectors gets overwritten. Good luck!
Some restore utility: http://www.ubuntugeek.com/recover-deleted-files-with-foremostscalpel-in-ubuntu.html
Forum where this was previously answered: http://webcache.googleusercontent.com/search?q=cache:m4hiPw-_GekJ:ubuntuforums.org/archive/index.php/t-1134955.html+&cd=1&hl=en&ct=clnk&gl=us
I think the secret guru register is the expression = register. It can be used for creative mappings.
:inoremap \d The current date <c-r>=system("date")<cr>
You can use it in conjunction with your system as above or get responses from custom VimL functions etc.
or just ad hoc stuff like
<c-r>=35+7<cr>
Well I guess I have found the solution for my own question, here is how I did it:
Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.
So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.
The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!
If you add:
jquery.form.min.js
You can simply do this:
<script>
$('#myform').ajaxForm(function(response) {
alert(response);
});
// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>
You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.
A Looper has a synchronized
MessageQueue
that's used to process Messages placed on the queue.
It implements a Thread
Specific Storage Pattern.
Only one Looper
per Thread
. Key methods include prepare()
,loop()
and quit()
.
prepare()
initializes the current Thread
as a Looper
. prepare()
is static
method that uses the ThreadLocal
class as shown below.
public static void prepare(){
...
sThreadLocal.set
(new Looper());
}
prepare()
must be called explicitly before running the event loop. loop()
runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop()
method dispatches the Message to its target handlerquit()
shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special messageLooper
can be programmed in a Thread
via several steps
Extend Thread
Call Looper.prepare()
to initialize Thread as a Looper
Create one or more Handler
(s) to process the incoming messages
Looper.loop()
to process messages until the loop is told to quit()
. The man page makes it pretty clear. If you want to pass two arguments (-rpath
and .
) to the linker you can write
-Wl,-rpath,.
or alternatively
-Wl,-rpath -Wl,.
The arguments -Wl,-rpath .
you suggested do NOT make sense to my mind. How is gcc supposed to know that your second argument (.
) is supposed to be passed to the linker instead of being interpreted normally? The only way it would be able to know that is if it had insider knowledge of all possible linker arguments so it knew that -rpath
required an argument after it.
Just for your App is on the iOS Simulator
Enter
console.log (Realm.defaultPath)
in the code eg: App.js
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
All the above solutions are quite large, i wanted to give my 2 cents on this.
I am only checking if the value inputed is a number or not, and checking if it's not blank, that's all.
Here is the html:
<input type="text" ng-keypress="CheckNumber()"/>
Here is the JS:
$scope.CheckKey = function () {
if (isNaN(event.key) || event.key === ' ' || event.key === '') {
event.returnValue = '';
}
};
It's quite simple.
I belive this wont work on Paste tho, just so it's known.
For Paste, i think you would need to use the onChange event and parse the whole string, quite another beast the tamme. This is specific for typing.
UPDATE for Paste: just add this JS function:
$scope.CheckPaste = function () {
var paste = event.clipboardData.getData('text');
if (isNaN(paste)) {
event.preventDefault();
return false;
}
};
And the html input add the trigger:
<input type="text" ng-paste="CheckPaste()"/>
I hope this helps o/
For Facebook share with an image without an API and using a #
to deep link into a sub page, the trick was to share the image as picture=
The variable mainUrl
would be http://yoururl.com/
var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);
var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);
var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);
var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;
// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
return false;
});
// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
return false;
});
Note that in both CMake and Autotools you don't always have to set the installation path at configure time. You can use DESTDIR
at install time (see also here) instead as in:
make DESTDIR=<installhere> install
See also this question which explains the subtle difference between DESTDIR
and PREFIX
.
This is intended for staged installs and to allow for storing programs in a different location from where they are run e.g. /etc/alternatives
via symbolic links.
However, if your package is relocatable and doesn't need any hard-coded (prefix) paths set via the configure stage you may be able to skip it. So instead of:
cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install
you would run:
cmake . && make DESTDIR=/usr all install
Note that, as user7498341 points out, this is not appropriate for cases where you really should be using PREFIX
.
You can use the Screen.PrimaryScreen.Bounds
to retrieve the size of the primary monitor (or inspect the Screen
object to retrieve all monitors). Use those with MyForms.Bounds
to figure out where to place your form.
Why not use a PdfPTable
object for this?
Create a fixed width table and use a float array to set the widths of the columns
PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);
addCell(table, "SER.\nNO.", 2);
addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);
addCell(table, "DESCRIPTION OF GOODS", 2);
addCell(table, "LINE DOC. RECL DATE", 1);
addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);
addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);
....
private static void addCell(PdfPTable table, string text, int rowspan)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPCell cell = new PdfPCell(new Phrase(text, times));
cell.Rowspan = rowspan;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.AddCell(cell);
}
have a look at this tutorial too...
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
Here is the code to get the Dimensions of the complete view of the device.
var windowSize = Dimensions.get("window");
Use it like this:
width=windowSize.width,heigth=windowSize.width/0.565
df.insert(0, 'New_ID', range(880, 880 + len(df)))
df
You can add them in your htaccess file or vhost configuration.
See here : http://httpd.apache.org/docs/2.2/mod/mod_expires.html
But unless you own those domains .. they are our of your control.
First go to https://myaccount.google.com/lesssecureapps and make Allow less secure apps true.
Then use the below code. This below code will work only if your from email address is from gmail.
static void SendEmail()
{
string mailBodyhtml =
"<p>some text here</p>";
var msg = new MailMessage("[email protected]", "[email protected]", "Hello", mailBodyhtml);
msg.To.Add("[email protected]");
msg.IsBodyHtml = true;
var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "[email protected]" then host should be "smtp.hotmail.com"**
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential("[email protected]", "password");
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
Console.WriteLine("Email Sent Successfully");
}
See here: Git doesn't clone all branches on subsequent clones?
If you really want this by pulling branches instead of push --mirror
, you can have a look here:
"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones
This answer provides detailed steps on how to achieve that relatively easily:
Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.
If it's part of your site then refer to it with the file system path, not the web URL. /var/www/...
, rather than http://domain.tld/...
.
if we use bootstrap our text will be green or red depending on the result
HTML
<div class="col-12 col-md-6 col-lg-4 mb-3">
<label class="form-group d-block mb-0">
<span class="text-secondary d-block font-weight-semibold mb-1">New Password</span>
<input type="password" id="txtNewPassword" class="form-control">
</label>
</div>
<div class="col-12 col-md-6 col-lg-4 mb-3">
<label class="form-group d-block mb-0">
<span class="text-secondary d-block font-weight-semibold mb-1">Confirm Password
</span>
<input class="form-control" type="password" id="txtConfirmPassword" onkeyup="checkPasswordMatch();">
</label>
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
CSS
.text-success {
color: #28a745;
}
.text-danger {
color: #dc3545;
}
JS
function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
$("#divCheckPasswordMatch").html("Passwords do not match!").addClass('text-danger').removeClass('text-success');
else
$("#divCheckPasswordMatch").html("Passwords match.").addClass('text-success').removeClass('text-danger');
}
I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.
Code with Excepion
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
After Fixes:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}
find out commit id
git reflog
recover local branch you deleted by mistake
git branch need-recover-branch-name commitId
push need-recover-branch-name again if you deleted remote branch too before
git push origin need-recover-branch-name
Finally I able resolve this issue.
Do not install Android SDK with studio package, unkcheck the option when asked.
Steps to resolve:
I tried other solutions, run as Administrator and proxy setting but nothing worked.
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
$("#iframe-id").load( function() {
$("#iframe-id").contents().on("click", ".child-node", function() {
//do something
});
});
HTML:
<button type="submit" name="submit" class="button">
<img src="images/free.png" />
</button>
CSS:
.button { }
Unbelievable, but on httpd 2.2 on centos 6.4 this works.
Export env vars in /etc/sysconfig/httpd
export mydocroot=/var/www/html
Then simply do this...
<VirtualHost *:80>
DocumentRoot ${mydocroot}
</VirtualHost>
Then finally....
service httpd restart;
#include <stdio.h>
int main() {
printf("gcc version: %d.%d.%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);
return 0;
}
This problem mostly occurs due to the error in setText()
method
Solution is simple put your Integer
value by converting into string
type
as
textview.setText(Integer.toString(integer_value));
Building off @Marc's solution -- since the bullet character is rendered differently with different fonts and browsers, I used the following css3 technique with border-radius to make a bullet that I have more control over:
li:before {
content: '';
background-color: #898989;
display: inline-block;
position: relative;
height: 12px;
width: 12px;
border-radius: 6px;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
-moz-background-clip: padding;
-webkit-background-clip: padding-box;
background-clip: padding-box;
margin-right: 4px;
top: 2px;
}
[Necromancer mode on]
Stumbled upon this question when was looking for fast, modern, platform independent and elegant solution. Didnt like any of above, cpp-netlib would be the winner but it has horrific memory vulnerability in "decoded" function. So I came up with boost's spirit qi/karma solution.
namespace bsq = boost::spirit::qi;
namespace bk = boost::spirit::karma;
bsq::int_parser<unsigned char, 16, 2, 2> hex_byte;
template <typename InputIterator>
struct unescaped_string
: bsq::grammar<InputIterator, std::string(char const *)> {
unescaped_string() : unescaped_string::base_type(unesc_str) {
unesc_char.add("+", ' ');
unesc_str = *(unesc_char | "%" >> hex_byte | bsq::char_);
}
bsq::rule<InputIterator, std::string(char const *)> unesc_str;
bsq::symbols<char const, char const> unesc_char;
};
template <typename OutputIterator>
struct escaped_string : bk::grammar<OutputIterator, std::string(char const *)> {
escaped_string() : escaped_string::base_type(esc_str) {
esc_str = *(bk::char_("a-zA-Z0-9_.~-") | "%" << bk::right_align(2,0)[bk::hex]);
}
bk::rule<OutputIterator, std::string(char const *)> esc_str;
};
The usage of above as following:
std::string unescape(const std::string &input) {
std::string retVal;
retVal.reserve(input.size());
typedef std::string::const_iterator iterator_type;
char const *start = "";
iterator_type beg = input.begin();
iterator_type end = input.end();
unescaped_string<iterator_type> p;
if (!bsq::parse(beg, end, p(start), retVal))
retVal = input;
return retVal;
}
std::string escape(const std::string &input) {
typedef std::back_insert_iterator<std::string> sink_type;
std::string retVal;
retVal.reserve(input.size() * 3);
sink_type sink(retVal);
char const *start = "";
escaped_string<sink_type> g;
if (!bk::generate(sink, g(start), input))
retVal = input;
return retVal;
}
[Necromancer mode off]
EDIT01: fixed the zero padding stuff - special thanks to Hartmut Kaiser
EDIT02: Live on CoLiRu
For
throw new Exception('test exception');
I got 500 (but didn't see anything in the browser), until I put
php_flag display_errors on
in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only
You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.
Try using the exact, or absolute, path.
In Bash, you can also redirect to a subshell using process substitution:
command > >(stdlog pipe) 2> >(stderr pipe)
For the case at hand:
command 2> >(grep 'something') >/dev/null
Following way very slowly in the running
mAgendaListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view.setBackgroundColor(Color.RED);
for(int i=0; i<parent.getChildCount(); i++)
{
if(i == position)
{
parent.getChildAt(i).setBackgroundColor(Color.BLUE);
}
else
{
parent.getChildAt(i).setBackgroundColor(Color.BLACK);
}
}
Replaced by the following
int pos = 0;
int save = -1;
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Always set the item clicked blue background
view.setBackgroundColor(Color.BLUE);
if (pos == 0) {
if (save != -1) {
parent.getChildAt(save).setBackgroundColor(Color.BLACK);
}
save = position;
pos++;
Log.d("Pos = 0", "Running");
} else {
parent.getChildAt(save).setBackgroundColor(Color.BLACK);
save = position;
pos = 0;
Log.d("Pos # 0", "Running");
}
If you don't care about data:
Best way would be to drop the database and run syncdb
again. Or you can run:
For Django >= 1.5
python manage.py flush
For Django < 1.5
python manage.py reset appname
(you can add --no-input
to the end of the command for it to skip the interactive prompt.)
If you do care about data:
From the docs:
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.
https://docs.djangoproject.com/en/dev/ref/django-admin/
Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database
People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.
I wanted a solution to have the output from stdout plus stderr written into a log file and stderr still on console. So I needed to duplicate the stderr output via tee.
This is the solution I found:
command 3>&1 1>&2 2>&3 1>>logfile | tee -a logfile
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
You could also do it with PowerShell:
Get-WmiObject win32_service -filter "Name='My Service'" `
| Invoke-WmiMethod -Name Change `
-ArgumentList @($null,$null,$null,$null,$null, `
"C:\Program Files (x86)\My Service\NewName.EXE")
Or:
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
-Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"
There is an "auth" parameter for Basic Auth:
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
Source/Docs: https://github.com/mzabriskie/axios
Example:
await axios.post(session_url, {}, {
auth: {
username: uname,
password: pass
}
});
# Creates a list containing 5 lists initialized to 0
Matrix = [[0]*5]*5
Be careful about this short expression, see full explanation down in @F.J's answer
Try
<IfModule mod_rewrite.so>
...
...
...
</IfModule>
instead of <IfModule mod_rewrite.c>
open looks in the current working directory, which in your case is ~
, since you are calling your script from the ~
directory.
You can fix the problem by either
cd
ing to the directory containing data.csv
before executing the script, or
by using the full path to data.csv
in your script, or
open
and os.listdir
) may be affected by this."location of notepad file" > notepad Filename
C:\Users\Desktop\Anaconda> notepad myfile
works for me! :)
def formatE_decimal(x, prec=2):
""" Examples:
>>> formatE_decimal('0.1613965',10)
'1.6139650000E-01'
>>> formatE_decimal('0.1613965',5)
'1.61397E-01'
>>> formatE_decimal('0.9995',2)
'1.00E+00'
"""
xx=decimal.Decimal(x) if type(x)==type("") else x
tup = xx.as_tuple()
xx=xx.quantize( decimal.Decimal("1E{0}".format(len(tup[1])+tup[2]-prec-1)), decimal.ROUND_HALF_UP )
tup = xx.as_tuple()
exp = xx.adjusted()
sign = '-' if tup.sign else ''
dec = ''.join(str(i) for i in tup[1][1:prec+1])
if prec>0:
return '{sign}{int}.{dec}E{exp:+03d}'.format(sign=sign, int=tup[1][0], dec=dec, exp=exp)
elif prec==0:
return '{sign}{int}E{exp:+03d}'.format(sign=sign, int=tup[1][0], exp=exp)
else:
return None
I'm seeing a lot of answers proposing a build or a re-build but just in case this don't fix your problem just notice that IDEA can detect a method but it will not compile in case you have a new
before as it will be expecting the instance.
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
Check out this really quick and to the point tutorial on how to get the scroll view working and fully scrollable with auto layout. Now, the only thing that is still leaving me puzzled is why the scroll view content size is always larger then necessary..
http://samwize.com/2014/03/14/how-to-use-uiscrollview-with-autolayout/
"Case" can return single value only, but you can use complex type:
create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;
Here's another; a C# port of the Ooura FFT. It's reasonably fast. The package also includes overlap/add convolution and some other DSP stuff, under the MIT license.
https://github.com/hughpyle/inguz-DSPUtil/blob/master/Fourier.cs
You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:
if x == 1 or y == 1 or z == 1:
x
and y
are otherwise evaluated on their own (False
if 0
, True
otherwise).
You can shorten that using a containment test against a tuple:
if 1 in (x, y, z):
or better still:
if 1 in {x, y, z}:
using a set
to take advantage of the constant-cost membership test (in
takes a fixed amount of time whatever the left-hand operand is).
When you use or
, python sees each side of the operator as separate expressions. The expression x or y == 1
is treated as first a boolean test for x
, then if that is False, the expression y == 1
is tested.
This is due to operator precedence. The or
operator has a lower precedence than the ==
test, so the latter is evaluated first.
However, even if this were not the case, and the expression x or y or z == 1
was actually interpreted as (x or y or z) == 1
instead, this would still not do what you expect it to do.
x or y or z
would evaluate to the first argument that is 'truthy', e.g. not False
, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).
So for the values x = 2; y = 1; z = 0
, x or y or z
would resolve to 2
, because that is the first true-like value in the arguments. Then 2 == 1
would be False
, even though y == 1
would be True
.
The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3
would fail for the same reasons. Use x == 1 or x == 2 or x == 3
or x in {1, 2, 3}
.
Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.
Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.
Without IoC:
public class MyClass
{
IMyService _myService;
public MyClass()
{
_myService = new SomeConcreteService();
}
}
With IoC container:
public class MyClass
{
IMyService _myService;
public MyClass(IMyService myService)
{
_myService = myService;
}
}
Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)
With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.
Using StructureMap, configuring the container looks like this:
StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();
So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.
That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).
Final step: when you create your MyClass, you would do this:
var myClass = ObjectFactory.GetInstance<MyClass>();
Hope that helps. Feel free to e-mail me.
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.
You need to individually add/remove unit of time in date object
var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
It is easy to write text to a canvas. Lets say that you canvas is declared like below.
<html>
<canvas id="YourCanvas" width="500" height="500">
Your Internet Browser does not support HTML5 (Get a new Browser)
</canvas>
</html>
This part of the code returns a variable into canvas which is a representation of your canvas in HTML.
var c = document.getElementById("YourCanvas");
The following code returns the methods for drawing lines, text, fills to your canvas.
var ctx = canvas.getContext("2d");
<script>
ctx.font="20px Times Roman";
ctx.fillText("Hello World!",50,100);
ctx.font="30px Verdana";
var g = ctx.createLinearGradient(0,0,c.width,0);
g.addColorStop("0","magenta");
g.addColorStop("0.3","blue");
g.addColorStop("1.0","red");
ctx.fillStyle=g; //Sets the fille of your text here. In this case it is set to the gradient that was created above. But you could set it to Red, Green, Blue or whatever.
ctx.fillText("This is some new and funny TEXT!",40,190);
</script>
There is a beginners guide out on Amazon for the kindle http://www.amazon.com/HTML5-Canvas-Guide-Beginners-ebook/dp/B00JSFVY9O/ref=sr_1_4?ie=UTF8&qid=1398113376&sr=8-4&keywords=html5+canvas+beginners that is well worth the money. I purchased it a couple of days ago and it showed me a lot of simple techniques that were very useful.
Through Code:
Your best bet is to use parse inside a try-catch
and catch exception in case of failed parsing. (I am not aware of any TryParse
method).
(Using JSON.Net)
Simplest way would be to Parse
the string using JToken.Parse
, and also to check if the string starts with {
or [
and ends with }
or ]
respectively (added from this answer):
private static bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}
The reason to add checks for {
or [
etc was based on the fact that JToken.Parse
would parse the values such as "1234"
or "'a string'"
as a valid token. The other option could be to use both JObject.Parse
and JArray.Parse
in parsing and see if anyone of them succeeds, but I believe checking for {}
and []
should be easier. (Thanks @RhinoDevel for pointing it out)
Without JSON.Net
You can utilize .Net framework 4.5 System.Json namespace ,like:
string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
//Invalid json format
Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
}
(But, you have to install System.Json
through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343
on Package Manager Console) (taken from here)
Non-Code way:
Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:
You can use this:
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('video'));
One function can do the job,
void free_list(node *pHead)
{
node *pNode = pHead, *pNext;
while (NULL != pNode)
{
pNext = pNode->next;
free(pNode);
pNode = pNext;
}
}
Simplified way (Used only on small arrays because of performance issues. In large arrays you have to make the filter manually via code):
See: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
@Pipe({
name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field : string, value : string): any[] {
if (!items) return [];
if (!value || value.length == 0) return items;
return items.filter(it =>
it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
}
}
Usage:
<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>
If you use a variable as a second argument, don't use quotes.
Basically you do the counts as sub-queries within a standard select.
An example would be the following, this returns 1 row, two columns
SELECT
(SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
(SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().
Ex:
Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.
You can write code below:
for (int key : map.keySet()) {
if (map.get(key) == value) {
res.add(key);
}
}
rather than use entrySet() below:
for (Map.Entry s : map.entrySet()) {
if ((int)s.getValue() == value) {
res.add((int)s.getKey());
}
}
Hope it helps :)
How about sys.exit()
from the module sys
.
If sys.exit()
is executed from within a thread it will close that thread only.
This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?
Use typeof
when you want to get the type at compilation time. Use GetType
when you want to get the type at execution time. There are rarely any cases to use is
as it does a cast and, in most cases, you end up casting the variable anyway.
There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use as
.
Foo foo = obj as Foo;
if (foo != null)
// your code here
This only uses one cast whereas this approach:
if (obj is Foo)
Foo foo = (Foo)obj;
requires two.
Update (Jan 2020):
Example:
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}
Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.
If you are designing your Javafx application using SceneBuilder
then use -fx-text-fill
(if not available as option then write it in style input box) as style and give the color you want,it will change the text color of your Textfield
.
I came here for the same problem and solved it in this way.
Another approach to sort HTML table. (based on W3.JS HTML Sort)
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
element.addEventListener("click", function() {_x000D_
w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
});_x000D_
});
_x000D_
th {_x000D_
cursor: pointer;_x000D_
background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
<!-- _x000D_
<tr>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
</tr> _x000D_
-->_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Address</th>_x000D_
<th>Sales Person</th>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>user:2911002</td>_x000D_
<td>UK</td>_x000D_
<td>Melissa</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2201002</td>_x000D_
<td>France</td>_x000D_
<td>Justin</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901092</td>_x000D_
<td>San Francisco</td>_x000D_
<td>Judy</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2801002</td>_x000D_
<td>Canada</td>_x000D_
<td>Skipper</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901009</td>_x000D_
<td>Christchurch</td>_x000D_
<td>Alex</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
There is nothing particularly tricky about the example you posted.
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
Think of it this way:
var x = (1 < 2) ? true : false;
Could also be written as:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
x = (1 < 2); // x will be set to "true"
Hundred lines of code for this basic function???
Just a simple method:
protected static int calculateDayDifference(Date dateAfter, Date dateBefore){
return (int)(dateAfter.getTime()-dateBefore.getTime())/(1000 * 60 * 60 * 24);
// MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
}
If your end goal is to add elements to your page, just manipulate the DOM directly. Don't use string concatenation to try to create HTML - what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:
var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";
Then, later when you put the element in your page, instead of setting the innerHTML
of the parent element, call appendChild()
:
mySelectElement.appendChild(x);
Add the following code to the top of your Markdown files to get MathJax rendering support
<style TYPE="text/css">
code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'] // removed 'code' entry
}
});
MathJax.Hub.Queue(function() {
var all = MathJax.Hub.getAllJax(), i;
for(i = 0; i < all.length; i += 1) {
all[i].SourceElement().parentNode.className += ' has-jax';
}
});
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full"></script>
and then `$x^2$` or `$$x^2$$` will render as expected :-)
You can always install a local version of MathJax if you don't want to use the online distribution, but you might need to host it through a local webserver.
UPDATE: these days I just use pandoc instead of canonical markdown, but the above is still useful.
[Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!
First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.
The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "
Source and example of polyfill here:
http://www.programmerinterview.com/index.php/html5/html5-polyfill/
The statement you're executing is valid. The error seems to mean that Toad is including the trailing semicolon as part of the command, which does cause an ORA-00911
when it's included as part of a statement - since it is a statement separator in the client, not part of the statement itself.
It may be the following commented-out line that is confusing Toad (as described here); or it might be because you're trying to run everything as a single statement, in which case you can try to use the run script command (F9) instead of run statement (F5).
Just removing the commented-out line makes the problem go away, but if you also saw this with an actual commit then it's likely to be that you're using the wrong method to run the statements.
There is a bit more information about how Toad parses the semicolons in a comment on this related question, but I'm not familiar enough with Toad to go into more detail.
Checking it out in python3:
python -V
Python 3.6.5
Example1:
.
+-- parent.py
+-- start.py
+-- sub
+-- relative.py
- start.py
import sub.relative
- parent.py
print('Hello from parent.py')
- sub/relative.py
from .. import parent
If we run it like this(just to make sure PYTHONPATH is empty):
PYTHONPATH='' python3 start.py
Output:
Traceback (most recent call last):
File "start.py", line 1, in <module>
import sub.relative
File "/python-import-examples/so-example-v1/sub/relative.py", line 1, in <module>
from .. import parent
ValueError: attempted relative import beyond top-level package
If we change import in sub/relative.py
- sub/relative.py
import parent
If we run it like this:
PYTHONPATH='' python3 start.py
Output:
Hello from parent.py
Example2:
.
+-- parent.py
+-- sub
+-- relative.py
+-- start.py
- parent.py
print('Hello from parent.py')
- sub/relative.py
print('Hello from relative.py')
- sub/start.py
import relative
from .. import parent
Run it like:
PYTHONPATH='' python3 sub/start.py
Output:
Hello from relative.py
Traceback (most recent call last):
File "sub/start.py", line 2, in <module>
from .. import parent
ValueError: attempted relative import beyond top-level package
If we change import in sub/start.py
:
- sub/start.py
import relative
import parent
Run it like:
PYTHONPATH='' python3 sub/start.py
Output:
Hello from relative.py
Traceback (most recent call last):
File "sub/start.py", line 3, in <module>
import parent
ModuleNotFoundError: No module named 'parent'
Run it like:
PYTHONPATH='.' python3 sub/start.py
Output:
Hello from relative.py
Hello from parent.py
Also it's better to use import from root folder, i.e.:
- sub/start.py
import sub.relative
import parent
Run it like:
PYTHONPATH='.' python3 sub/start.py
Output:
Hello from relative.py
Hello from parent.py
You can use this to add numbers:
var x = +num1 + +num2;
The simple approach of just averaging them has weird edge cases with angles when they wrap from 359' back to 0'.
A much earlier question on SO asked about finding the average of a set of compass angles.
An expansion of the approach recommended there for spherical coordinates would be:
$count = 0;
$output ='';
$ischeckedvalueArray = array();
for ($i=0; $i < sizeof($array); $i++) {
$eachArrayValue = $array[$i];
if(! in_array($eachArrayValue, $ischeckedvalueArray)) {
for( $j=$i; $j < sizeof($array); $j++) {
if ($array[$j] === $eachArrayValue) {
$count++;
}
}
$ischeckedvalueArray[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated ". $count."<br/>";
$count = 0;
}
}
echo $output;
Deleting metadata folder might not work in this case. Or eclipse -clean command. Or reinstall eclipse might not solve this.
Instead try deleting other java versions you might have in your machine.
Check what you have right now using this:
/usr/libexec/java_home -V
Delete other java versions which you don't want, following below command:
sudo rm -rf /System/Library/Java/JavaVirtualMachines/java-version.jdk
This should resolve your issue.
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.
java.util.TimeZone represents a time zone offset, and also figures out daylight savings.
sample code:
TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);
Another solution that I found to this issue is by wrapping the Text inside a View. Also set the style of the View to flex: 1.
if( receiver.isOrderedBroadcast() ){
// receiver object is registered
}
else{
// receiver object is not registered
}
I got this issue when the Virtualbox had the wrong networking. I've updated to NAT and was able to get on internet and download packages from us.archive.ubuntu.com
Have you seen this question and its answer?
You can set a globally valid value for you app like this:
app.value('key', 'value');
and then use it in your services. You could move this code to a config.js file and execute it on page load or another convenient moment.
You could better use the localStorage of the web browser.
You can find a reference here
An ObservableCollection
works essentially like a regular collection except that it implements
the interfaces:
As such it is very useful when you want to know when the collection has changed. An event is triggered that will tell the user what entries have been added/removed or moved.
More importantly they are very useful when using databinding on a form.
You don't need to iterate the array. Just:
>>> x = ['[email protected]', '[email protected]']
>>> x
['[email protected]', '[email protected]']
>>> x.remove('[email protected]')
>>> x
['[email protected]']
This will remove the first occurence that matches the string.
EDIT: After your edit, you still don't need to iterate over. Just do:
index = initial_list.index(item1)
del initial_list[index]
del other_list[index]
Solved, this is how your parse their html results:
table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
cells = row.findAll("td")
if len(cells) == 9:
summons = cells[1].find(text=True)
plateType = cells[2].find(text=True)
vDate = cells[3].find(text=True)
location = cells[4].find(text=True)
borough = cells[5].find(text=True)
vCode = cells[6].find(text=True)
amount = cells[7].find(text=True)
print amount
This solution is for Vue-2 users:
vue-2
if you don't like to keep your files in static
folder (relevant info), orvue-2
& vue-cli-3
if you don't like to keep your files in public
folder (static
folder is renamed to public
):The simple solution is :)
<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}
If you like to keep your static images in static/assets/img
or public/assets/img
folder, then just do:
<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./
Unfortunately, No. You will you have to go through a loop and count them.
EDIT :
var arrLength = arr.filter(Number);
alert(arrLength);
Run ./mnistCUDNN
in /usr/src/cudnn_samples_v7/mnistCUDNN
Here is an example:
cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30 Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0, boardGroupID=0
Using device 0
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
You could check for the count of the Object keys:
if (Object.keys(a).length > 0) {
// not empty
}
Use Access's VBA function Replace(text, find, replacement)
:
Dim result As String
result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")
I made this change and now it works for me.
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
You should go the submodule dir and run git status
.
You may see a lot of files were deleted. You may run
git reset .
git checkout .
git fetch -p
git rm --cached submodules
//submoudles is your name
git submoudle add ....
For POI 3.17 this worked for me
switch (cellh.getCellTypeEnum()) {
case FORMULA:
if (cellh.getCellFormula().indexOf("LINEST") >= 0) {
value = Double.toString(cellh.getNumericCellValue());
} else {
value = XLS_getDataFromCellValue(evaluator.evaluate(cellh));
}
break;
case NUMERIC:
value = Double.toString(cellh.getNumericCellValue());
break;
case STRING:
value = cellh.getStringCellValue();
break;
case BOOLEAN:
if(cellh.getBooleanCellValue()){
value = "true";
} else {
value = "false";
}
break;
default:
value = "";
break;
}
From a module:
UserFormName.UserForm_Initialize
Just make sure that in your userform, you update the sub like so:
Public Sub UserForm_Initialize()
so it can be called from outside the form.
Alternately, if the Userform hasn't been loaded:
UserFormName.Show
will end up calling UserForm_Initialize
because it loads the form.
Request.RawUrl
I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.
To workaround I use JPQL CONCAT function (this code emulate start with):
@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
private static final String QUERY = "select b from Branch b"
+ " left join b.filial f"
+ " where f.id = ?1 and b.id like CONCAT(?2, '%')";
@Query(QUERY)
List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}
I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html
This is the simplest way to remove all the packages. From an admin prompt:
wmic product where "name like 'microsoft visual%'" call uninstall /nointeractive
Repeat for SQL etc by replacing visual%
in above command with sql
.
The plugin's author says you should use "square brackets without the quotes", []
http://bassistance.de/2011/10/07/release-validation-plugin-1-9-0/
Release: Validation Plugin 1.9.0: "...Another change should make the setup of forms with hidden elements easier, these are now ignored by default (option “ignore” has “:hidden” now as default). In theory, this could break an existing setup. In the unlikely case that it actually does, you can fix it by setting the ignore-option to “[]” (square brackets without the quotes)."
To change this setting for all forms:
$.validator.setDefaults({
ignore: [],
// any other default options and/or rules
});
(It is not required that .setDefaults()
be within the document.ready
function)
OR for one specific form:
$(document).ready(function() {
$('#myform').validate({
ignore: [],
// any other options and/or rules
});
});
EDIT:
See this answer for how to enable validation on some hidden fields but still ignore others.
EDIT 2:
Before leaving comments that "this does not work", keep in mind that the OP is simply asking about the jQuery Validate plugin and his question has nothing to do with how ASP.NET, MVC, or any other Microsoft framework can alter this plugin's normal expected behavior. If you're using a Microsoft framework, the default functioning of the jQuery Validate plugin is over-written by Microsoft's unobtrusive-validation
plugin.
If you're struggling with the unobtrusive-validation
plugin, then please refer to this answer instead: https://stackoverflow.com/a/11053251/594235
On a Windows machine I was able to log to to ssh from git bash with
ssh vagrant@VAGRANT_SERVER_IP
without providing a password
Using Bitvise SSH client on window
Server host: VAGRANT_SERVER_IP
Server port: 22
Username: vagrant
Password: vagrant
SELECT
resultIn the Navigator, right click on the table > Table Data Export Wizard
All columns and rows are included by default, so click on Next.
Select File Path, type, Field Separator (by default it is ;
, not ,
!!!) and click on Next.
Click Next > Next > Finish and the file is created in the specified location
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
Depsite the year old topic, this one seems to have the most of the answers for this problem. Just ren into it. Tried everything, starting from "cleans", ending with total ".metadata" and another server setup, and nothing worked.
Than i remembered that a while ago i'w decided to clean up some of the "pom" warnings, and there were some suggestions on "apply to the project data". Then i started to browse the folder project, where i found the source of my headache - a file called ".tomcatplugin". After deleting it(it was the third hour of my attempts of resolving the problem) everything worked like a charm.
I had the same problem, except I have a table with 2 billion rows, so the log file would grow to no end if I did this, even with the recovery model set to Bulk-Logging:
insert into newtable select * from oldtable
So I operate on blocks of data. This way, if the transfer is interupted, you just restart it. Also, you don't need a log file as big as the table. You also seem to get less tempdb I/O, not sure why.
set identity_insert newtable on
DECLARE @StartID bigint, @LastID bigint, @EndID bigint
select @StartID = isNull(max(id),0) + 1
from newtable
select @LastID = max(ID)
from oldtable
while @StartID < @LastID
begin
set @EndID = @StartID + 1000000
insert into newtable (FIELDS,GO,HERE)
select FIELDS,GO,HERE from oldtable (NOLOCK)
where id BETWEEN @StartID AND @EndId
set @StartID = @EndID + 1
end
set identity_insert newtable off
go
You might need to change how you deal with IDs, this works best if your table is clustered by ID.
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset" refers to the integer key of a numeric array, and "index" refers to the string key of an associative array.
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Simply,
SELECT TIME(column_name), DATE(column_name)
I did as follows in XML - with 0 padding around the image and ripple ontop of the image:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/my_image"
android:clickable="true"
android:focusable="true"
android:src="?android:attr/selectableItemBackground" />
Make sure you have the right selector, and then wait until the page is ready and that the element exists until you run the function.
$(function(){
$('#searchBar').val('hi')
});
As Derek points out, the ID is wrong as well.
Change to $('#main_search')
use state is not always needed you can just simply do this
let paymentList = [
{"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]
then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.
<div className="card-body">
<div className="table-responsive">
<table className="table table-striped">
<thead>
<tr>
<th>Transaction ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{
paymentList.map((payment, key) => (
<tr key={key}>
<td>{payment.txnid}</td>
<td>{payment.fname}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("Synchronous\(jsonResult)")
} catch {
print(error.localizedDescription)
}
}.resume()
If you are looking to use modules and want it to compile to a single JavaScript file you can do the following:
tsc -out _compiled/main.js Main.ts
Main.ts
///<reference path='AnotherNamespace/ClassOne.ts'/>
///<reference path='AnotherNamespace/ClassTwo.ts'/>
module MyNamespace
{
import ClassOne = AnotherNamespace.ClassOne;
import ClassTwo = AnotherNamespace.ClassTwo;
export class Main
{
private _classOne:ClassOne;
private _classTwo:ClassTwo;
constructor()
{
this._classOne = new ClassOne();
this._classTwo = new ClassTwo();
}
}
}
ClassOne.ts
///<reference path='CommonComponent.ts'/>
module AnotherNamespace
{
export class ClassOne
{
private _component:CommonComponent;
constructor()
{
this._component = new CommonComponent();
}
}
}
CommonComponent.ts
module AnotherNamespace
{
export class CommonComponent
{
constructor()
{
}
}
}
You can read more here: http://www.codebelt.com/typescript/javascript-namespacing-with-typescript-internal-modules/
There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.
WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
"return arguments[0].parentNode;", myElement);
WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));
WebElement
Note: As you can see, for the JavaScript version you'll need the driver
. If you don't have direct access to it, you can retrieve it from the WebElement
using:
WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();
is there a way to disable it?
Yes, you only need to use the JSON_UNESCAPED_SLASHES
flag.
!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)
json_encode($str, JSON_UNESCAPED_SLASHES);
If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).
<?php
/*
* Escaping the reverse-solidus character ("/", slash) is optional in JSON.
*
* This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
*
* @link http://stackoverflow.com/a/10210433/367456
*/
$url = 'http://www.example.com/';
echo json_encode($url), "\n";
echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";
Example Output:
"http:\/\/www.example.com\/"
"http://www.example.com/"
I would call it nib.py. And I would also name the class Nib.
In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following:
from nib import Nib
from foo import Foo
from spam.eggs import Eggs, FriedEggs
It's a bit like emulating the Java way. One class per file. But with the added flexibility, that you can allways add another class to a single file if it makes sense.
A very direct way is to just use read.table
on your character vector:
> read.table(text = text, sep = ".", colClasses = "character")
V1 V2 V3 V4
1 F US CLE V13
2 F US CA6 U13
3 F US CA6 U13
4 F US CA6 U13
5 F US CA6 U13
6 F US CA6 U13
7 F US CA6 U13
8 F US CA6 U13
9 F US DL U13
10 F US DL U13
11 F US DL U13
12 F US DL Z13
13 F US DL Z13
colClasses
needs to be specified, otherwise F
gets converted to FALSE
(which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )
Alternatively, you can use my cSplit
function, like this:
cSplit(as.data.table(text), "text", ".")
# text_1 text_2 text_3 text_4
# 1: F US CLE V13
# 2: F US CA6 U13
# 3: F US CA6 U13
# 4: F US CA6 U13
# 5: F US CA6 U13
# 6: F US CA6 U13
# 7: F US CA6 U13
# 8: F US CA6 U13
# 9: F US DL U13
# 10: F US DL U13
# 11: F US DL U13
# 12: F US DL Z13
# 13: F US DL Z13
Or, separate
from "tidyr", like this:
library(dplyr)
library(tidyr)
as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
# V_1 V_2 V_3 V_4
# 1 F US CLE V13
# 2 F US CA6 U13
# 3 F US CA6 U13
# 4 F US CA6 U13
# 5 F US CA6 U13
# 6 F US CA6 U13
# 7 F US CA6 U13
# 8 F US CA6 U13
# 9 F US DL U13
# 10 F US DL U13
# 11 F US DL U13
# 12 F US DL Z13
# 13 F US DL Z13
Here are some options to convert the .csv files into one data.frame using R base and some of the available packages for reading files in R.
This is slower than the options below.
# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))
Edit: - A few more extra choices using data.table
and readr
A fread()
version, which is a function of the data.table
package. This is by far the fastest option in R.
library(data.table)
DT = do.call(rbind, lapply(files, fread))
# The same using `rbindlist`
DT = rbindlist(lapply(files, fread))
Using readr, which is another package for reading csv files. It's slower than fread
, faster than base R but has different functionalities.
library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()
Based on Kenton's answer, a simpler yet working solution looks like:
message Foo {
oneof optional_baz { // "optional_" prefix here just serves as an indicator, not keyword in proto2
int32 baz = 1;
}
}
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
gnu/stubs-32.h
is not directed included in programms. It's a back-end type header file of gnu/stubs.h
, just like gnu/stubs-64.h
. You can install the multilib
package to add both.
group by fV.tier_id, f.form_template_id
My solution breaks down in 3 parts: the state of the user is stored in a service, in the run method you watch when the route changes and you check if the user is allowed to access the requested page, in your main controller you watch if the state of the user change.
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
You should create a service (I will name it Auth
) which will handle the user object and have a method to know if the user is logged or not.
service:
.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})
From your app.run
, you should listen the $routeChangeStart
event. When the route will change, it will check if the user is logged (the isLoggedIn
method should handle it). It won't load the requested route if the user is not logged and it will redirect the user to the right page (in your case login).
The loginController
should be used in your login page to handle login. It should just interract with the Auth
service and set the user as logged or not.
loginController:
.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
//submit
$scope.login = function () {
// Ask to the server, do your job and THEN set the user
Auth.setUser(user); //Update the state of the user in the app
};
}])
From your main controller, you could listen if the user state change and react with a redirection.
.controller('mainCtrl', ['$scope', 'Auth', '$location', function ($scope, Auth, $location) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);
You can use docker update --restart=on-failure <container ID or name>
.
On top of what the name suggests, on-failure
will not only restart the container on failure, but also at system boot.
Per the documentation, there are multiple restart options:
Flag Description
no Do not automatically restart the container. (the default)
on-failure Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
You can easily reach them by using the Run window and entering:
shell:startup
and
shell:common startup
With Behaviors and Actions in Blend for Visual Studio 2013 you can use the InvokeCommandAction. I tried this with the Drop event and although no CommandParameter was specified in the XAML, to my surprise, the Execute Action parameter contained the DragEventArgs. I presume this would happen for other events but have not tested them.
Some JavaScript engines can parse that format directly, which makes the task pretty easy:
function convertDate(inputFormat) {_x000D_
function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
var d = new Date(inputFormat)_x000D_
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
In my opinion, there is no problem in using var
heavily. It is not a type of its own (you are still using static typing). Instead it's just a time saver, letting the compiler figure out what to do.
Like any other time saver (such as auto properties for example), it is a good idea to understand what it is and how it works before using it everywhere.
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
>>> L = range (11)
>>> [ x if x%2 == 1 else None for x in L ]
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
You can also get the value by the following way
$(document).ready(function(){
$("#start").click(function(){
alert($(this).find("input[class='myClass']").val());
});
});
Scala function :
def countChange(money: Int, coins: List[Int]): Int = {
def loop(money: Int, lcoins: List[Int], count: Int): Int = {
// if there are no more coins or if we run out of money ... return 0
if ( lcoins.isEmpty || money < 0) 0
else{
if (money == 0 ) count + 1
/* if the recursive subtraction leads to 0 money left - a prefect division hence return count +1 */
else
/* keep iterating ... sum over money and the rest of the coins and money - the first item and the full set of coins left*/
loop(money, lcoins.tail,count) + loop(money - lcoins.head,lcoins, count)
}
}
val x = loop(money, coins, 0)
Console println x
x
}
if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):
// tsconfig.json
{
"compilerOptions": {
...
"rootDir": ".",
"paths": {
"lib/*": [
"src/org/global/lib/*"
]
}
}
}
// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');
resolve: {
plugins: [
new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
]
}
This should about cut it (i'll leave the error handling to you):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
My problem (and so solution) was yet different from those described above.
I wasn't using models.py
file, but created a models
directory and created the my_model.py
file there, where I put my model. Django couldn't find my model so it wrote that there are no migrations to apply.
My solution was: in the my_app/models/__init__.py
file I added this line:
from .my_model import MyModel
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
One liners to start or stop mongodb service using command line;
NET START MONGODB
NET STOP MONGODB
I use this myself, it does work.
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
For those coming across this question more recently, .values
is deprecated as of Sequelize 3.0.0. Use .get()
instead to get the plain javascript object. So the above code would change to:
var nodedata = node.get({ plain: true });
Sequelize docs here
Java 8
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 45
System.out.println(LocalDateTime.now().getSecond()); // 32
Calendar
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
Joda Time
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 45
System.out.println(new DateTime().getSecondOfMinute()); // 32
Java 8
// 07:48:55.056
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
// 7:48:55
System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());
// 07:48:55
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
// 074855
System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));
// 07:48:55
System.out.println(new Date().toString().substring(11, 20));
An 8-digit hex color value is a representation of ARGB (Alpha, Red, Green, Blue), whereas a 6-digit value just assumes 100% opacity (fully opaque) and defines just the RGB values. So to make this be fully opaque, you can either use #FF555555, or just #555555. Each 2-digit hex value is one byte, representing values from 0-255.
Using the stat.* bit masks does seem to me the most portable and explicit way of doing this. But on the other hand, I often forget how best to handle that. So, here's an example of masking out the 'group' and 'other' permissions and leaving 'owner' permissions untouched. Using bitmasks and subtraction is a useful pattern.
import os
import stat
def chmodme(pn):
"""Removes 'group' and 'other' perms. Doesn't touch 'owner' perms."""
mode = os.stat(pn).st_mode
mode -= (mode & (stat.S_IRWXG | stat.S_IRWXO))
os.chmod(pn, mode)
You should apply the following styles:
#button:active {
vertical-align: top;
padding: 8px 13px 6px;
}
This will give you the necessary effect, demo here.
The Revert command in the context menu ignores your edits and returns the working copy to its previous state. You may also select the desired revision other than the "Head" when you "CheckOut" from the repository.
If you want to skip running and compiling tests:
mvn -Dmaven.test.skip=true install
If you want to compile but not run tests:
mvn install -DskipTests