You did not post the code generated by the compiler, so there' some guesswork here, but even without having seen it, one can say that this:
test rax, 1
jpe even
... has a 50% chance of mispredicting the branch, and that will come expensive.
The compiler almost certainly does both computations (which costs neglegibly more since the div/mod is quite long latency, so the multiply-add is "free") and follows up with a CMOV. Which, of course, has a zero percent chance of being mispredicted.
In python, extracting substring form string can be done using findall
method in regular expression (re
) module.
>>> import re
>>> s = 'gfgfdAAA1234ZZZuijjk'
>>> ss = re.findall('AAA(.+)ZZZ', s)
>>> print ss
['1234']
Wrote the below function that allows me to quickly check to see if an index exists; works just like OBJECT_ID.
CREATE FUNCTION INDEX_OBJECT_ID (
@tableName VARCHAR(128),
@indexName VARCHAR(128)
)
RETURNS INT
AS
BEGIN
DECLARE @objectId INT
SELECT @objectId = i.object_id
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(@tableName)
AND i.name = @indexName
RETURN @objectId
END
GO
EDIT: This just returns the OBJECT_ID of the table, but it will be NULL if the index doesn't exist. I suppose you could set this to return index_id, but that isn't super useful.
This is the correct way:
You should declare the length of the array after "="
Veicle[] cars = new Veicle[N];
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeIf you prefer a non-visual mode method and acknowledge the line numbers, I would like to suggest you an another straightforward way.
Example
I want to delete text from line 45 to line 101.
My method suggests you to type a below command in command-mode:
45Gd101G
It reads:
Go to line 45 (
45G
) then delete text (d
) from the current line to the line 101 (101G
).
Note that on vim
you might use gg
in stead of G
.
Compare to the @Bonnie Varghese's answer which is:
:45,101d[enter]
The command above from his answer requires 9 times typing including enter, where my answer require 8 - 10 times typing. Thus, a speed of my method is comparable.
Personally, I myself prefer 45Gd101G
over :45,101d
because I like to stick to the syntax of the vi's command, in this case is:
+---------+----------+--------------------+
| syntax | <motion> | <operator><motion> |
+---------+----------+--------------------+
| command | 45G | d101G |
+---------+----------+--------------------+
You can do this dynamically that way:
mkdir($dirname);
@touch($dirname . "/.htaccess");
$f = fopen($dirname . "/.htaccess", "w");
fwrite($f, "deny from all");
fclose($f);
According to the CSS basic box model, an element's width and height are applied to its content box. Padding falls outside of that content box and increases the element's overall size.
As a result, if you set an element with padding to 100% width, its padding will make it wider than 100% of its containing element. In your context, inputs become wider than their parent.
You can change the way the box model treats padding and width. Set the box-sizing
CSS property to border-box
to prevent padding from affecting an element's width or height:
border-box : The width and height properties include the padding and border, but not the margin... Note that padding and border will be inside of the box.
Note the browser compatibility of box-sizing
(IE8+).
At the time of this edit, no prefixes are necessary.
Paul Irish and Chris Coyier recommend the "inherited" usage below:
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
For reference, see:
* { Box-sizing: Border-box } FTW
Inheriting box-sizing Probably Slightly Better Best-Practice.
Here's a demonstration in your specific context:
#mainContainer {
line-height: 20px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: rgba(0, 50, 94, 0.2);
margin: 20px auto;
display: table;
-moz-border-radius: 15px;
border-style: solid;
border-color: rgb(40, 40, 40);
border-radius: 2px 5px 2px 5px / 5px 2px 5px 2px;
border-radius: 2px;
border-radius: 2px 5px / 5px;
box-shadow: 0 5px 10px 5px rgba(0, 0, 0, 0.2);
}
.loginForm {
width: 320px;
height: 250px;
padding: 10px 15px 25px 15px;
overflow: hidden;
}
.login-fields > .login-bottom input#login-button_normal {
float: right;
padding: 2px 25px;
cursor: pointer;
margin-left: 10px;
}
.login-fields > .login-bottom input#login-remember {
float: left;
margin-right: 3px;
}
.spacer {
padding-bottom: 10px;
}
input[type=text],
input[type=password] {
width: 100%;
height: 30px;
padding: 5px 10px;
background-color: rgb(215, 215, 215);
line-height: 20px;
font-size: 12px;
color: rgb(136, 136, 136);
border-radius: 2px 2px 2px 2px;
border: 1px solid rgb(114, 114, 114);
box-shadow: 0 1px 0 rgba(24, 24, 24, 0.1);
box-sizing: border-box;
}
input[type=text]:hover,
input[type=password]:hover,
label:hover ~ input[type=text],
label:hover ~ input[type=password] {
background: rgb(242, 242, 242);
!important;
}
input[type=submit]:hover {
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), inset 0 -10px 10px rgba(255, 255, 255, 0.1);
}
.login-top {
height: auto;/*85px;*/
}
.login-bottom {
padding: 35px 15px 0 0;
}
_x000D_
<div id="mainContainer">
<div id="login" class="loginForm">
<div class="login-top">
</div>
<form class="login-fields" onsubmit="alert('test'); return false;">
<div id="login-email" class="login-field">
<label for="email" style="-moz-user-select: none;-webkit-user-select: none;" onselectstart="return false;">E-mail address</label>
<span><input name="email" id="email" type="text" /></span>
</div>
<div class="spacer"></div>
<div id="login-password" class="login-field">
<label for="password" style="-moz-user-select: none;-webkit-user-select: none;" onselectstart="return false;">Password</label>
<span><input name="password" id="password" type="password" /></span>
</div>
<div class="login-bottom">
<input type="checkbox" name="remember" id="login-remember" />
<label for="login-remember" style="-moz-user-select: none;-webkit-user-select: none;" onselectstart="return false;">Remember my email</label>
<input type="submit" name="login-button" id="login-button_normal" style="cursor: pointer" value="Log in" />
</div>
</form>
</div>
</div>
_x000D_
Alternatively, rather than adding padding to the <input>
elements themselves, style the <span>
elements wrapping the inputs. That way, the <input>
elements can be set to width:100%
without being affected by any additional padding. Example below:
#login-form {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: rgba(0, 50, 94, 0.2);
margin: 20px auto;
padding: 10px 15px 25px 15px;
border: 4px solid rgb(40, 40, 40);
box-shadow: 0 5px 10px 5px rgba(0, 0, 0, 0.2);
border-radius: 2px;
width: 320px;
}
label span {
display: block;
padding: .3em 1em;
background-color: rgb(215, 215, 215);
border-radius: .25em;
border: 1px solid rgb(114, 114, 114);
box-shadow: 0 1px 0 rgba(24, 24, 24, 0.1);
margin: 0 0 1em;
}
label span:hover {
background: rgb(242, 242, 242);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), inset 0 -10px 10px rgba(255, 255, 255, 0.1);
}
input[type=text],
input[type=password] {
background: none;
border: none;
width: 100%;
height: 2em;
line-height: 2em;
font-size: 12px;
color: rgb(136, 136, 136);
outline: none;
}
.login-bottom {
margin: 2em 1em 0 0;
}
input#login-button {
float: right;
padding: 2px 25px;
}
input#login-remember {
float: left;
margin-right: 3px;
}
_x000D_
<form id="login-form">
<label>E-mail address
<span><input name="email" type="text" /></span>
</label>
<label>Password
<span><input name="password" type="password" /></span>
</label>
<div class="login-bottom">
<label>
<input type="checkbox" name="remember" id="login-remember" />Remember my email
</label>
<input type="submit" name="login-button" id="login-button" value="Log in" />
</div>
</form>
_x000D_
As of docker-compose file version 3.2, you can specify a volume mount of type "bind" (instead of the default type "volume") that allows you to mount a single file into the container. Search for "bind mount" in the docker-compose volume docs: https://docs.docker.com/compose/compose-file/#volumes
In my case, I was trying to mount a single ".secrets" file into my application that contained secrets for local development and testing only. In production, my application fetches these secrets from AWS instead.
If I mounted this file as a volume using the shorthand syntax:
volumes:
- ./.secrets:/data/app/.secrets
Docker would create a ".secrets" directory inside the container instead of mapping to the file outside of the container. My code would then raise an error like "IsADirectoryError: [Errno 21] Is a directory: '.secrets'".
I fixed this by using the long-hand syntax instead, specifying my secrets file using a read-only "bind" volume mount:
volumes:
- type: bind
source: ./.secrets
target: /data/app/.secrets
read_only: true
Now Docker correctly mounts my .secrets file into the container, creating a file inside the container instead of a directory.
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.
The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)
From: http://technet.microsoft.com/en-us/library/ee681792.aspx:
"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."
Edit:
Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE
returned.
If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week
which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll
.
Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206
I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.
Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.
See https://code.angularjs.org/1.4.10/docs/api/ngRoute/provider/$routeProvider
[reloadOnSearch=true] - {boolean=} - reload route when only $location.search() or $location.hash() changes.
Setting this to false did the trick without all of the above for me.
COUNT(expresion)
returns the count of of rows where expresion
is not null. So SELECT COUNT (COL_NAME) FROM TABLE WHERE COL_NAME IS NULL
will return 0, because you are only counting col_name
where col_name
is null, and a count of nothing but nulls is zero. COUNT(*)
will return the number of rows of the query:
SELECT COUNT (*) FROM TABLE WHERE COL_NAME IS NULL
The other two queries are probably not returning any rows, since they are trying to match against strings with one blank character, and your dump query indicates that the column is actually holding nulls.
If you have rows with variable strings of space characters that you want included in the count, use:
SELECT COUNT (*) FROM TABLE WHERE trim(COL_NAME) IS NULL
trim(COL_NAME)
will remove beginning and ending spaces. If the string is nothing but spaces, then the string becomes ''
(empty string), which is equivalent to null in Oracle.
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
@studentid INT, --Input parameter , Studentid of the student
@studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROM tbl_Students WHERE studentid=@studentid
END
The Python time.strftime
docs say:
When used with the strptime() function, the
%p
directive only affects the output hour field if the%I
directive is used to parse the hour.
Sure enough, changing your %H
to %I
makes it work.
SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC
To all: don't forget about case MotionEvent.ACTION_CANCEL:
it calls in 30% swipes without ACTION_UP
and its equal to ACTION_UP in this case
The answer of this question is very simple,Whatever we can do with interface can be done with abstract class Agree...so when to use interfaces,the answer lies in C# restriction of multiple inheritance. When you have only contracts(abstracts) to declare and want your sub-classes implement it go with interfaces, because if you use abstract class in this case, you can not inherit from one more class and you are stuck if want to inherit from one more class,but you can implement as many interfaces.
Most likely, the userdata()
function is returning an object, not a string. Look into the documentation (or var_dump the return value) to find out which value you need to use.
You can increase client_max_body_size and upload_max_filesize + post_max_size all day long. Without adjusting HTTP timeout it will never work.
//You need to adjust this, and probably on PHP side also. client_body_timeout 2min // 1GB fileupload
Mutations expect two arguments: state
and payload
, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.
The easiest way to pass a number of parameters is to destruct them:
mutations: {
authenticate(state, { token, expiration }) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expiration);
}
}
Then later on in your actions you can simply
store.commit('authenticate', {
token,
expiration,
});
I downloaded the latest JDK 7u10. Once you do that, try running your jar, It should execute.
I found a fix that while it's not actually using ajax it does allow you to use a javascript call to request the download and then get a callback when the download actually starts. I found this helpful if the link runs a server side script that takes a little bit to compose the file before sending it. so you can alert them that it's processing, and then when it does finally send the file remove that processing notification. which is why I wanted to try to load the file via ajax to begin with so that I could have an event happen when the file is requested and another when it actually starts downloading.
the js on the front page
function expdone()
{
document.getElementById('exportdiv').style.display='none';
}
function expgo()
{
document.getElementById('exportdiv').style.display='block';
document.getElementById('exportif').src='test2.php?arguments=data';
}
the iframe
<div id="exportdiv" style="display:none;">
<img src="loader.gif"><br><h1>Generating Report</h1>
<iframe id="exportif" src="" style="width: 1px;height: 1px; border:0px;"></iframe>
</div>
then the other file:
<!DOCTYPE html>
<html>
<head>
<script>
function expdone()
{
window.parent.expdone();
}
</script>
</head>
<body>
<iframe id="exportif" src="<?php echo "http://10.192.37.211/npdtracker/exportthismonth.php?arguments=".$_GET["arguments"]; ?>"></iframe>
<script>document.getElementById('exportif').onload= expdone;</script>
</body></html>
I think there's a way to read get data using js so then no php would be needed. but I don't know it off hand and the server I'm using supports php so this works for me. thought I'd share it in case it helps anyone.
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if
(or elif
or else
) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.
It can also be done using a single line with while
loops and if
like this:
if (blah)
doThis();
It also works with while
loops.
Anyway, here is how to fix it: Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New: Variable name: _JAVA_OPTIONS Variable value: -Xmx512M
OR
Change the ant call as shown as below.
<exec
**<arg value="-J-Xmx512m" />**
</exec>
It worked for me.
By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
String username = (String)request.getAttribute("un");
session.setAttribute("UserName", username);
}
You can use Length annotation for a column. By using it you can maximize or minimize column length. Length annotation only be used for Strings
.
@Column(name = "NAME", nullable = false, length = 50)
@Length(max = 50)
public String getName() {
return this.name;
}
If you have the luxury of creating the yaml file yourself, or if you don't require any of these features of regular yaml, I recommend using strictyaml
instead of the standard pyyaml
package.
In short, default yaml has some serious flaws in terms of security, interface, and predictability. strictyaml
is a subset of the yaml spec that does not have those issues (and is better documented).
You can read more about the problems with regular yaml here
OPINION: strictyaml
should be the default implementation of yaml and the old yaml spec should be obsoleted.
SELECT Call.ID, Call.date, Call.phone_number
FROM Call
LEFT OUTER JOIN Phone_Book
ON (Call.phone_number=Phone_book.phone_number)
WHERE Phone_book.phone_number IS NULL
Should remove the subquery, allowing the query optimiser to work its magic.
Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).
Based on your comments looks like this is what you need:
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost/ [NC]
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,NC]
I have tested it on my localhost and it seems to be working fine.
Your second version is less efficient because it creates an extra string object when there is simply no need to do so.
Immutability means that your first version behaves the way you expect and is thus the approach to be preferred.
I found a better way of doing this
function genrateJSONEngine() {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) {
var array = workbook.Sheets[y];
var first = array[0].join()
var headers = first.split(',');
var jsonData = [];
for (var i = 1, length = array.length; i < length; i++) {
var myRow = array[i].join();
var row = myRow.split(',');
var data = {};
for (var x = 0; x < row.length; x++) {
data[headers[x]] = row[x];
}
jsonData.push(data);
}
This approach, df1 != df2
, works only for dataframes with identical rows and columns. In fact, all dataframes axes are compared with _indexed_same
method, and exception is raised if differences found, even in columns/indices order.
If I got you right, you want not to find changes, but symmetric difference. For that, one approach might be concatenate dataframes:
>>> df = pd.concat([df1, df2])
>>> df = df.reset_index(drop=True)
group by
>>> df_gpby = df.groupby(list(df.columns))
get index of unique records
>>> idx = [x[0] for x in df_gpby.groups.values() if len(x) == 1]
filter
>>> df.reindex(idx)
Date Fruit Num Color
9 2013-11-25 Orange 8.6 Orange
8 2013-11-25 Apple 22.1 Red
To redirect stderr to a file, display stdout to screen, and also save stdout to a file:
./aaa.sh 2>ccc.out | tee ./bbb.out
EDIT: To display both stderr and stdout to screen and also save both to a file, you can use bash's I/O redirection:
#!/bin/bash
# Create a new file descriptor 4, pointed at the file
# which will receive stderr.
exec 4<>ccc.out
# Also print the contents of this file to screen.
tail -f ccc.out &
# Run the command; tee stdout as normal, and send stderr
# to our file descriptor 4.
./aaa.sh 2>&4 | tee bbb.out
# Clean up: Close file descriptor 4 and kill tail -f.
exec 4>&-
kill %1
If you're using .NET 4.5 and want to use async then you can use HttpClient
in System.Net.Http
:
using (var httpClient = new HttpClient())
{
var json = await httpClient.GetStringAsync("url");
// Now parse with JSON.Net
}
in
Python strings and listsHere are a few useful examples that speak for themselves concerning the in
method:
"foo" in "foobar"
True
"foo" in "Foobar"
False
"foo" in "Foobar".lower()
True
"foo".capitalize() in "Foobar"
True
"foo" in ["bar", "foo", "foobar"]
True
"foo" in ["fo", "o", "foobar"]
False
["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]
Caveat. Lists are iterables, and the in
method acts on iterables, not just strings.
The two forms are the same with one exception: temporarily, the new (Object *)
has an undefined value when the creation and assignment are separate. The compiler may combine them back together, since the undefined pointer is not particularly useful. This does not relate to global variables (unless the declaration is global, in which case it's still true for both forms).
public void breadthFirstSearch(Node root, Consumer<String> c) {
List<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node n = queue.remove(0);
c.accept(n.value);
if (n.left != null)
queue.add(n.left);
if (n.right != null)
queue.add(n.right);
}
}
And the Node:
public static class Node {
String value;
Node left;
Node right;
public Node(final String value, final Node left, final Node right) {
this.value = value;
this.left = left;
this.right = right;
}
}
Reading Datetime value From Excel sheet : Try this will be work.
string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();
double date = double.Parse(sDate);
var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
To solve problems like this I'm using CSS - fastest & simplest way I think... Just modify it by your needs...
@media only screen and (max-width: 480px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 480px) and (max-width: 768px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#your_id {width:000px;height:000px;}
}
@media only screen and (min-width: 959px) {
#your_id {width:000px;height:000px;}
}
I am one of the engineers on the Fresco project. So obviously I'm biased.
But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.
I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco
.
Fresco offers features that Picasso, UIL, and Glide do not yet have:
There are many others (see our documentation), but these are the most important.
>>> import ctypes
>>> s = 'abcdef'
>>> mutable = ctypes.create_string_buffer(s)
>>> for i in range(0,len(s),2):
>>> mutable[i], mutable[i+1] = mutable[i+1], mutable[i]
>>> s = mutable.value
>>> print s
badcfe
Agree that unless you use these often there is no need for an external library. Although similar solutions are available, I see that some of them are tricky to follow here is a gist that has a solution with comments if you're trying to understand what is happening.
const cars = [{
'make': 'audi',
'model': 'r8',
'year': '2012'
}, {
'make': 'audi',
'model': 'rs5',
'year': '2013'
}, {
'make': 'ford',
'model': 'mustang',
'year': '2012'
}, {
'make': 'ford',
'model': 'fusion',
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
}, ];
/**
* Groups an array of objects by a key an returns an object or array grouped by provided key.
* @param array - array to group objects by key.
* @param key - key to group array objects by.
* @param removeKey - remove the key and it's value from the resulting object.
* @param outputType - type of structure the output should be contained in.
*/
const groupBy = (
inputArray,
key,
removeKey = false,
outputType = {},
) => {
return inputArray.reduce(
(previous, current) => {
// Get the current value that matches the input key and remove the key value for it.
const {
[key]: keyValue
} = current;
// remove the key if option is set
removeKey && keyValue && delete current[key];
// If there is already an array for the user provided key use it else default to an empty array.
const {
[keyValue]: reducedValue = []
} = previous;
// Create a new object and return that merges the previous with the current object
return Object.assign(previous, {
[keyValue]: reducedValue.concat(current)
});
},
// Replace the object here to an array to change output object to an array
outputType,
);
};
console.log(groupBy(cars, 'make', true))
_x000D_
Using one line to convert the dates to preferred format:
nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
Why not just use the WordPress get_query_var()
function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php
by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,
+----------+
| _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|
I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.
df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")
Here I'm creating a temporary view and store the year values using this single line and the output will be,
+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
| 1872|
| 1873|
| 1874|
| 1875|
| 1876|
| 1876|
| 1877|
| 1877|
| 1878|
| 1878|
| 1879|
| 1879|
| 1879|
Here is my best shot at it. I added another Div and made it red and changed you parent's height to 200px just to test it. The idea is the the child now becomes the grandchild and the parent becomes the grandparent. So the parent respects its parent. Hope you get my idea.
<html>
<body>
<div style="background-color: blue; padding: 10px; position: relative; height: 200px;">
<div style="background-color: red; position: relative; height: 100%;">
<div style="background-color: gray; position: absolute; left: 0px; right: 0px;bottom: 0px;">css sux</div>
</div>
</div>
</body>
</html>
Edit:
I think what you are trying to do can't be done. Absolute position means that you are going to give it co-ordinates it must honor. What if the parent has a padding of 5px. And you absolutely position the child at top: -5px; left: -5px. How is it suppose to honor the parent and you at the same time??
My solution
If you want it to honor the parent, don't absolutely position it then.
Unicode version 11.0.0
In Unicode the Chinese, Japanese and Korean (CJK) scripts share a common background, collectively known as CJK characters.
These ranges often contain non-assigned or reserved code points(such as U+2E9A , U+2EF4 - 2EFF),
bottom top reference (also have a look at wiki page) block name
4E00 9FEF http://www.unicode.org/charts/PDF/U4E00.pdf CJK Unified Ideographs
3400 4DBF http://www.unicode.org/charts/PDF/U3400.pdf CJK Unified Ideographs Extension A
20000 2A6DF http://www.unicode.org/charts/PDF/U20000.pdf CJK Unified Ideographs Extension B
2A700 2B73F http://www.unicode.org/charts/PDF/U2A700.pdf CJK Unified Ideographs Extension C
2B740 2B81F http://www.unicode.org/charts/PDF/U2B740.pdf CJK Unified Ideographs Extension D
2B820 2CEAF http://www.unicode.org/charts/PDF/U2B820.pdf CJK Unified Ideographs Extension E
2CEB0 2EBEF https://www.unicode.org/charts/PDF/U2CEB0.pdf CJK Unified Ideographs Extension F
3007 3007 https://zh.wiktionary.org/wiki/%E3%80%87 in block CJK Symbols and Punctuation
Therefore the range is
[0x3007,0x3007],[0x3400,0x4DBF],[0x4E00,0x9FEF],[0x20000,0x2EBFF]
They are Common Han used only for compatibility.
It is almost impossible to see them appear in any Chinese books, articles, writings etc.
All characters here have one corresponding glyph-identical Chinese character, such as ?(U+F90A) and ?(U+91D1), they are identical glyphs.
F900 FAFF https://www.unicode.org/charts/PDF/UF900.pdf CJK Compatibility Ideographs
2F800 2FA1F https://www.unicode.org/charts/PDF/U2F800.pdf CJK Compatibility Ideographs Supplement
2E80 2EFF http://www.unicode.org/charts/PDF/U2E80.pdf CJK Radicals Supplement
2F00 2FDF http://www.unicode.org/charts/PDF/U2F00.pdf Kangxi Radicals
2FF0 2FFF https://unicode.org/charts/PDF/U2FF0.pdf Ideographic Description Character
3000 303F https://www.unicode.org/charts/PDF/U3000.pdf CJK Symbols and Punctuation
3100 312f https://unicode.org/charts/PDF/U3100.pdf Bopomofo
31A0 31BF https://unicode.org/charts/PDF/U31A0.pdf Bopomofo Extended
31C0 31EF http://www.unicode.org/charts/PDF/U31C0.pdf CJK Strokes
3200 32FF https://unicode.org/charts/PDF/U3200.pdf Enclosed CJK Letters and Months
3300 33FF https://unicode.org/charts/PDF/U3300.pdf CJK Compatibility
FE30 FE4F https://www.unicode.org/charts/PDF/UFE30.pdf CJK Compatibility Forms
FF00 FFEF https://www.unicode.org/charts/PDF/UFF00.pdf Halfwidth and Fullwidth Forms
1F200 1F2FF https://www.unicode.org/charts/PDF/U1F200.pdf Enclosed Ideographic Supplement
This is a wide range, some punctuation may be never used, some punctuations such as ……”“
are used so much in Chinese.
0000 007F https://unicode.org/charts/PDF/U0000.pdf C0 Controls and Basic Latin
2000 206F https://unicode.org/charts/PDF/U2000.pdf General Punctuation
……
There are also many Chinese-related symbols, such as Yijing Hexagram Symbols or Kanbun, but it's off-topic anyway. I write non-chinese-characters in CJK to have a better explanation of what Chinese characters are. And the ranges above already cover almost all the characters which appear in Chinese writing except math and other specialty notation.
CJK Symbols and Punctuation
???????<>«»??????????????[]?????????????????????????????????? ? ?
Halfwidth and Fullwidth Forms
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Here's a flexbox solution when using a full screen wrapper div. justify-content centers it's child div horizontally and align-items centers it vertically.
<div class="full-screen-wrapper">
<div class="center"> //... content</div>
</div>
.full-screen-wrapper {
position: fixed;
display: flex;
justify-content: center;
width: 100vw;
height: 100vh;
top: 0;
align-items: center;
}
.center {
// your styles
}
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKind(of: LoginViewController.self) {
}
}
}
FOR SWIFT 3.0
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let utf8str = str.data(using: String.Encoding.utf8)
if let base64Encoded = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
{
print("Encoded: \(base64Encoded)")
if let base64Decoded = NSData(base64Encoded: base64Encoded, options: NSData.Base64DecodingOptions(rawValue: 0))
.map({ NSString(data: $0 as Data, encoding: String.Encoding.utf8.rawValue) })
{
// Convert back to a string
print("Decoded: \(base64Decoded)!")
}
}
-- Access:
SELECT CHR(13) & CHR(10)
-- SQL Server:
SELECT CHAR(13) + CHAR(10)
There is also a very simple but powerful JSON CLI processing tool fx — https://github.com/antonmedv/fx
Examples
Use anonymous function:
$ echo '{"key": "value"}' | fx "x => x.key"
value
If you don't pass anonymous function param => ..., code will be automatically transformed into anonymous function. And you can get access to JSON by this keyword:
$ echo '[1,2,3]' | fx "this.map(x => x * 2)"
[2, 4, 6]
Or just use dot syntax too:
$ echo '{"items": {"one": 1}}' | fx .items.one
1
You can pass any number of anonymous functions for reducing JSON:
$ echo '{"items": ["one", "two"]}' | fx "this.items" "this[1]"
two
You can update existing JSON using spread operator:
$ echo '{"count": 0}' | fx "{...this, count: 1}"
{"count": 1}
Just plain JavaScript. Don't need to learn new syntax.
UPDATE 2018-11-06
fx
now has interactive mode (!)
I ran into the same problem with an "update"-statement. My solution was simply to run through the operations available in phpMyAdmin for the table. I optimized, flushed and defragmented the table (not in that order). No need to drop the table and restore it from backup for me. :)
I had also the same problem and fix it via Jenkins Console.
Go to "Manage Jenkins" > "Script Console" and run a script:
Jenkins .instance.getItemByFullName("JobName")
.getBuildByNumber(JobNumber)
.finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build"));
You'll have just specify your JobName and JobNumber.
There are two ways to handle this.
The background image is probably easier. You need a fixed width somewhere.
.background-image {
width: 400px;
background: url(background.png) 50% 50%;
}
<form><div class="background-image"></div></form>
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
It is also possible to review changes between two commits for a specific file.
git diff <commit_Id_1> <commit_Id_2> some_dir/file.txt
You simply cannot use WHERE when doing an INSERT statement:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;
should be:
INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );
The WHERE part only works in SELECT statements:
SELECT from Users WHERE id = 1;
or in UPDATE statements:
UPDATE Users set (weight = 160, desiredWeight = 145) WHERE id = 1;
That might happen because the pojos you are using lack of the precise constructor the service needs. That is, try to generate all the constructors for the pojo or objects (model object) that your serviceClient uses, so that the client can be instanced correctly. In your case,regenerate the constructors (with arguments)for your client object (taht is your model object).
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
$uploadfile = $_SERVER['DOCUMENT_ROOT'].'/Thesis/images/';
$profic = uniqid(rand()).$_FILES["pic"]["name"];
if(is_uploaded_file($_FILES["pic"]["tmp_name"]))
{
$moved = move_uploaded_file($_FILES["pic"]["tmp_name"], $uploadfile.$profic);
if($moved)
{
echo "sucess";
}
else
{
echo 'failed';
}
}
The full command is:
dir /b /a-d
Let me break it up;
Basically the /b
is what you look for.
/a-d
will exclude the directory names.
For more information see dir /?
for other arguments that you can use with the dir
command.
I saw it's solved, but I still want to share a solution which worked for me.
.env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]
MySQL admin:
SELECT user, host FROM mysql.user
Console:
php artisan cache:clear
php artisan config:cache
Now it works for me.
Here is a solution without eval nor $() nor `` :
ord () {
local s
printf -v s '\\%03o' $1
printf "$s"
}
ord 65
git diff > patchfile
and
patch -p1 < patchfile
work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile
if you need handle file adds, deletes and renames.
EDIT December 2015
Latest versions of patch
command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).
So provided one uses current/latest version of patch
there is no need to use git
to be able to apply its diff as a patch.
The easy-to-remember, lazy and perhaps imperfect solution:
Directory.GetFiles(dir, "*.dll").Union(Directory.GetFiles(dir, "*.exe"))
Fragment fr = new Fragment_class();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.viewpagerId, fr);
fragmentTransaction.commit();
Just to be precise, R.id.viewpagerId
is cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.
CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml
file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.
I do the following in my application:
Process process = new Process();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.ErrorDialog = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
process.Start();
process.WaitForExit(1000 * 60 * 5); // Wait up to five minutes.
There are a few extra features in there which you might find useful...
function csvToArray($path)
{
try{
$csv = fopen($path, 'r');
$rows = [];
$header = [];
$index = 0;
while (($line = fgetcsv($csv)) !== FALSE) {
if ($index == 0) {
$header = $line;
$index = 1;
} else {
$row = [];
for ($i = 0; $i < count($header); $i++) {
$row[$header[$i]] = $line[$i];
}
array_push($rows, $row);
}
}
return $rows;
}catch (Exception $exception){
return false;
}
}
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php
You could do something like this:
\documentclass{article}
\begin{document}
Normal:
\begin{itemize}
\item foo
\item bar
\item baz
\end{itemize}
Less space:
\begin{itemize}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
In my case, the problem was with the specific box I was trying to use ubuntu/xenial64, I just had to switch to centos/7 and all those errors disappeared.
Hope this helps someone.
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
docker rmi 91c95931e552
Error response from daemon: Conflict, cannot delete 91c95931e552 because the container 76068d66b290 is using it, use -f to force FATA[0000] Error: failed to remove one or more images
Find container ID,
# docker ps -a
# docker rm daf644660736
The agg
function will do this for you. Pass the columns and function as a dict with column, output:
df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]}) # Added example for two output columns from a single input column
This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.
To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:
df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})
Instead of LIKE
(which does work as other commenters have suggested), you can alternatively use CHARINDEX
:
declare @full varchar(100) = 'abcdefg'
declare @find varchar(100) = 'cde'
if (charindex(@find, @full) > 0)
print 'exists'
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
Though it is very old question, i would like to answer as i faced same issue recently and got solution from here -
http://www.codeproject.com/Questions/727493/JavaScript-document-location-href-not-working Solution:
document.location.href = 'Your url',true;
This worked for me.
You can specify the -t
option (--target
) to specify the destination directory. See pip install --help
for detailed information. This is the command you need:
pip install -t path_to_your_home package-name
for example, for installing say mxnet, in my $HOME
directory, I type:
pip install -t /home/foivos/ mxnet
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
You must have either disabled
, froze
or uninstalled
FaceProvider in settings>applications>all
This will only happen if it's frozen
, either uninstall
it, or enable
it.
Your sample does not work in IE for me, you have to specify Doctype header in your document to render your page in standard way in IE to use the content CSS property:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</html>
Second way is to use CSS 3 selectors
li:not(:last-of-type):after
{
content: " |";
}
But you still need to specify Doctype
And third way is to use JQuery with some script like following:
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$("li:not(:last)").append(" | ");
});
</script>
Advantage of third way is that you dont have to specify doctype and jQuery will take care of compatibility.
jQuery's animate function is not exclusively usable for directly animating properties of DOM-objects. You can also tween variables and use the step function to get the variables for every step of the tween.
For example, to animate a background-position from background-position(0px 0px) to background-position(100px 500px) you can do this:
$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: 100, temporary_y: 500}, {
duration: 1000,
step: function() {
var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
$("#your_div").css("background-position", position);
}
});
Just make sure to not forget the this. inside the step function.
Just piling on: the classic example of cache-unfriendly versus cache-friendly code is the "cache blocking" of matrix multiply.
Naive matrix multiply looks like:
for(i=0;i<N;i++) {
for(j=0;j<N;j++) {
dest[i][j] = 0;
for( k=0;k<N;k++) {
dest[i][j] += src1[i][k] * src2[k][j];
}
}
}
If N
is large, e.g. if N * sizeof(elemType)
is greater than the cache size, then every single access to src2[k][j]
will be a cache miss.
There are many different ways of optimizing this for a cache. Here's a very simple example: instead of reading one item per cache line in the inner loop, use all of the items:
int itemsPerCacheLine = CacheLineSize / sizeof(elemType);
for(i=0;i<N;i++) {
for(j=0;j<N;j += itemsPerCacheLine ) {
for(jj=0;jj<itemsPerCacheLine; jj+) {
dest[i][j+jj] = 0;
}
for( k=0;k<N;k++) {
for(jj=0;jj<itemsPerCacheLine; jj+) {
dest[i][j+jj] += src1[i][k] * src2[k][j+jj];
}
}
}
}
If the cache line size is 64 bytes, and we are operating on 32 bit (4 byte) floats, then there are 16 items per cache line. And the number of cache misses via just this simple transformation is reduced approximately 16-fold.
Fancier transformations operate on 2D tiles, optimize for multiple caches (L1, L2, TLB), and so on.
Some results of googling "cache blocking":
http://stumptown.cc.gt.atl.ga.us/cse6230-hpcta-fa11/slides/11a-matmul-goto.pdf
http://software.intel.com/en-us/articles/cache-blocking-techniques
A nice video animation of an optimized cache blocking algorithm.
http://www.youtube.com/watch?v=IFWgwGMMrh0
Loop tiling is very closely related:
There is a easy way to do this. It only takes a couple steps and you don't need to use the command line too much. If you new to the command line this is the way to do it.
Step 1 : Finding the bin file to put the subl executable file in
cd ..
---------------------this should go back a directoryls
------------------------to see a list of files in the directorycd ..
---------------------until you get a folder that contains usropen usr
---------------this should open the finder and you should see some foldersStep 2: Finding the executable file
subl
--------------this should open Sublime TextMake sure that it gets copied and it's not a shortcut. If you do have a problem, view the usr/bin folder as icons and paste the subl in a empty area in the folder. It should not have a shortcut arrow in the icon image.
You can try as follows it works for me
select * from nm_admission where trunc(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
OR
select * from nm_admission where trunc(entry_timestamp) = '09-SEP-2018';
You can also try using to_char but remember to_char is too expensive
select * from nm_admission where to_char(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
The TRUNC(17-SEP-2018 08:30:11) will give 17-SEP-2018 00:00:00 as a result, you can compare the only date portion independently and time portion will skip.
To detect whether two balls collide, just check whether the distance between their centers is less than two times the radius. To do a perfectly elastic collision between the balls, you only need to worry about the component of the velocity that is in the direction of the collision. The other component (tangent to the collision) will stay the same for both balls. You can get the collision components by creating a unit vector pointing in the direction from one ball to the other, then taking the dot product with the velocity vectors of the balls. You can then plug these components into a 1D perfectly elastic collision equation.
Wikipedia has a pretty good summary of the whole process. For balls of any mass, the new velocities can be calculated using the equations (where v1 and v2 are the velocities after the collision, and u1, u2 are from before):
If the balls have the same mass then the velocities are simply switched. Here's some code I wrote which does something similar:
void Simulation::collide(Storage::Iterator a, Storage::Iterator b)
{
// Check whether there actually was a collision
if (a == b)
return;
Vector collision = a.position() - b.position();
double distance = collision.length();
if (distance == 0.0) { // hack to avoid div by zero
collision = Vector(1.0, 0.0);
distance = 1.0;
}
if (distance > 1.0)
return;
// Get the components of the velocity vectors which are parallel to the collision.
// The perpendicular component remains the same for both fish
collision = collision / distance;
double aci = a.velocity().dot(collision);
double bci = b.velocity().dot(collision);
// Solve for the new velocities using the 1-dimensional elastic collision equations.
// Turns out it's really simple when the masses are the same.
double acf = bci;
double bcf = aci;
// Replace the collision velocity components with the new ones
a.velocity() += (acf - aci) * collision;
b.velocity() += (bcf - bci) * collision;
}
As for efficiency, Ryan Fox is right, you should consider dividing up the region into sections, then doing collision detection within each section. Keep in mind that balls can collide with other balls on the boundaries of a section, so this may make your code much more complicated. Efficiency probably won't matter until you have several hundred balls though. For bonus points, you can run each section on a different core, or split up the processing of collisions within each section.
Here's a little hack that switched from data-hover to data-toggle depending the screen width:
/**
* Bootstrap nav menu hack
*/
$(window).on('load', function () {
// On page load
if ($(window).width() < 768) {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
}
// On window resize
$(window).resize(function () {
if ($(window).width() < 768) {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
} else {
$('.navbar-nav > li > .dropdown-toggle').removeAttr('data-toggle').attr('data-hover', 'dropdown');
}
});
});
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
This is just a guess, but I think your editor actually matches every single digit — 1
2
3
— but only odd matches are highlighted, to distinguish it from the case when the whole 123
string is matched.
Most regex consoles highlight contiguous matches with different colors, but due to the plugin settings, terminal limitations or for some other reason, only every other group might be highlighted in your case.
Adding this command to Dockerfile can disable it:
RUN echo "daemon off;" >> /etc/nginx/nginx.conf
If in the folder with your project you created a file with the name "datetime.py"
For fine tuning the position of an inline-block
item, use top and left:
position: relative;
top: 5px;
left: 5px;
Thanks CSS-Tricks!
In my case, this was a test target that I removed all the pods from inside my podfile (because I added pods that I later realized I did not need in that target). None of the other solutions here worked for me.
Go to the Build Phases tab in the project settings for the target that's causing trouble.
Delete the section named "Check Pods Manifest" and "Copy Pods Resources"
Inside "Link Binary With Libraries" remove libPods-YourTarget.a
In your project settings in the Info tab expand "Configurations" and set the configuration for the target to None for both debug and release. (This will fix a couple of missing file warnings)
Delete your project's derived data (Window > Projects > Delete [next to your project) and restart Xcode. Build / run target.
In case of your jdk version less than 1.5, following option can be used.
int iTest = 2;
StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
sTest.append(String.valueOf(iTest));
System.out.println(sTest.substring(sTest.length()-6, sTest.length()));
If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.
Sample Output:
$5.23
-$5.23
function formatCurrency(total) {
var neg = false;
if(total < 0) {
neg = true;
total = Math.abs(total);
}
return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}
Use:
var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
new RFCValidation(),
new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true
I use:
if exists (select *
from sys.tables
where name = 'tableName'
and schema_id = schema_id('dbo'))
begin
drop table dbo.tableName
end
I did some mock testing to record the difference between save()
and persist()
.
Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.
For the below example, take EmployeeVehicle as an Entity with PK as vehicleId
which is a generated value and vehicleName
as one of its properties.
Example 1 : Dealing with Transient Object
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = new EmployeeVehicle();
entity.setVehicleName("Honda");
session.save(entity);
// session.persist(entity);
session.getTransaction().commit();
session.close();
Result:
select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)
Note the result is same when you get an already persisted object and save it
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
entity.setVehicleName("Toyota");
session.save(entity); -------> **instead of session.update(entity);**
// session.persist(entity);
Repeat the same using persist(entity)
and will result the same with new Id ( say 37 , honda ) ;
Example 2 : Dealing with Detached Object
// Session 1
// Get the previously saved Vehicle Entity
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached object
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.save(entity);
session2.getTransaction().commit();
session2.close();
Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"
select nextval ('hibernate_sequence')
insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)
Using persist to persist detached entity
// (ii) Using Persist() to persist a detached
// Session 1
Session session = factory.openSession();
session.beginTransaction();
EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
session.close();
// Session 2
// Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it
// (i) Using Save() to persist a detached
Session session2 = factory.openSession();
session2.beginTransaction();
entity.setVehicleName("Toyota");
session2.persist(entity);
session2.getTransaction().commit();
session2.close();
Result:
Exception being thrown : detached entity passed to persist
So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with Transient object .
Important Note : In the above example , the pk of vehicle entity is a generated value , so when using save() to persist a detached entity , hibernate generates a new id to persist . However if this pk is not a generated value than it is result in a exception stating key violated.
As said, JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
A simpler solution could be replacing the method getLocations
with:
public static List<Location> getLocations(InputStream inputStream) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference<List<Location>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
On the other hand, if you don't have a pojo like Location
, you could use:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
I can make it work after turn off and turn on the wifi on android config
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
If you're dealing with multiple values and multiple inputs you could also set up an apply function like this. In this case filtering a dataframe for GPS locations that fall withing certain ranges.
def filter_values(lat,lon):
if abs(lat - 33.77) < .01 and abs(lon - -118.16) < .01:
return True
elif abs(lat - 37.79) < .01 and abs(lon - -122.39) < .01:
return True
else:
return False
df = df[df.apply(lambda x: filter_values(x['lat'],x['lon']),axis=1)]
I prefer use an extension for that. Besides, this url http://emailregex.com can help you to test if regex is correct. In fact, the site offers differents implementations for some programming languages. I share my implementation for Swift 3.
extension String {
func validateEmail() -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
}
You can use the text-align-last
property
.center-justified {
text-align: justify;
text-align-last: center;
}
Here is a compatibility table : https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last#Browser_compatibility.
Works in all browsers except for Safari (both Mac and iOS), including Internet Explorer.
Also in Internet Explorer, only works with text-align: justify
(no other values of text-align
) and start
and end
are not supported.
use mysql_real_escape_string()
instead of mysqli_real_escape_string()
like so:
$username = mysql_real_escape_string($_POST['username']);
Please look at this document
http://www.socialsecurity.gov/employer/randomization.html
The SSA is instituting a new policy the where all previously unused sequences are will be available for use.
Goes into affect June 25, 2011.
Taken from the new FAQ:
What changes will result from randomization?
The SSA will eliminate the geographical significance of the first three digits of the SSN, currently referred to as the area number, by no longer allocating the area numbers for assignment to individuals in specific states. The significance of the highest group number (the fourth and fifth digits of the SSN) for validation purposes will be eliminated. Randomization will also introduce previously unassigned area numbers for assignment excluding area numbers 000, 666 and 900-999. Top
Will SSN randomization assign group number (the fourth and fifth digits of the SSN) 00 or serial number (the last four digits of the SSN) 0000?
SSN randomization will not assign group number 00 or serial number 0000. SSNs containing group number 00 or serial number 0000 will continue to be invalid.
It's supposed to be as simple as this:
<select id='multipleSelect' multiple='multiple'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<script type='text/javascript'>
$('#multipleSelect').val(['1', '2']);
</script>
Check my Fiddle: https://jsfiddle.net/luthrayatin/jaLygLzo/
Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and
operator:
if x & 1:
return 'odd'
else:
return 'even'
&
(bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.You need to add another \
before your carbon class to start in the root namespace.
$current_time = \Carbon\Carbon::now()->toDateTimeString();
Also, make sure Carbon is loaded in your composer.json
.
I had the same problem with bringing a JFrame
to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a WindowListener
. Specifically, I had to set my JFrame
to always stay on top whenever toFront()
is invoked, and provide windowDeactivated
event handler to setAlwaysOnTop(false)
.
So, here is the code that could be placed into a base JFrame
, which is used to derive all application frames.
@Override
public void setVisible(final boolean visible) {
// make sure that frame is marked as not disposed if it is asked to be visible
if (visible) {
setDisposed(false);
}
// let's handle visibility...
if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
super.setVisible(visible);
}
// ...and bring frame to the front.. in a strange and weird way
if (visible) {
toFront();
}
}
@Override
public void toFront() {
super.setVisible(true);
int state = super.getExtendedState();
state &= ~JFrame.ICONIFIED;
super.setExtendedState(state);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
Whenever your frame should be displayed or brought to front call frame.setVisible(true)
.
Since I moved to Ubuntu 9.04 there seems to be no need in having a WindowListener
for invoking super.setAlwaysOnTop(false)
-- as can be observed; this code was moved to the methods toFront()
and setVisible()
.
Please note that method setVisible()
should always be invoked on EDT.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
You can use the spool
command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool
can change the file that's being written to, so you can have several queries writing to different files just by putting spool
commands between them:
spool "\path\to\spool1.txt"
select /*csv*/ * from employees;
spool "\path\to\spool2.txt"
select /*csv*/ * from locations;
spool off;
You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set
command, though some of those do not translate to SQL Developer.
Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.
A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.
With netcat and awk you can handle the server response manually:
if netcat 127.0.0.1 8080 <<EOF | awk 'NR==1{if ($2 == "500") exit 0; exit 1;}'; then
GET / HTTP/1.1
Host: www.example.com
EOF
apache2ctl restart;
fi
Never is a good practice to pass the password argument directly from the command line, it is saved in the ~/.bash_history
file and can be accessible from other applications.
Use this instead:
mysql -u user --host host --port 9999 database_name < /scripts/script.sql -p
Enter password:
When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.
In this case, as others pointed out, you missed the case insensitivity option.
Swift 3/4
You can use the below extension for your convenience.
Usage inside a ViewController
:
showInputDialog(title: "Add number",
subtitle: "Please enter the new number below.",
actionTitle: "Add",
cancelTitle: "Cancel",
inputPlaceholder: "New number",
inputKeyboardType: .numberPad)
{ (input:String?) in
print("The new number is \(input ?? "")")
}
The extension code:
extension UIViewController {
func showInputDialog(title:String? = nil,
subtitle:String? = nil,
actionTitle:String? = "Add",
cancelTitle:String? = "Cancel",
inputPlaceholder:String? = nil,
inputKeyboardType:UIKeyboardType = UIKeyboardType.default,
cancelHandler: ((UIAlertAction) -> Swift.Void)? = nil,
actionHandler: ((_ text: String?) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: subtitle, preferredStyle: .alert)
alert.addTextField { (textField:UITextField) in
textField.placeholder = inputPlaceholder
textField.keyboardType = inputKeyboardType
}
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: { (action:UIAlertAction) in
guard let textField = alert.textFields?.first else {
actionHandler?(nil)
return
}
actionHandler?(textField.text)
}))
alert.addAction(UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler))
self.present(alert, animated: true, completion: nil)
}
}
Cmd below solved my problem:
$ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
In my case, I upgraded to Xcode 8 and downloaded another version 7.3.1 later (renamed it to "Xcode 7.3.1"), then cannot get the simulator list in Xcode 8.
First you have to set the MultiLine
property of the TextBox
to true
so that it supports multiple lines.
Then you just use Environment.NewLine
to get the newline character combination.
You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.
Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)
Try this to move your table (tbl1) to tablespace (tblspc2).
alter table tb11 move tablespace tblspc2;
I had the same problem. I eventually figured it out by inspecting the element and the element I thought I had selected was different element. When I did that I found there was a hidden element that had z-index of 9999, once I fixed that my problem went away.
If the script only defines the functions and does nothing else, you can first execute the script within the context of the current shell using the source
or .
command and then simply call the function. See help source
for more information.
In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:
using System.Globalization;
...
NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+("
+ Regex.Escape(nfi.CurrencyDecimalSeparator)
+ "\\d{1,2}))$");
You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.
It's possible if you believe. Hehe. try this code.
public function add_new_enum($new_value)
{
$table="product";
$column="category";
$row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();
$old_category = array();
$new_category="";
foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
{
//getting the old category first
$old_category[$val] = $val;
$new_category.="'".$old_category[$val]."'".",";
}
//after the end of foreach, add the $new_value to $new_category
$new_category.="'".$new_value."'";
//Then alter the table column with the new enum
$this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
}
Try this
SELECT *
FROM people P
where P.IDNo in (SELECT DISTINCT IDNo
FROM people)
sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
Change MYSECRET with your new root password
UPDATE user SET Password=PASSWORD('MYSECRET') WHERE User='root'; FLUSH PRIVILEGES; exit;
The URL which worked for me is http://download.eclipse.org/tools/pdt/updates/2.0/interim/.
See also Stack Overflow question Installing PDT in Eclipse - No runtime option .. only SDK.
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
I guess if you are using WSL with GUI, then you could just try
sudo /etc/init.d/docker start
If anyone comes to this thread and has this issue when you remote to a VMware VM with windows 10 1903, disabling 3d in the graphics card worked for me.
You cannot "convert" an existing column into an IDENTITY
column - you will have to create a new column as INT IDENTITY
:
ALTER TABLE ProductInProduct
ADD NewId INT IDENTITY (1, 1);
Update:
OK, so there is a way of converting an existing column to IDENTITY
. If you absolutely need this - check out this response by Martin Smith with all the gory details.
I know this doesn't answer the question, but with Material Design (API 21+) we can change the color of the status bar by adding this line in the theme declaration in styles.xml
:
<!-- MAIN THEME -->
<style name="AppTheme" parent="@android:style/Theme.Material.Light">
<item name="android:actionBarStyle">@style/actionBarCustomization</item>
<item name="android:spinnerDropDownItemStyle">@style/mySpinnerDropDownItemStyle</item>
<item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item>
<item name="android:colorButtonNormal">@color/myDarkBlue</item>
<item name="android:statusBarColor">@color/black</item>
</style>
Notice the android:statusBarColor
, where we can define the color, otherwise the default is used.
I just got the same situation, Factory data reset worked well for me.
in order to know the phone resolution simply create a image with label mdpi, hdpi, xhdpi and xxhdpi. put these images in respective folder like mdpi, hdpi, xhdpi and xxhdpi. create a image view in layout and load this image. the phone will load the respective image from a specific folder. by this you will get the phone resolution or *dpi it is using.
See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!
Arraylist<String> list = new ArrayList<>();
public void addingToTheList() {
if(isSunday()) {
list.add("Pray today")
return;
}
if(isMonday()) {
list.add("Work today"
return;
}
if(isTuesday()) {
list.add("Tr today")
return;
}
}
The problem is that the CASE
statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:
SELECT
ActivityID,
FieldName = CASE
WHEN ActivityTypeID <> 2 THEN
(Some Aggregate Sub Query)
ELSE
(Some Aggregate Sub Query with diff result)
END,
FieldName2 = CASE
WHEN ActivityTypeID <> 2 THEN
(Some Aggregate Sub Query)
ELSE
(Some Aggregate Sub Query with diff result)
END
SELECT CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
WHEN SERVERPROPERTY('EditionID') = -2117995310 THEN 'Developer'
WHEN SERVERPROPERTY('EditionID') = 610778273 THEN 'Windows Embedded SQL'
WHEN SERVERPROPERTY('EditionID') = 4161255391 THEN 'Express with Advanced Services'
END AS 'Edition';
You would have to watch the DOM node changes. There is an API called MutationObserver
, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.
One way you could get around this problem is to have the part of the code that modifies the data-select-content-val
attribute dispatch an event that you can listen to.
For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.
The code here is
$(function() {
// Here you register for the event and do whatever you need to do.
$(document).on('data-attribute-changed', function() {
var data = $('#contains-data').data('mydata');
alert('Data changed to: ' + data);
});
$('#button').click(function() {
$('#contains-data').data('mydata', 'foo');
// Whenever you change the attribute you will user the .trigger
// method. The name of the event is arbitrary
$(document).trigger('data-attribute-changed');
});
$('#getbutton').click(function() {
var data = $('#contains-data').data('mydata');
alert('Data is: ' + data);
});
});
Under Visual Studio 2008, it defaults to an __int64
unless you define _USE_32BIT_TIME_T
. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.
They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.
Simple way:
repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));
You convert type np.dot(X, T)
to float32 like this:
z=np.array(np.dot(X, T),dtype=np.float32)
def sigmoid(X, T):
return (1.0 / (1.0 + np.exp(-z)))
Hopefully it will finally work!
Add permission to the folder where your .mdf
file is.
Check this name: NT Service\MSSQLSERVER
And change the Location
to your server name.
IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
BEGIN
DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
END
GO
I can fix this by adding below code in my JSP file. Now both model and UI values are same.
<div ng-show="false">
{{dt = (dt | date:'dd-MMMM-yyyy') }}
</div>
This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)
JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest
and the associated browser methods. Instead a <script>
tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head>
element).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// success
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.
{ "bar": "baz" }
foo( { "bar": "baz" } );
This is why you see JSONP requests containing the callback
parameter, so that the server knows the name of the function to wrap the response.
This function must exist in the global scope at the time the <script>
tag is evaluated by the browser (once the request has completed).
Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.
Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.
The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.
By default jQuery requires you to include &callback=?
in the URL of your AJAX request. jQuery will take the success
function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ?
in &callback=?
with the name it has assigned.
The following assumes a response object { "bar" : "baz" }
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
};
};
xhr.open("GET", "somewhere.php", true);
xhr.send();
function foo(response) {
document.getElementById("output").innerHTML = response.bar;
};
var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';
document.getElementsByTagName("head")[0].appendChild(tag);
Let us say we have a project social_login. To check the traffic to your repo, you can goto https://github.com//social_login/graphs/traffic
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
See the below example
CREATE TABLE users (
-- make the "id" column a primary key; this also creates
-- a UNIQUE constraint and a b+-tree index on the column
id SERIAL PRIMARY KEY,
name TEXT,
age INT4
);
INSERT INTO users (name, age) VALUES ('Mozart', 20);
Then for getting last inserted id use this for table "user" seq column name "id"
SELECT currval(pg_get_serial_sequence('users', 'id'));
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
It describes a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.It contains the following properties.
{
"name": "mobileapp",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@angular-devkit/architect": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@angular- devkit/architect/-/architect-0.11.4.tgz",
"integrity": "sha512-2zi6S9tPlk52vyqNFg==",
"dev": true,
"requires": {
"@angular-devkit/core": "7.1.4",
"rxjs": "6.3.3"
}
},
}
In case anyone comes across this article looking for what I was looking for, I found examples at
How to visualize scalar 2D data with Matplotlib?
and
http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)
then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.
Starting with a 3D array of images of shape (nBins, nBins, nBins), called frames
.
def animate_frames(frames):
nBins = frames.shape[0]
frame = frames[0]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
for k in range(nBins):
frame = frames[k]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
del tempCS1
fig.canvas.draw()
#time.sleep(1e-2) #unnecessary, but useful
fig.clf()
fig = plt.figure()
ax = fig.add_subplot(111)
win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate_frames, frames)
I also found a much simpler way to go about this whole process, albeit less robust:
fig = plt.figure()
for k in range(nBins):
plt.clf()
plt.imshow(frames[k],cmap=plt.cm.gray)
fig.canvas.draw()
time.sleep(1e-6) #unnecessary, but useful
Note that both of these only seem to work with ipython --pylab=tk
, a.k.a.backend = TkAgg
Thank you for the help with everything.
As mentioned here, you need to remove the unused references and the warnings will go.
I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.
As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.
I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.
I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.
I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.
If you use Spring boot, consider to remove server.tomcat.additional-tld-skip-patterns=*.jar
from Application.properties
if there is any
You can use this simple JavaScript code to make search button to link to a sample search results page. Here I have redirected to '/search' of my home page, If you want to search from Google search engine, You can use "https://www.google.com/search" in form action.
<form action="/search"> Enter your search text:
<input type="text" id="searchtext" name="q">
<input onclick="myFunction()" type="submit" value="Search It" />
</form>
<script> function myFunction()
{
var search = document.getElementById("searchtext").value;
window.location = '/search?q='+search;
}
</script>
Tried and working. you are using,
<textarea name='Status'> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
I am using javascript , (don't know about php), use id ="status" in textarea like
<textarea name='Status' id="status"> </textarea>
<input type='button' onclick='UpdateStatus()' value='Status Update'>
then make a call to servlet sending the status to backend for updating using whatever strutucre(like MVC in java or anyother) you like, like this in your UI in script tag
<srcipt>
function UpdateStatus(){
//make an ajax call and get status value using the same 'id'
var var1= document.getElementById("status").value;
$.ajax({
type:"GET",//or POST
url:'http://localhost:7080/ajaxforjson/Testajax',
// (or whatever your url is)
data:{data1:var1},
//can send multipledata like {data1:var1,data2:var2,data3:var3
//can use dataType:'text/html' or 'json' if response type expected
success:function(responsedata){
// process on data
alert("got response as "+"'"+responsedata+"'");
}
})
}
</script>
and jsp is like
the servlet will look like: //webservlet("/zcvdzv") is just for url annotation
@WebServlet("/Testajax")
public class Testajax extends HttpServlet {
private static final long serialVersionUID = 1L;
public Testajax() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String data1=request.getParameter("data1");
//do processing on datas pass in other java class to add to DB
// i am adding or concatenate
String data="i Got : "+"'"+data1+"' ";
System.out.println(" data1 : "+data1+"\n data "+data);
response.getWriter().write(data);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
'use strict'
function A() {}
var a = new A();
class B extends A {}
var b = new B();
console.log('====='); // =====
console.log(B.__proto__ === A); // true
console.log(B.prototype.__proto__ === A.prototype); // true
console.log(b.__proto__ === B.prototype); // true
console.log(a.__proto__ === A.prototype); // true
console.log(A.__proto__ === Function.__proto__); // true
console.log(Object.__proto__ === Function.__proto__); // true
console.log(Object.prototype === Function.__proto__.__proto__); // true
console.log(Object.prototype.__proto__ === null); // true
In JavaScript, Every object(function is object too!) has a __proto__
property, the property is reference to its prototype.
When we use the new
operator with a constructor to create a new object,
the new object's __proto__
property will be set with constructor's prototype
property,
then the constructor will be call by the new object,
in that process "this" will be a reference to the new object in the constructor scope, finally return the new object.
Constructor's prototype is __proto__
property, Constructor's prototype
property is work with the new
operator.
Constructor must be a function, but function not always is constructor even if it has prototype
property.
Prototype chain actually is object's __proto__
property to reference its prototype,
and the prototype's __proto__
property to reference the prototype's prototype, and so on,
until to reference Object's prototype's __proto__
property which is reference to null.
For example:
console.log(a.constructor === A); // true
// "a" don't have constructor,
// so it reference to A.prototype by its ``__proto__`` property,
// and found constructor is reference to A
[[Prototype]]
and __proto__
property actually is same thing.
We can use Object's getPrototypeOf method to get something's prototype.
console.log(Object.getPrototypeOf(a) === a.__proto__); // true
Any function we written can be use to create an object with the new
operator,
so anyone of those functions can be a constructor.
IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.
An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.
Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.
Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
http://vim.wikia.com/wiki/Search_and_replace
Try this search and replace:
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first.
Press y or n to change or keep your text.
I've been working on this problem of ditching those irritable Google error pages today. It is possible with the Android example code seen above and in plenty of other forums (ask how I know):
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
});
IF you put it in shouldOverrideUrlLoading() as one more webclient. At least, this is working for me on my 2.3.6 device. We'll see where else it works later. That would only depress me now, I'm sure. The goBack bit is mine. You may not want it.
Here's how I do it. Simple and concise:
- (IBAction)buttonTappedAction:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero
toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
...
}
UPDATE January, 2017:
According to Can I use, the user-select
is currently supported in all browsers except Internet Explorer 9 and earlier versions (but sadly still needs a vendor prefix).
All of the correct CSS variations are:
.noselect {_x000D_
-webkit-touch-callout: none; /* iOS Safari */_x000D_
-webkit-user-select: none; /* Safari */_x000D_
-khtml-user-select: none; /* Konqueror HTML */_x000D_
-moz-user-select: none; /* Firefox */_x000D_
-ms-user-select: none; /* Internet Explorer/Edge */_x000D_
user-select: none; /* Non-prefixed version, currently_x000D_
supported by Chrome and Opera */_x000D_
}
_x000D_
<p>_x000D_
Selectable text._x000D_
</p>_x000D_
<p class="noselect">_x000D_
Unselectable text._x000D_
</p>
_x000D_
Note that it's a non-standard feature (i.e. not a part of any specification). It is not guaranteed to work everywhere, and there might be differences in implementation among browsers and in the future browsers can drop support for it.
More information can be found in Mozilla Developer Network documentation.
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2
that aren't in array1
. It sounds like you're asking is array1 a subset of array2?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true
Look at the following:
echo "ls -l" | at 07:00
This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:
http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html
Hope it helps!
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.If I understand correctly you want to change the CSS style of an element by clicking an item in a ul
list. Am I right?
HTML:
<div class="results" style="background-color:Red;">
</div>
<ul class="colors-list">
<li>Red</li>
<li>Blue</li>
<li>#ffee99</li>
</ul>
jquery
$('.colors-list li').click(function(e){
var color = $(this).text();
$('.results').css('background-color',color);
});
Note that jquery can use addClass
, removeClass
and toggleClass
if you want to use classes rather than inline styling. This means that you can do something like that:
$('.results').addClass('selected');
And define the 'selected' styling in the CSS.
Working example: http://jsfiddle.net/uuJmP/
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
Most answers here forget the obvious culprit why recursion is often slower than iterative solutions. It's linked with the build up and tear down of stack frames but is not exactly that. It's generally a big difference in the storage of the auto variable for each recursion. In an iterative algorithm with a loop, the variables are often held in registers and even if they spill, they will reside in the Level 1 cache. In a recursive algorithm, all intermediary states of the variable are stored on the stack, meaning they will engender many more spills to memory. This means that even if it makes the same amount of operations, it will have a lot memory accesses in the hot loop and what makes it worse, these memory operations have a lousy reuse rate making the caches less effective.
TL;DR recursive algorithms have generally a worse cache behavior than iterative ones.
Do you have a "shared object" (usually a shared library on AIX), a UNIX shared library, or a Windows DLL? These are all different things, and your question conflates them all :-(
dump -Tv /path/to/foo.o
.readelf -Ws /path/to/libfoo.so
, or (if you have GNU nm) nm -D /path/to/libfoo.so
.dumpbin /EXPORTS foo.dll
.Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.
In case anyone else comes across this problem, if you have already laid the page out, I would recommend using media queries to set up your print page. You can then simply attach a print function to your html button and in your component call window.print();
component.html:
<div class="doNotPrint">
Header is here.
</div>
<div>
all my beautiful print-related material is here.
</div>
<div class="doNotPrint">
my footer is here.
<button (click)="onPrint()">Print</button>
</div>
component.ts:
onPrint(){
window.print();
}
component.css:
@media print{
.doNotPrint{display:none !important;}
}
You can optionally also add other elements / sections you do not wish to print in the media query.
You can change the document margins and all in the print query as well, which makes it quite powerful. There are many articles online. Here is one that seems comprehensive: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes/ It also means you don't have to create a separate script to create a 'print version' of the page or use lots of javascript.
You might need to register this DLL using the 32 bit version of regsvr32.exe
:
c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll
You can do it like you assumed. But your HashMap has to be templated:
Map<String, Map<String, String>> map =
new HashMap<String, Map<String, String>>();
Otherwise you have to do a cast to Map
after you retrieve the second map from the first.
Map map = new HashMap();
((Map)map.get( "keyname" )).get( "nestedkeyname" );
I have resolve the problem as below 1. Get the tag from your branch 2. Write below command
Example: git branch <Hotfix branch> <TAG>
git branch hotfix_4.4.3 v4.4.3
git checkout hotfix_4.4.3
or you can do with other command
git checkout -b <Hotfix branch> <TAG>
-b stands for creating new branch to local
once you ready with your hotfix branch, It's time to move that branch to github, you can do so by writing below command
git push --set-upstream origin hotfix_4.4.3
In Solution Explorer Under Project Click on Dependencies->NuGet->Microsoft.NetCore.All-> Here list of all Microsoft .NetCore pakcages will appear. Search for Microsoft.EntityFrameworkCore(2.0.3) in bracket version can be seen Like this
The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath()
(and thus NOT getServletPath()
as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}
.
<p>The context path is: ${pageContext.request.contextPath}.</p>
If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base>
tag:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
<!doctype html>
<html lang="en">
<head>
<title>SO question 2204870</title>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
<script src="js/global.js"></script>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<ul>
<li><a href="home.jsp">Home</a></li>
<li><a href="faq.jsp">FAQ</a></li>
<li><a href="contact.jsp">Contact</a></li>
</ul>
</body>
</html>
All links in the page will then automagically be relative to the <base>
so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /
, then they will not be relative to the <base>
anymore, but to the domain root instead.
This might help..!!!
SQLCMD -S SERVERNAME -E
This formula does not require a column letter reference ("A", "B", etc.). It returns the value of the cell one row above in the same column.
=INDIRECT(ADDRESS(ROW()-1,COLUMN()))
Note : Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. For these kind of things we should use isset instead of empty.
$requestArr = $_POST['data']// Requested data
$requiredFields = ['emailType', 'emailSubtype'];
$missigFields = $this->checkRequiredFields($requiredFields, $requestArr);
if ($missigFields) {
$errorMsg = 'Following parmeters are mandatory: ' . $missigFields;
return $errorMsg;
}
// Function to check whether the required params is exists in the array or not.
private function checkRequiredFields($requiredFields, $requestArr) {
$missigFields = [];
// Loop over the required fields and check whether the value is exist or not in the request params.
foreach ($requiredFields as $field) {`enter code here`
if (empty($requestArr[$field])) {
array_push($missigFields, $field);
}
}
$missigFields = implode(', ', $missigFields);
return $missigFields;
}
When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
}
This approach support cross-browser changing the value of key code. Source
var $textBox = $("#myTextBox");
var press = jQuery.Event("keypress");
press.altGraphKey = false;
press.altKey = false;
press.bubbles = true;
press.cancelBubble = false;
press.cancelable = true;
press.charCode = 13;
press.clipboardData = undefined;
press.ctrlKey = false;
press.currentTarget = $textBox[0];
press.defaultPrevented = false;
press.detail = 0;
press.eventPhase = 2;
press.keyCode = 13;
press.keyIdentifier = "";
press.keyLocation = 0;
press.layerX = 0;
press.layerY = 0;
press.metaKey = false;
press.pageX = 0;
press.pageY = 0;
press.returnValue = true;
press.shiftKey = false;
press.srcElement = $textBox[0];
press.target = $textBox[0];
press.type = "keypress";
press.view = Window;
press.which = 13;
$textBox.trigger(press);
In Visual Studio 2019- Tools > Command Line > Developer Command Prompt.enter image description here
testSpace.Style.Add("display", "none");
IE didn't add media query support until IE9. So with IE8 you're out of luck.
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
On some servers and web hosts, it's possible to disable ModSecurity via .htaccess
, but be aware that you can only switch it on or off, you can't disable individual rules.
But a good practice that still keeps your site secure is to disable it only on specific URLs, rather than your entire site. You can specify which URLs to match via the regex in the <If>
statement below...
### DISABLE mod_security firewall
### Some rules are currently too strict and are blocking legitimate users
### We only disable it for URLs that contain the regex below
### The regex below should be placed between "m#" and "#"
### (this syntax is required when the string contains forward slashes)
<IfModule mod_security.c>
<If "%{REQUEST_URI} =~ m#/admin/#">
SecFilterEngine Off
SecFilterScanPOST Off
</If>
</IfModule>
Why you don't use a DELETE CASCADE FK
?
For a dynamic approach, if your labels are always in front of your text areas:
$(object).prev("label").text(charsleft);
I've tested two ways in Firefox, Chrome, IE9 and Safari.
(1). $(document.activeElement)
works as expected in Firefox, Chrome and Safari.
(2). $(':focus')
works as expected in Firefox and Safari.
I moved into the mouse to input 'name' and pressed Enter on keyboard, then I tried to get the focused element.
(1). $(document.activeElement)
returns the input:text:name as expected in Firefox, Chrome and Safari, but it returns input:submit:addPassword in IE9
(2). $(':focus')
returns input:text:name as expected in Firefox and Safari, but nothing in IE
<form action="">
<div id="block-1" class="border">
<h4>block-1</h4>
<input type="text" value="enter name here" name="name"/>
<input type="button" value="Add name" name="addName"/>
</div>
<div id="block-2" class="border">
<h4>block-2</h4>
<input type="text" value="enter password here" name="password"/>
<input type="submit" value="Add password" name="addPassword"/>
</div>
</form>
Added below "Conclusion" paragraph
I've went down the pipenv
rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.
This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.
As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".
pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt
, pipenv
delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile
is to supplant requirements.txt
.
HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.
So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.
The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:
prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)
So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv
- varies materially from venv
.
Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.
An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.