jQuery.Deferred() can simplify management of asynchronous sequencing and error handling.
polling_active = true // set false to interrupt polling
function initiate_polling()
{
$.Deferred().resolve() // optional boilerplate providing the initial 'then()'
.then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
.then( () => $.get('/my-api') ) // initiate AJAX
.then( response =>
{
if ( JSON.parse(response).my_result == my_target ) polling_active = false
if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
if ( polling_active ) initiate_polling() // iterative recursion
})
.fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
}
This is an elegant approach, but there are some gotchas...
then()
to fall through immediately, the callback should return another thenable object (probably another Deferred
), which the sleep and ajax lines both do.I would do it this way (Reference http://www.w3.org/TR/page-visibility/):
window.onload = function() {
// check the visiblility of the page
var hidden, visibilityState, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
}
else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
}
else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
}
else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
}
if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
// not supported
}
else {
document.addEventListener(visibilityChange, function() {
console.log("hidden: " + document[hidden]);
console.log(document[visibilityState]);
switch (document[visibilityState]) {
case "visible":
// visible
break;
case "hidden":
// hidden
break;
}
}, false);
}
if (document[visibilityState] === "visible") {
// visible
}
};
Open command prompt in the folder in which you files to be imported are present. when you type 'python', python terminal will be opened. Now you can use
import script_nameNote: no .py extension to be used while importing.
If you are using the default R console, the key combination Option + Command + L will clear the console.
A REST API is an API implementation that adheres to the REST architectural constraints. It acts as an interface. The communication between the client & the server happens over HTTP. A REST API takes advantage of the HTTP methodologies to establish communication between the client and the server. REST also enables servers to cache the response that improves the performance of the application. The communication between the client and the server is a stateless process. And by that, I mean every communication between the client and the server is like a new one.
There is no information or memory carried over from the previous communications. So, every time a client interacts with the backend, it has to send the authentication information to it as well. This enables the backend to figure out that the client is authorized to access the data or not.
With the implementation of a REST API the client gets the backend endpoints to communicate with. This entirely decouples the backend & the client code.
Might also be interesting for you to know that you can use:
{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)
to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
This is not jQuery, but it works for me. Taken from this site.
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
You need to edit your ~/.ssh/config file. Add something like the following:
Host example.com
Port 1234
A quick google search shows a few different resources that explain it in more detail than me.
//XAML Code
// ViewModel code
private CategoryModel _SelectedCategory;
public CategoryModel SelectedCategory
{
get { return _SelectedCategory; }
set
{
_SelectedCategory = value;
OnPropertyChanged("SelectedCategory");
}
}
private ObservableCollection<CategoryModel> _Categories;
public ObservableCollection<CategoryModel> Categories
{
get { return _Categories; }
set
{
_Categories = value;
_Categories.Insert(0, new CategoryModel()
{
CategoryId = 0,
CategoryName = " -- Select Category -- "
});
SelectedCategory = _Categories[0];
OnPropertyChanged("Categories");
}
}
print(*names)
this will work in python 3 if you want them to be printed out as space separated. If you need comma or anything else in between go ahead with .join() solution
What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.
The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.
You have uncommited changes on my_branch
that you want to commit to master
, without committing all the changes from my_branch
.
git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop
Start by merging master
into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.
The -u
option (aka --include-untracked
) in git stash -u
prevents you from losing untracked files when you later do git clean -f -d
within master
.
After git checkout master
it is important that you do NOT git stash pop
, because you will need this stash later. If you pop the stash created in my_branch
and then do git stash
in master
, you will cause needless merge conflicts when you later apply that stash in my_branch
.
git reset
unstages everything resulting from git stash apply
. For example, files that have been modified in the stash but do not exist in master
get staged as "deleted by us" conflicts.
git checkout .
and git clean -f -d
discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master
would cause needless merge conflicts when switching back to my_branch
.
The last git stash pop
will be based on the original my_branch
, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop
, git add .
, and git reset
.
innerText
has been added to Firefox and should be available in the FF45 release: https://bugzilla.mozilla.org/show_bug.cgi?id=264412
A draft spec has been written and is expected to be incorporated into the HTML living standard in the future: http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465
Note that currently the Firefox, Chrome and IE implementations are all incompatible. Going forward, we can probably expect Firefox, Chrome and Edge to converge while old IE remains incompatible.
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
Use +
, the string concatenation operator:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);
or use String.valueOf(int)
:
ed.setText(String.valueOf(x));
or use Integer.toString(int)
:
ed.setText(Integer.toString(x));
In Java 8, a better and more concise approach could be:
double[] arr = {13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4};
Double[] boxedarr = Arrays.stream( arr ).boxed().toArray( Double[]::new );
Arrays.sort(boxedarr, Collections.reverseOrder());
System.out.println(Arrays.toString(boxedarr));
This would give the reversed array and is more presentable.
Input: [13.6, 7.2, 6.02, 45.8, 21.09, 9.12, 2.53, 100.4]
Output: [100.4, 45.8, 21.09, 13.6, 9.12, 7.2, 6.02, 2.53]
This produces a nice effect.
<div style="border: 1px solid gray; padding: 1px">
<div style="border: 1px solid gray">
internal stuff
</div>
</div>
You can use Float.floatToIntBits().
Float.floatToIntBits(sectionID) == Float.floatToIntBits(currentSectionID)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
wstring outputMe = L"can" + L" concatenate\n";
OutputDebugString(outputMe.c_str());
Here is some code I wrote to help us identify and correct untrusted CONSTRAINTs in a DATABASE. It generates the code to fix each issue.
;WITH Untrusted (ConstraintType, ConstraintName, ConstraintTable, ParentTable, IsDisabled, IsNotForReplication, IsNotTrusted, RowIndex) AS
(
SELECT
'Untrusted FOREIGN KEY' AS FKType
, fk.name AS FKName
, OBJECT_NAME( fk.parent_object_id) AS FKTableName
, OBJECT_NAME( fk.referenced_object_id) AS PKTableName
, fk.is_disabled
, fk.is_not_for_replication
, fk.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( fk.parent_object_id), OBJECT_NAME( fk.referenced_object_id), fk.name) AS RowIndex
FROM
sys.foreign_keys fk
WHERE
is_ms_shipped = 0
AND fk.is_not_trusted = 1
UNION ALL
SELECT
'Untrusted CHECK' AS KType
, cc.name AS CKName
, OBJECT_NAME( cc.parent_object_id) AS CKTableName
, NULL AS ParentTable
, cc.is_disabled
, cc.is_not_for_replication
, cc.is_not_trusted
, ROW_NUMBER() OVER (ORDER BY OBJECT_NAME( cc.parent_object_id), cc.name) AS RowIndex
FROM
sys.check_constraints cc
WHERE
cc.is_ms_shipped = 0
AND cc.is_not_trusted = 1
)
SELECT
u.ConstraintType
, u.ConstraintName
, u.ConstraintTable
, u.ParentTable
, u.IsDisabled
, u.IsNotForReplication
, u.IsNotTrusted
, u.RowIndex
, 'RAISERROR( ''Now CHECKing {%i of %i)--> %s ON TABLE %s'', 0, 1'
+ ', ' + CAST( u.RowIndex AS VARCHAR(64))
+ ', ' + CAST( x.CommandCount AS VARCHAR(64))
+ ', ' + '''' + QUOTENAME( u.ConstraintName) + ''''
+ ', ' + '''' + QUOTENAME( u.ConstraintTable) + ''''
+ ') WITH NOWAIT;'
+ 'ALTER TABLE ' + QUOTENAME( u.ConstraintTable) + ' WITH CHECK CHECK CONSTRAINT ' + QUOTENAME( u.ConstraintName) + ';' AS FIX_SQL
FROM Untrusted u
CROSS APPLY (SELECT COUNT(*) AS CommandCount FROM Untrusted WHERE ConstraintType = u.ConstraintType) x
ORDER BY ConstraintType, ConstraintTable, ParentTable;
Another way of doing:
>>> seq = [1,2,3,'a', 'a', 1,2]
>> dict.fromkeys(seq).keys()
['a', 1, 2, 3]
What about using the .click() function and the tag?
(Compressed version)
<a id="downloadtag" href="examplefolder/testfile.txt" hidden download></a>_x000D_
_x000D_
<button onclick="document.getElementById('downloadtag').click()">Download</button>
_x000D_
Now you can trigger it with js. It also doesn't open, as other examples, image and text files!
(js-function version)
function download(){_x000D_
document.getElementById('downloadtag').click();_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<button onclick="download()">Download</button>_x000D_
<a id="downloadtag" href="coolimages/awsome.png" hidden download></a>
_x000D_
The problem with the set based approaches ("if random value in return values, try again") is that their runtime is undetermined due to collisions (which require another "try again" iteration), especially when a large amount of random values are returned from the range.
An alternative that isn't prone to this non-deterministic runtime is the following:
import bisect
import random
def fast_sample(low, high, num):
""" Samples :param num: integer numbers in range of
[:param low:, :param high:) without replacement
by maintaining a list of ranges of values that
are permitted.
This list of ranges is used to map a random number
of a contiguous a range (`r_n`) to a permissible
number `r` (from `ranges`).
"""
ranges = [high]
high_ = high - 1
while len(ranges) - 1 < num:
# generate a random number from an ever decreasing
# contiguous range (which we'll map to the true
# random number).
# consider an example with low=0, high=10,
# part way through this loop with:
#
# ranges = [0, 2, 3, 7, 9, 10]
#
# r_n :-> r
# 0 :-> 1
# 1 :-> 4
# 2 :-> 5
# 3 :-> 6
# 4 :-> 8
r_n = random.randint(low, high_)
range_index = bisect.bisect_left(ranges, r_n)
r = r_n + range_index
for i in xrange(range_index, len(ranges)):
if ranges[i] <= r:
# as many "gaps" we iterate over, as much
# is the true random value (`r`) shifted.
r = r_n + i + 1
elif ranges[i] > r_n:
break
# mark `r` as another "gap" of the original
# [low, high) range.
ranges.insert(i, r)
# Fewer values possible.
high_ -= 1
# `ranges` happens to contain the result.
return ranges[:-1]
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
You need to only grab the element with an appropriate jQuery selector and then the .val()
method to get the string contained in the input textbox and then call the .length
on that string.
$('input:text').val().length
However, be warned that if the selector matches multiple inputs, .val()
will only return the value of the first textbox. You can also change the selector to get a more specific element but keep the :text
to ensure it's an input textbox.
On another note, to get the length of a string contained in another, non-input element, you can use the .text()
function to get the string and then use .length
on that string to find its length.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
android:shape="rectangle">
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#ff9900" />
</selector>
You have to remove >
this from selector
root tag, like below
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
As well as move your code to shape
from selector
.
Nested classes are just like regular classes, but:
Some examples:
Assume you want to have a class SomeSpecificCollection
which would aggregate objects of class Element
. You can then either:
declare two classes: SomeSpecificCollection
and Element
- bad, because the name "Element" is general enough in order to cause a possible name clash
introduce a namespace someSpecificCollection
and declare classes someSpecificCollection::Collection
and someSpecificCollection::Element
. No risk of name clash, but can it get any more verbose?
declare two global classes SomeSpecificCollection
and SomeSpecificCollectionElement
- which has minor drawbacks, but is probably OK.
declare global class SomeSpecificCollection
and class Element
as its nested class. Then:
SomeSpecificCollection
you refer to just Element
, and everywhere else as SomeSpecificCollection::Element
- which looks +- the same as 3., but more clearSomeSpecificCollection
is also a class.In my opinion, the last variant is definitely the most intuitive and hence best design.
Let me stress - It's not a big difference from making two global classes with more verbose names. It just a tiny little detail, but imho it makes the code more clear.
This is especially useful for introducing typedefs or enums. I'll just post a code example here:
class Product {
public:
enum ProductType {
FANCY, AWESOME, USEFUL
};
enum ProductBoxType {
BOX, BAG, CRATE
};
Product(ProductType t, ProductBoxType b, String name);
// the rest of the class: fields, methods
};
One then will call:
Product p(Product::FANCY, Product::BOX);
But when looking at code completion proposals for Product::
, one will often get all the possible enum values (BOX, FANCY, CRATE) listed and it's easy to make a mistake here (C++0x's strongly typed enums kind of solve that, but never mind).
But if you introduce additional scope for those enums using nested classes, things could look like:
class Product {
public:
struct ProductType {
enum Enum { FANCY, AWESOME, USEFUL };
};
struct ProductBoxType {
enum Enum { BOX, BAG, CRATE };
};
Product(ProductType::Enum t, ProductBoxType::Enum b, String name);
// the rest of the class: fields, methods
};
Then the call looks like:
Product p(Product::ProductType::FANCY, Product::ProductBoxType::BOX);
Then by typing Product::ProductType::
in an IDE, one will get only the enums from the desired scope suggested. This also reduces the risk of making a mistake.
Of course this may not be needed for small classes, but if one has a lot of enums, then it makes things easier for the client programmers.
In the same way, you could "organise" a big bunch of typedefs in a template, if you ever had the need to. It's a useful pattern sometimes.
The PIMPL (short for Pointer to IMPLementation) is an idiom useful to remove the implementation details of a class from the header. This reduces the need of recompiling classes depending on the class' header whenever the "implementation" part of the header changes.
It's usually implemented using a nested class:
X.h:
class X {
public:
X();
virtual ~X();
void publicInterface();
void publicInterface2();
private:
struct Impl;
std::unique_ptr<Impl> impl;
}
X.cpp:
#include "X.h"
#include <windows.h>
struct X::Impl {
HWND hWnd; // this field is a part of the class, but no need to include windows.h in header
// all private fields, methods go here
void privateMethod(HWND wnd);
void privateMethod();
};
X::X() : impl(new Impl()) {
// ...
}
// and the rest of definitions go here
This is particularly useful if the full class definition needs the definition of types from some external library which has a heavy or just ugly header file (take WinAPI). If you use PIMPL, then you can enclose any WinAPI-specific functionality only in .cpp
and never include it in .h
.
Your Comparator would look like this:
public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
public int compare(GraduationCeremony o1, GraduationCeremony o2) {
int value1 = o1.campus.compareTo(o2.campus);
if (value1 == 0) {
int value2 = o1.faculty.compareTo(o2.faculty);
if (value2 == 0) {
return o1.building.compareTo(o2.building);
} else {
return value2;
}
}
return value1;
}
}
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0
).
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
Here is a SUMMARY of all the major answers above (or maybe below later :)
For modern browsers, put css wherever you like it. They would analyze your html file (which they call speculative parsing) and start downloading css in parallel with html parsing.
For old browsers keep putting css on top (if you don't want to show a naked but interactive page first).
For all browsers, put javascript as farther down on the page as possible, since it will halt parsing of your html. Preferably, download it asynchronously (i.e., ajax call)
There are also, some experimental results for a particular case which claims putting javascript first (as opposed to traditional wisdom of putting CSS first) gives better performance but there is no logical reasoning given for it, and lacks validation regarding widespread applicability, so you can ignore it for now.
So, to answer the question: Yes. The recommendation to include the CSS before JS is invalid for the modern browsers. Put CSS wherever you like, and put JS towards the end, as possible.
Try this:
delete from your_table;
delete from sqlite_sequence where name='your_table';
SQLite keeps track of the largest ROWID that a table has ever held using the special
SQLITE_SEQUENCE
table. TheSQLITE_SEQUENCE
table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
You don't need to create a button. The facility exists by default.
Just right click on the arrow buttons on the bottom left hand corner of the Excel window. These are the arrow buttons which if you left click move left or right one worksheet.
If you right-click on these arrows Excel will pop up a dialogue with a list of worksheets from which you can click to set your chosen sheet active.
Many string update functions in MySQL seems to be working like this:
If one argument is null
, then concatenation or other functions return null
too.
So, to update a field with null
value, first set it to a non-null value, such as ''
For example:
update table set field='' where field is null;
update table set field=concat(field,' append');
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
More pythonic way:
df = data_set[['data_date', 'data_1', 'data_2']]
map(tuple,df.values)
Ruby
Longitude -179.99999999..180
/^(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,8})?|180(?:\.0{1,8})?)$/ === longitude.to_s
Latitude -89.99999999..90
/^(-?[1-8]?\d(?:\.\d{1,8})?|90(?:\.0{1,8})?)$/ === latitude.to_s
If the web service being invoked uses windows integrated security, creating a NetworkCredential
from the current WindowsIdentity
should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.
Edit: To get the credentials for the current identity, use the following:
Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");
Use SHOW VARIABLES
:
Instead of this :
for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
It should be
for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
^ ^ ^
| | |
| | |
-------------------------------------------Note the changes
|
v |
if(rank==cards.substring(a,b){ |
-------------------------------------------------------------
|
v
System.out.println(c); //capital S in system
If you want to change the external terminal to the new windows terminal, here's how.
Go to your project path on CMD(command Prompt) and execute the following command:-
set FLASK_APP=ABC.py
SET FLASK_ENV=development
flask run -h [yourIP] -p 8080
you will get following o/p on CMD:-
Now you can access your flask app on another machine using http://[yourIP]:8080/ url
Try curl -v http://localhost:8080/
instead of 127.0.0.1
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
An Error "indicates serious problems that a reasonable application should not try to catch."
while
An Exception "indicates conditions that a reasonable application might want to catch."
Error along with RuntimeException
& their subclasses are unchecked
exceptions. All other Exception classes are checked
exceptions.
Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException
, ParseException
, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller
On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException
, ClassCastException
, etc. Many applications will use try-catch
or throws
clause for RuntimeExceptions
& their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException
is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.
Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch
clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError
, StackOverflowError
, etc.
Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions
(also unchecked exceptions) in code. Checked exceptions should be handled by the code.
In order to match a digit, you can use [0-9]
.
So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9]
and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]
. I do this a lot for zip codes.
<Hoverable hoverStyle={styles.linkHover}>
<a href="https://example.com" style={styles.link}>
Go
</a>
</Hoverable>
Where Hoverable is defined as:
function Hoverable(props) {
const [hover, setHover] = useState(false);
const child = Children.only(props.children);
const onHoverChange = useCallback(
e => {
const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
setHover(!hover);
if (child.props[name]) {
child.props[name](e);
}
},
[setHover, hover, child]
);
return React.cloneElement(child, {
onMouseEnter: onHoverChange,
onMouseLeave: onHoverChange,
style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
});
}
For bootstrap datetimepicker
, assign decade
value as follow:
$(".years").datetimepicker({
format: "yyyy",
startView: 'decade',
minView: 'decade',
viewSelect: 'decade',
autoclose: true,
});
You can use VBA - something like
Range("A1:A6").Interior.Color = RGB(127,187,199)
Just pass in the cell value.
You can use Collections.min and List.indexOf:
int minIndex = list.indexOf(Collections.min(list));
If you want to traverse the list only once (the above may traverse it twice):
public static <T extends Comparable<T>> int findMinIndex(final List<T> xs) {
int minIndex;
if (xs.isEmpty()) {
minIndex = -1;
} else {
final ListIterator<T> itr = xs.listIterator();
T min = itr.next(); // first element as the current minimum
minIndex = itr.previousIndex();
while (itr.hasNext()) {
final T curr = itr.next();
if (curr.compareTo(min) < 0) {
min = curr;
minIndex = itr.previousIndex();
}
}
}
return minIndex;
}
Use net use
or New-PSDrive
to create a new drive:
New-PsDrive: create a new PsDrive only visible in PowerShell environment:
New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
Net use: create a new drive visible in all parts of the OS.
Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
To access from remote server to mydb database only
GRANT ALL PRIVILEGES ON mydb.* TO 'root'@'192.168.2.21';
To access from remote server to all databases.
GRANT ALL PRIVILEGES ON * . * TO 'root'@'192.168.2.21';
const
applies for variables, and prevents them from being modified in your code.
constexpr
tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const
variables, etc. The link given by Oli has a lot of excellent examples.
Basically they are 2 different concepts altogether, and can (and should) be used together.
FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.
Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.
The ...For
extension methods on the HtmlHelper (e.g., DisplayFor
, TextBoxFor
, ElementFor
, etc...) take a property and nothing else. If you don't have a property, use the non-For
method (e.g., Display
, TextBox
, Element
, etc...).
The ...For
extension methods provides a way of simplifying postback by naming the control after the property. This is why it takes an expression and not simply a value. If you are not interested in this postback facilitation then do not use the ...For
methods at all.
Note: You should not be doing things like calling ToString
inside the view. This should be done inside the view model. I realize that a lot of demo projects put domain objects straight into the view. In my experience, this rarely works because it assumes that you do not want any formatting on the data in the domain entity. Best practice is to create a view model that wraps the entity into something that can be directly consumed by the view. Most of the properties in this view model should be strings that are already formatted or data for which you have element or display templates created.
For a minimum API level of 15, you'd want to use AppCompatActivity
. So for example, your MainActivity
would look like this:
public class MainActivity extends AppCompatActivity {
....
....
}
To use the AppCompatActivity
, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:
compile 'com.android.support:appcompat-v7:22:2.0'
You can use this AppCompat
as your main Activity
, which can then be used to launch Fragments or other Activities (this depends on what kind of app you're building).
The BigNerdRanch book is a good resource, but yeah, it's outdated. Read it for general information on how Android works, but don't expect the specific classes they use to be up to date.
In order to create a backup using pg_dump
that is compatible with pg_restore
you must use the --format=custom
/ -Fc
when creating your dump.
From the docs:
Output a custom-format archive suitable for input into pg_restore.
So your pg_dump
command might look like:
pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password
And your pg_restore
command:
pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump
That isn't the problem, Jack. Android SDK isn't x64, but works ok with x64 jvm (and x64 eclipse IDE).
As helios said, you must set project compatibility to Java 5.0 or Java 6.0.
To do that, 2 options:
"Android Tools -> Fix
Project Properties"
(if this din't work, try second option)"Properties -> Java
Compiler"
, check "Enable project specific settings" and select
1.5 or 1.6 from "Compiler compliance settings" select box.Add poster="placeholder.png"
to the video tag.
<video width="470" height="255" poster="placeholder.png" controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogg" type="video/ogg">
<source src="video.webm" type="video/webm">
<object data="video.mp4" width="470" height="255">
<embed src="video.swf" width="470" height="255">
</object>
</video>
Does that work?
Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)
If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)
Then edit .zshrc
vim ~/.zshrc
find plugins
section and update it to use ssh-agent
like so:
plugins=(ssh-agent git)
And that's all! You'll have ssh-agent
up and running every time you start your shell
Most common cause, considering that all certificates are installed properly is not specifying the Code Signing Identity in the Active Target settings along with the Project settings. Change these from to iPhone Developer (Xcode will select the right profile depending on App ID match).
In Xcode , change from Simulator to Device (in the dropdown at the top of the Xcode window), so that your target for application deployment will be the Device.
The default ID which is a wild card ID is like a catch all iD, when associated in Code Signing (if you are using sample files to build, they will most obviously not have com.coolapps.appfile imports, in which case without the 'Team Provisioning profile', your build would fail. So you would want to set this in your
Xcode->Project ->Edit Project Settings->Build (tab)->Code Signing Identity (header) ->Any iOS (change from Any iOS Simulator)->(select 'iPhone Developer' as value and it will default to the wildcard development provisioning profile (Team Provisioning Profile: * )
and also (VERY IMPORTANT)
Complete steps for a beginner at: http://codevelle.wordpress.com/2010/12/21/moving-from-ios-simulator-to-the-ios-device-smoothly-without-code-sign-error/
Changing the value property does not change the defaultValue
. In the code (retrieved with .html()
or innerHTML
) the value attribute will contain the defaultValue
, not the value property.
Disabling and Enabling All Foreign Keys
CREATE PROCEDURE pr_Disable_Triggers_v2
@disable BIT = 1
AS
DECLARE @sql VARCHAR(500)
, @tableName VARCHAR(128)
, @tableSchema VARCHAR(128)
-- List of all tables
DECLARE triggerCursor CURSOR FOR
SELECT t.TABLE_NAME AS TableName
, t.TABLE_SCHEMA AS TableSchema
FROM INFORMATION_SCHEMA.TABLES t
ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA
OPEN triggerCursor
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
IF @disable = 1
SET @sql = @sql + ' DISABLE TRIGGER ALL'
ELSE
SET @sql = @sql + ' ENABLE TRIGGER ALL'
PRINT 'Executing Statement - ' + @sql
EXECUTE ( @sql )
FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
END
CLOSE triggerCursor
DEALLOCATE triggerCursor
First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:
0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missingInside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.
Unlike C++, Java does not support user defined operator overloading. The overloading is done internally in java.
We can take +
(plus) for example:
int a = 2 + 4;
string = "hello" + "world";
Here, plus adds two integer numbers and concatenates two strings. So we can say that Java supports internal operator overloading but not user defined.
for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number};
can be used before the UPDATE
query
SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;
will limit the update to 100 rows
It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017
If you take advantage of width: 100vw;
and height: 100vh;
, the object with these styles applied will stretch to the full width and height of the device.
Also note, there are times padding and margins can get added to your view, by browsers and the like. I added a *
global no padding and margins so you can see the difference. Keep this in mind.
*{_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
.wrapper {_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
width: 100vw;_x000D_
height: 100vh;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
^(?!filename).+\.js
works for me
tested against:
A proper explanation for this regex can be found at Regular expression to match string not containing a word?
Look ahead is available since version 1.5 of javascript and is supported by all major browsers
Updated to match filename2.js and 2filename.js but not filename.js
(^(?!filename\.js$).).+\.js
If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html
I find it useful to understand the underlying tools. These are cl.exe (compiler) and link.exe (linker). You need to tell the compiler the signatures of the functions you want to call in the dynamic library (by including the library's header) and you need to tell the linker what the library is called and how to call it (by including the "implib" or import library).
This is roughly the same process gcc uses for linking to dynamic libraries on *nix, only the library object file differs.
Knowing the underlying tools means you can more quickly find the appropriate settings in the IDE and allows you to check that the commandlines generated are correct.
Say A.exe depends B.dll. You need to include B's header in A.cpp (#include "B.h"
) then compile and link with B.lib:
cl A.cpp /c /EHsc
link A.obj B.lib
The first line generates A.obj, the second generates A.exe. The /c
flag tells cl not to link and /EHsc
specifies what kind of C++ exception handling the binary should use (there's no default, so you have to specify something).
If you don't specify /c
cl will call link
for you. You can use the /link
flag to specify additional arguments to link
and do it all at once if you like:
cl A.cpp /EHsc /link B.lib
If B.lib is not on the INCLUDE
path you can give a relative or absolute path to it or add its parent directory to your include path with the /I
flag.
If you're calling from cygwin (as I do) replace the forward slashes with dashes.
If you write #pragma comment(lib, "B.lib")
in A.cpp you're just telling the compiler to leave a comment in A.obj telling the linker to link to B.lib. It's equivalent to specifying B.lib on the link commandline.
It should be noted as well that this will of course only find all those subclasses that exist on your current classpath. Presumably this is OK for what you are currently looking at, and chances are you did consider this, but if you have at any point released a non-final
class into the wild (for varying levels of "wild") then it is entirely feasible that someone else has written their own subclass that you will not know about.
Thus if you happened to be wanting to see all subclasses because you want to make a change and are going to see how it affects subclasses' behaviour - then bear in mind the subclasses that you can't see. Ideally all of your non-private methods, and the class itself should be well-documented; make changes according to this documentation without changing the semantics of methods/non-private fields and your changes should be backwards-compatible, for any subclass that followed your definition of the superclass at least.
Jquery: Fire Button click event Using enter Button Press try this::
tabindex="0" onkeypress="return EnterEvent(event)"
<!--Enter Event Script-->
<script type="text/javascript">
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=btnSave.UniqueID%>', "");
}
}
</script>
<!--Enter Event Script-->
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
You Can Use FORMAT if you column is a number Syntax like
FORMAT ( value, format [, culture ] ) In use like
FORMAT ( @d, 'D', 'en-US' )
or FORMAT(123456789,'###-##-####')
(But This works for only SQL SERVER 2012 And After)
In Use Like
UPDATE TABLE_NAME SET COLUMN_NAME = FORMAT(COLUMN_NAME ,'###-##-####')
And
if your column is Varchar Or Nvarchar use do like this
CONCAT(SUBSTRING(CELLPHONE,0,4),' ',SUBSTRING(CELLPHONE,4,3),'
',SUBSTRING(CELLPHONE,7,2) ,' ',SUBSTRING(CELLPHONE,9,2) )
You can always get help from
I was compiling my application targeting any CPU and main problem turned out that adobe reader was installed older v10.x needs to upgrade v11.x, this is the way how I get to resolve this issue.
From the terminal you can do:
\conninfo
I would suggest reading a documentation on their exhaustive list of all commands using:
\?
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by
<span style="color: #ff0000">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span style="color: #0000a0">summer</span>
trips!
</p>
Or you may want to use CSS classes instead:
<html>
<head>
<style type="text/css">
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
.date {
color: #ff0000;
}
.season { /* OK, a bit contrived... */
color: #0000a0;
}
</style>
</head>
<body>
<p>
Enter the competition by
<span class="date">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span class="season">summer</span>
trips!
</p>
</body>
</html>
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST
is an array, if the script loads and no data is present in the $_POST
variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST
is set... In fact $_POST
always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST
always exists in itself being either empty or has array values.
$_POST['value']
may not exist, thus throwing an "undefined index" error.
OK, so first this is breaking a basic security feature in PowerShell. With that understanding, here is how you can do it:
You may want to put a -NoProfile
argument in there too depending on what your profile does.
Simple we can remove new line by using text.replace(/\n/g, " ")
const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);
var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
_x000D_
Use LINQ Aggregate
method to convert array of integers to a comma separated string
var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);
output will be
1,2,3,4
This is one of the solution you can use if you have not .net 4 installed.
DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread
to your command line.
Things that DID NOT WORK for me with an iPad 4/iOS 6:
My request containing: Cache-Control:no-cache
//asp.net's:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Adding cache: false to my jQuery ajax call
$.ajax(
{
url: postUrl,
type: "POST",
cache: false,
...
Only this did the trick:
var currentTime = new Date();
var n = currentTime.getTime();
postUrl = "http://www.example.com/test.php?nocache="+n;
$.post(postUrl, callbackFunction);
My usual method is:
var require = function (src, cb) {
cb = cb || function () {};
var newScriptTag = document.createElement('script'),
firstScriptTag = document.getElementsByTagName('script')[0];
newScriptTag.src = src;
newScriptTag.async = true;
newScriptTag.onload = newScriptTag.onreadystatechange = function () {
(!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb());
};
firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag);
}
It works great and uses no page-reloads for me. I've tried the AJAX method (one of the other answers) but it doesn't seem to work as nicely for me.
Here's an explanation of how the code works for those that are curious: essentially, it creates a new script tag (after the first one) of the URL. It sets it to asynchronous mode so it doesn't block the rest of the code, but calls a callback when the readyState (the state of the content to be loaded) changes to 'loaded'.
Execute in command mode d$
.
As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.
var Mongoose = require('mongoose').Mongoose;
var instance1 = new Mongoose();
instance1.connect('foo');
var instance2 = new Mongoose();
instance2.connect('bar');
This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.
There's no real danger in not freeing your variables, but if you assign a pointer to a block of memory to a different block of memory without freeing the first block, the first block is no longer accessible but still takes up space. This is what's called a memory leak, and if you do this with regularity then your process will start to consume more and more memory, taking away system resources from other processes.
If the process is short-lived you can often get away with doing this as all allocated memory is reclaimed by the operating system when the process completes, but I would advise getting in the habit of freeing all memory you have no further use for.
You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.
Based only on your style you would have:
<a href="home.com" id="logo"></a>
The following code works for me on owl carousel .
https://github.com/OwlFonk/OwlCarousel
$(".owl-carousel").owlCarousel({
items: 1,
autoplay: true,
navigation: true,
navigationText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});
For OwlCarousel2
https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html
$(".owl-carousel").owlCarousel({
items: 1,
autoplay: true,
nav: true,
navText: ["<i class='fa fa-angle-left'></i>", "<i class='fa fa-angle-right'></i>"]
});
I faced the issue, In my understanding, It is because of invalid combination of Android Studio And Gradle Plugin versions. I was using Gradle version 5.4.1 and Studio version 3.4, hence I updated the Android studio to 3.5 and the issue got resolved
Just set the height and width where you are adding that logo. I tried and its working fine
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit()
method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
A nice handy overview table from the Bash Hackers Wiki:
Syntax | Effective result |
---|---|
$* |
$1 $2 $3 … ${N} |
$@ |
$1 $2 $3 … ${N} |
"$*" |
"$1c$2c$3c…c${N}" |
"$@" |
"$1" "$2" "$3" … "${N}" |
where c
in the third row is the first character of $IFS
, the Input Field Separator, a shell variable.
If the arguments are to be stored in a script variable and the arguments are expected to contain spaces, I wholeheartedly recommend employing a "$*"
trick with the input field separator set to tab IFS=$'\t'
.
git ls-remote | cut -f1 | git cat-file --batch-check >&-
will list everything referenced in any remote that isn't in your repo. To catch remote ref changes to things you already had (e.g. resets to previous commits) takes a little more:
git pack-refs --all
mine=`mktemp`
sed '/^#/d;/^^/{G;s/.\(.*\)\n.* \(.*\)/\1 \2^{}/;};h' .git/packed-refs | sort -k2 >$mine
for r in `git remote`; do
echo Checking $r ...
git ls-remote $r | sort -k2 | diff -b - $mine | grep ^\<
done
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
Short Summary
Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
Long Answer
Firstly, one needs to know what's Directory Service
.
Directory Service is a software system that stores, organises, and provides access to information in a computer operating system's directory. In software engineering, a directory is a map between names and values. It allows the lookup of named values, similar to a dictionary.
For more details, read https://en.wikipedia.org/wiki/Directory_service
Secondly,as one could imagine, different vendors implement all kinds of forms of directory service, which is harmful to multi-vendor interoperability.
Thirdly, so in the 1980s, the ITU and ISO came up with a set of standards - X.500, for directory services, initially to support the requirements of inter-carrier electronic messaging and network name lookup.
Fourthly, so based on this standard, Lightweight Directory Access Protocol, LDAP, is developed. It uses the TCP/IP stack and a string encoding scheme of the X.500 Directory Access Protocol (DAP), giving it more relevance on the Internet.
Lastly, based on this LDAP/X.500 stack, Microsoft implemented a modern directory service for Windows, originating from the X.500 directory, created for use in Exchange Server. And this implementation is called Active Directory
.
So in a short summary, Active Directory
is a directory services implemented by Microsoft, and it supports Lightweight Directory Access Protocol
(LDAP).
PS[0]: This answer heavily copies content from the wikipedia page listed above.
PS[1]: To know why it may be better use directory service rather just using a relational database, read https://en.wikipedia.org/wiki/Directory_service#Comparison_with_relational_databases
Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:
''
or ""
) are not allowed to have linebreaks.${myVariable}
syntax.const name = 'Willem';_x000D_
const age = 26;_x000D_
_x000D_
const story = `_x000D_
My name is: ${name}_x000D_
And I'm: ${age} years old_x000D_
`;_x000D_
_x000D_
console.log(story);
_x000D_
Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.
Take a look at Shell MegaPack control set. It provides Windows Explorer like folder/file browsing with most of the features and functionality like context menus, renaming, drag-drop, icons, overlay icons, thumbnails, etc
Database ? right click Properties ? file ? add another log file with a different name and set the path the same as the old log file with a different file name.
The database automatically picks up the newly created log file.
Try This:
/// <summary>
/// AlphabetizeDropDownList alphabetizes a given dropdown list by it's displayed text.
/// </summary>
/// <param name="dropDownList">The drop down list you wish to modify.</param>
/// <remarks></remarks>
private void AlphabetizeDropDownList(ref DropDownList dropDownList)
{
//Create a datatable to sort the drop down list items
DataTable machineDescriptionsTable = new DataTable();
machineDescriptionsTable.Columns.Add("DescriptionCode", typeof(string));
machineDescriptionsTable.Columns.Add("UnitIDString", typeof(string));
machineDescriptionsTable.AcceptChanges();
//Put each of the list items into the datatable
foreach (ListItem currentDropDownListItem in dropDownList.Items) {
string currentDropDownUnitIDString = currentDropDownListItem.Value;
string currentDropDownDescriptionCode = currentDropDownListItem.Text;
DataRow currentDropDownDataRow = machineDescriptionsTable.NewRow();
currentDropDownDataRow["DescriptionCode"] = currentDropDownDescriptionCode.Trim();
currentDropDownDataRow["UnitIDString"] = currentDropDownUnitIDString.Trim();
machineDescriptionsTable.Rows.Add(currentDropDownDataRow);
machineDescriptionsTable.AcceptChanges();
}
//Sort the data table by description
DataView sortedView = new DataView(machineDescriptionsTable);
sortedView.Sort = "DescriptionCode";
machineDescriptionsTable = sortedView.ToTable();
//Clear the items in the original dropdown list
dropDownList.Items.Clear();
//Create a dummy list item at the top
ListItem dummyListItem = new ListItem(" ", "-1");
dropDownList.Items.Add(dummyListItem);
//Begin transferring over the items alphabetically from the copy to the intended drop
downlist
foreach (DataRow currentDataRow in machineDescriptionsTable.Rows) {
string currentDropDownValue = currentDataRow["UnitIDString"].ToString().Trim();
string currentDropDownText = currentDataRow["DescriptionCode"].ToString().Trim();
ListItem currentDropDownListItem = new ListItem(currentDropDownText, currentDropDownValue);
//Don't deal with dummy values in the list we are transferring over
if (!string.IsNullOrEmpty(currentDropDownText.Trim())) {
dropDownList.Items.Add(currentDropDownListItem);
}
}
}
This will take a given drop down list with a Text and a Value property of the list item and put them back into the given drop down list. Best of Luck!
This happens when you index a row/column with a number that is larger than the dimensions of your dataframe
. For instance, getting the eleventh column when you have only three.
import pandas as pd
df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})
You have 5 rows and three columns:
Name City Car
0 Mark Lisbon Tesla
1 Laura Montreal Audi
2 Adam Lisbon Porsche
3 Roger Berlin Ford
4 Anna Glasgow Honda
Let's try to index the eleventh column (it doesn't exist):
df.iloc[:, 10] # there is obviously no 11th column
IndexError: single positional indexer is out-of-bounds
If you are a beginner with Python, remember that df.iloc[:, 10]
would refer to the eleventh column.
You can use flutter commons package to display different types of toasts like success, error, warning and info in flutter applications.
successToast("Success Message");
This works:
$string = 'A B C D';
$arr = preg_split('/[\s]+/', $string);
Updated 2018
See if this example helps: http://bootply.com/mQh8DyRfWY
The brand is centered using..
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
top: 0;
text-align: center;
margin: auto;
}
Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner
.
EDIT - Another approach is using transform: translateX(-50%);
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
http://www.bootply.com/V7vKDfk46G
In Bootstrap 4, mx-auto
or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.
Also see:
I totally do not get it, why everyone is suggesting the genric type over the array particularly for this question.
What if my need is to index n
different arraylists.
With declaring List<List<Integer>>
I need to create n
ArrayList<Integer>
objects manually or put a for loop to create n
lists or some other way, in any way it will always be my duty to create n
lists.
Isn't it great if we declare it through casting as List<Integer>[] = (List<Integer>[]) new List<?>[somenumber]
. I see it as a good design where one do not have to create all the indexing object (arraylists) by himself
Can anyone enlighten me why this (arrayform) will be a bad design and what are its disadvantages?
Fascinating. I needed to improve the speed of a series of loops that must perform matching index determination in this same way. So I decided to time all the solutions here, along with some riff's.
Here are my speed tests for Python 2.7.10:
import timeit
timeit.timeit('N.any(N.in1d(sids, val))', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')
18.86137104034424
timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = [20010401010101+x for x in range(1000)]')
15.061666011810303
timeit.timeit('N.in1d(sids, val)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')
11.613027095794678
timeit.timeit('N.any(val == sids)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')
7.670552015304565
timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')
5.610057830810547
timeit.timeit('val == sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')
1.6632978916168213
timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = set([20010401010101+x for x in range(1000)])')
0.0548710823059082
timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = dict(zip([20010401010101+x for x in range(1000)],[True,]*1000))')
0.054754018783569336
Very surprising! Orders of magnitude difference!
To summarize, if you just want to know whether something's in a 1D list or not:
If you want to know where something is in the list as well (order is important):
Here is your code for add data into both tableView:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table1Text: UITextField!
@IBOutlet weak var table2Text: UITextField!
@IBOutlet weak var table1: UITableView!
@IBOutlet weak var table2: UITableView!
var table1Data = ["a"]
var table2Data = ["1"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func addData(sender: AnyObject) {
//add your data into tables array from textField
table1Data.append(table1Text.text)
table2Data.append(table2Text.text)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//reload your tableView
self.table1.reloadData()
self.table2.reloadData()
})
table1Text.resignFirstResponder()
table2Text.resignFirstResponder()
}
//delegate methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == table1 {
return table1Data.count
}else if tableView == table2 {
return table2Data.count
}
return Int()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == table1 {
let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table1Data[row]
return cell
}else if tableView == table2 {
let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = table2Data[row]
return cell
}
return UITableViewCell()
}
}
And your result will be:
Simply, you use ADB, as follows:
adb install <path to apk>
Also see the section Installing an Application in Android Debug Bridge.
You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.
As mentioned in the github issue originally linked by @peter in the comments:
const freshFruits = (fruits as (Apple | Pear)[]).filter((fruit: (Apple | Pear)) => !fruit.isDecayed);
you can easily do like this:-
<table>
<thead>
<tr>
<th bgcolor="#5D7B9D"><font color="#fff">Header 1</font></th>
<th bgcolor="#5D7B9D"><font color="#fff">Header 2</font></th>
<th bgcolor="#5D7B9D"><font color="#fff">Header 3</font></th>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
<td>blah blah</td>
<td>blah blah</td>
</tr>
</tbody>
</table>
Demo:- http://jsfiddle.net/VWdxj/7/
In [3]: df[df['ids'].str.contains("ball")]
Out[3]:
ids vals
0 aball 1
1 bball 2
3 fball 4
I wrote this program to do the math for you. Just enter in the summary statistics. No need to provide an array:
One-Sample Z-Test for a Population Proportion:
To do this for mean rather than proportion, change the formula for z accordingly
EDIT:
Here is the content from the link:
import scipy.stats as stats
import math
def one_sample_ztest_pop_proportion(tail, p, pbar, n, alpha):
#Calculate test stat
sigma = math.sqrt((p*(1-p))/(n))
z = round((pbar - p) / sigma, 2)
if tail == 'lower':
pval = round(stats.norm(p, sigma).cdf(pbar),4)
print("Results for a lower tailed z-test: ")
elif tail == 'upper':
pval = round(1 - stats.norm(p, sigma).cdf(pbar),4)
print("Results for an upper tailed z-test: ")
elif tail == 'two':
pval = round(stats.norm(p, sigma).cdf(pbar)*2,4)
print("Results for a two tailed z-test: ")
#Print test results
print("Test statistic = {}".format(z))
print("P-value = {}".format(pval))
print("Confidence = {}".format(alpha))
#Compare p-value to confidence level
if pval <= alpha:
print("{} <= {}. Reject the null hypothesis.".format(pval, alpha))
else:
print("{} > {}. Do not reject the null hypothesis.".format(pval, alpha))
#one_sample_ztest_pop_proportion('upper', .20, .25, 400, .05)
#one_sample_ztest_pop_proportion('two', .64, .52, 100, .05)
With the default Jenkins installation using Homebrew on macOS this will output the initial password for the admin
user:
sudo cat /Users/Shared/Jenkins/Home/secrets/initialAdminPassword
You can not "attach" a SASS/SCSS file to an HTML document.
SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.
There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.
It's as simple as adding 2 lines of code to your HTML file.
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
Use of sort
can result in warning message. See github discussion.
So you might wanna use sort_values
, docs here
Then your code can look like this:
df = df.sort_values(by=['c1','c2'], ascending=[False,True])
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
Use the Boost C++ libraries. There is a CRC included there and the license is good.
Here's some code I use to deal with this.
First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":
jQuery( '.element' ).show().css( 'visibility', 'visible' );
Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:
jQuery( '.element' ).toggleClass( 'hidden' );
Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:
jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );
When I was facing this issue, I simply put just getter setter methods and my issues were resolved.
I am using Spring boot version 2.0.
Here is how you can get a number of table columns using Python 3, sqlite3 and pragma statement:
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE tablename (d1 VARCHAR, d2 VARCHAR)")
cur = con.cursor()
cur.execute("PRAGMA table_info(tablename)")
print(len(cur.fetchall()))
This way you can handle the both cases - if the page is already loaded or not:
document.onreadystatechange = function(){
if (document.readyState === "complete") {
myFunction();
}
else {
window.onload = function () {
myFunction();
};
};
}
You need to create an alias for the mother.kind
. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
This work for me.
<input oninvalid="this.setCustomValidity('custom text on invalid')" onchange="this.setCustomValidity('')" required>
onchange is a must!
There is also an experimental technology called Broadcast Channel API
that is designed specifically for communication between different browser contexts with same origin. You can post messages to and recieve messages from another browser context without having a reference to it:
var channel = new BroadcastChannel("foo");
channel.onmessage = function( e ) {
// Process messages from other contexts.
};
// Send message to other listening contexts.
channel.postMessage({ value: 42, type: "bar"});
Obviously this is experiental technology and is not supported accross all browsers yet.
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
Source: http://www.christianschenk.org/blog/php-curl-allow-url-fopen/
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
Use this code very simple solution
@Override
public void onBackPressed() {
super.onBackPressed(); // this line close the app on backpress
}
Actually we get this error also when we create canvas in javascript as below.
document.createElement('canvas');
Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.
Thanks
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
You can't change a Font once it's created - so you need to create a new one:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
As suggested by Alan, function 'mapply' applies a function to multiple Multiple Lists or Vector Arguments:
mapply(myfun, arg1, arg2)
See man page: https://stat.ethz.ch/R-manual/R-devel/library/base/html/mapply.html
Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:
def module_register_class_constants(klass, attr_prefix):
globals().update(
(name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
)
class Animal(object):
SIZE_HUGE = "Huge"
SIZE_BIG = "Big"
module_register_class_constants(Animal, "SIZE_")
class Horse(Animal):
def printSize(self):
print SIZE_BIG
I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.
<audio controls>
<source src="horse.mp3" type="audio/mpeg">
<embed height="50" width="100" src="horse.mp3">
</audio>
Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.
Here is another way to do this - using the API function WideCharToMultiByte:
Option Explicit
Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long, _
ByVal lpMultiByteStr As Long, _
ByVal cbMultiByte As Long, _
ByVal lpDefaultChar As Long, _
ByVal lpUsedDefaultChar As Long) As Long
Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
Erase b
len_s = Len(s)
If len_s = 0 Then _
Err.Raise 30030, , "Len(WideChars) = 0"
ptr_s = StrPtr(s)
size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
If size = 0 Then _
Err.Raise 30030, , "WideCharToMultiByte() = 0"
ReDim b(0 To size - 1)
If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub
Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
s = "äöüßµ@€|~{}[]²³\ .." & _
" OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
file = FreeFile
Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
getUtf8 s, b
Put #file, , b
Close #file
End Sub
They always say it depends but when it comes to mirroring a website The best exists httrack. It is super fast and easy to work. The only downside is it's so called support forum but you can find your way using official documentation. It has both GUI and CLI interface and it Supports cookies just read the docs This is the best.(Be cureful with this tool you can download the whole web on your harddrive)
httrack -c8 [url]
By default maximum number of simultaneous connections limited to 8 to avoid server overload
Given a column of numbers:
lst = []
cols = ['A']
for a in range(100, 105):
lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df
A
0 100
1 101
2 102
3 103
4 104
You can reference the previous row with shift:
df['Change'] = df.A - df.A.shift(1)
df
A Change
0 100 NaN
1 101 1.0
2 102 1.0
3 103 1.0
4 104 1.0
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
$url="http://example.com";
$html = file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src');
}
sudo du -x -h / | sort -h | tail -40
/tmp
or /home/user_name/.cache
folder if these are taking up a lot of memory. You can do this by running sudo rm -R /path/to/folder
Step 2 outlines fairly common folders to delete from (/tmp
and /home/user_name/.cache
). If you get back other results when running the first command showing you have lots of memory being used elsewhere, I advise being a bit more cautious when deleting from those locations.
You have to change delimiter before using triggers, stored procedures and so on.
delimiter //
create procedure ProG()
begin
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;
Here is for Android studio 2.3.3
I did not find any Project Structure under File
menu.
So here are steps in pictures
Swift 5 & String Response, In presentable format
public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
var str = hours > 0 ? "\(hours) h" : ""
str = minutes > 0 ? str + " \(minutes) min" : str
str = seconds > 0 ? str + " \(seconds) sec" : str
return str
}
public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Usage:
print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"
you can try implementing this ForkJoinWorkerThreadFactory and inject it to Fork-Join class.
public ForkJoinPool(int parallelism,
ForkJoinWorkerThreadFactory factory,
UncaughtExceptionHandler handler,
boolean asyncMode) {
this(checkParallelism(parallelism),
checkFactory(factory),
handler,
asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
"ForkJoinPool-" + nextPoolId() + "-worker-");
checkPermission();
}
you can use this constructor of Fork-Join pool to do this.
notes:-- 1. if you use this, take into consideration that based on your implementation of new threads, scheduling from JVM will be affected, which generally schedules fork-join threads to different cores(treated as a computational thread). 2. task scheduling by fork-join to threads won't get affected. 3. Haven't really figured out how parallel stream is picking threads from fork-join(couldn't find proper documentation on it), so try using a different threadNaming factory so as to make sure, if threads in parallel stream are being picked from customThreadFactory that you provide. 4. commonThreadPool won't use this customThreadFactory.
I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.
Not package.json
, but for whatever reason, my node_modules/
had become read-only. Resetting that fixed this.
I was getting this error in Flutter. Check the debug console and find this command
Use.RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("")
And copy the device id from list to MobileAdTargetingInfo testDevices and it will work !!!
The PHP function echo() prints out its input to the web server response.
echo("Hello World!");
prints out Hello World! to the web server response.
echo("<prev>");
prints out the tag to the web server response.
echo do not require valid HTML tags. You can use PHP to print XML, images, excel, HTML and so on.
<prev> is not a HTML tag. Is is a valid XML tag, but since I don't know what page you are working in, i cannot tell you what it is. Maybe it is the root tag of a XML page, or a miswritten <pre> tag.
I was looking for a reliable method to do this all the way down to API 9 at least. The "casting to LayerDrawble" solution seemed like a risky solution to me, and when I tested it out on an Android phone on 2.3, it casted successfully but the call to DrawableCompat.setTint(...) did not have any effect.
The need to load drawable assets did not seem like a good solution to me either.
I decided to code my own solution which is a class extending AppCompatRatingBar, using a custom Drawable taking care of drawing the stars programmatically. It works perfectly for my needs, I'll post it in case it helps anyone:
https://gist.github.com/androidseb/2b8044c90a07c7a52b4bbff3453c8460
The link is easier because you can get the full file directly, but here is the full code just in case:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatRatingBar;
import android.util.AttributeSet;
/**
* @author androidseb
* <p/>
* Extends AppCompatRatingBar with the ability to tint the drawn stars when selected, pressed and un-selected.
* Limitation: Only draws full stars.
*/
public class TintableRatingBar extends AppCompatRatingBar {
private TintableRatingBarProgressDrawable progressDrawable;
public TintableRatingBar(final Context context) {
super(context);
init();
}
public TintableRatingBar(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public TintableRatingBar(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
progressDrawable = new TintableRatingBarProgressDrawable();
setProgressDrawable(progressDrawable);
}
public void setCustomTintColors(final int _uncheckedColor, final int _pressedColor, final int _checkedColor) {
progressDrawable.setRatingMaxLevelValue(getMax() * 1000);
progressDrawable.setUnCheckedColor(_uncheckedColor);
progressDrawable.setPressedColor(_pressedColor);
progressDrawable.setCheckedColor(_checkedColor);
invalidate();
}
public class TintableRatingBarProgressDrawable extends Drawable {
private static final int STAR_COUNT = 5;
private static final int STAR_BRANCHES_COUNT = 5;
/** Sets the max level value: if the level is at the max, then all stars are selected. */
private int ratingMaxLevelValue = 10000;
/** Color to be painted for unselected stars */
private int uncheckedColor = Color.GRAY;
/** Color to be painted for unselected stars when the ratingbar is pressed */
private int pressedColor = Color.CYAN;
/** Color to be painted for selected stars */
private int checkedColor = Color.BLUE;
@Override
public void setAlpha(final int _i) {
}
@Override
public void setColorFilter(final ColorFilter _colorFilter) {
}
@Override
public boolean isStateful() {
return true;
}
@Override
public boolean setState(final int[] stateSet) {
final boolean res = super.setState(stateSet);
invalidateSelf();
return res;
}
@Override
public int getOpacity() {
return 255;
}
public void setRatingMaxLevelValue(final int _ratingMaxLevelValue) {
ratingMaxLevelValue = _ratingMaxLevelValue;
}
public void setUnCheckedColor(final int _uncheckedColor) {
uncheckedColor = _uncheckedColor;
}
public void setPressedColor(final int _pressedColor) {
pressedColor = _pressedColor;
}
public void setCheckedColor(final int _checkedColor) {
checkedColor = _checkedColor;
}
@Override
public void draw(final Canvas _canvas) {
boolean pressed = false;
for (int i : getState()) {
if (i == android.R.attr.state_pressed) {
pressed = true;
}
}
final int level = (int) Math.ceil(getLevel() / (double) ratingMaxLevelValue * STAR_COUNT);
final int starRadius = Math.min(getBounds().bottom / 2, getBounds().right / STAR_COUNT / 2);
for (int i = 0; i < STAR_COUNT; i++) {
final int usedColor;
if (level >= i + 1) {
usedColor = checkedColor;
} else if (pressed) {
usedColor = pressedColor;
} else {
usedColor = uncheckedColor;
}
drawStar(_canvas, usedColor, (i * 2 + 1) * starRadius, getBounds().bottom / 2, starRadius,
STAR_BRANCHES_COUNT);
}
}
private void drawStar(final Canvas _canvas, final int _color, final float _centerX, final float _centerY,
final float _radius, final int _branchesCount) {
final double rotationAngle = Math.PI * 2 / _branchesCount;
final double rotationAngleComplement = Math.PI / 2 - rotationAngle;
//Calculating how much space is left between the bottom of the star and the bottom of the circle
//In order to be able to center the star visually relatively to the square when drawn
final float bottomOffset = (float) (_radius - _radius * Math.sin(rotationAngle / 2) / Math.tan(
rotationAngle / 2));
final float actualCenterY = _centerY + (bottomOffset / 2);
final Paint paint = new Paint();
paint.setColor(_color);
paint.setStyle(Style.FILL);
final Path path = new Path();
final float relativeY = (float) (_radius - _radius * (1 - Math.sin(rotationAngleComplement)));
final float relativeX = (float) (Math.tan(rotationAngle / 2) * relativeY);
final PointF a = new PointF(-relativeX, -relativeY);
final PointF b = new PointF(0, -_radius);
final PointF c = new PointF(relativeX, -relativeY);
path.moveTo(_centerX + a.x, actualCenterY + a.y);
_canvas.save();
for (int i = 0; i < _branchesCount; i++) {
path.lineTo(_centerX + b.x, actualCenterY + b.y);
path.lineTo(_centerX + c.x, actualCenterY + c.y);
rotationToCenter(b, rotationAngle);
rotationToCenter(c, rotationAngle);
}
_canvas.drawPath(path, paint);
_canvas.restore();
}
private void rotationToCenter(final PointF _point, final double _angleRadian) {
final float x = (float) (_point.x * Math.cos(_angleRadian) - _point.y * Math.sin(_angleRadian));
final float y = (float) (_point.x * Math.sin(_angleRadian) + _point.y * Math.cos(_angleRadian));
_point.x = x;
_point.y = y;
}
}
}
On your command prompt type sqllocaldb start
Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />
Configure your DB connection in the 'Manage DB Connections dialog. Select 'Standard (TCP/IP)' as connection method.
See this page for more details http://dev.mysql.com/doc/workbench/en/wb-manage-db-connections.html
According to this other page a socket file is used even if you specify localhost.
A Unix socket file is used if you do not specify a host name or if you specify the special host name localhost.
It also shows how to check on your server by running these commands:
If a mysqld process is running, you can check it by trying the following commands. The port number or Unix socket file name might be different in your setup. host_ip represents the IP address of the machine where the server is running.
shell> mysqladmin version
shell> mysqladmin variables
shell> mysqladmin -h `hostname` version variables
shell> mysqladmin -h `hostname` --port=3306 version
shell> mysqladmin -h host_ip version
shell> mysqladmin --protocol=SOCKET --socket=/tmp/mysql.sock version
A more pythonic way would be to use context managers like the code below:
from tempfile import mkstemp
from shutil import move
from os import remove
def replace(source_file_path, pattern, substring):
fh, target_file_path = mkstemp()
with open(target_file_path, 'w') as target_file:
with open(source_file_path, 'r') as source_file:
for line in source_file:
target_file.write(line.replace(pattern, substring))
remove(source_file_path)
move(target_file_path, source_file_path)
You can find the full snippet here.
You need to change
<activity
android:name=".YOUR ACTIVITY"
android:theme="@style/AppTheme.NoActionBar" />
</application>`
these lines in the manifest.It will perfectly work for me.
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
You can do this a few ways. One, simply add this meta tag to your head
:
<meta http-equiv="Cache-control" content="no-cache">
If you want to remove the document from cache, expires
meta tag should work to delete it by setting its content
attribute to -1
like so:
<meta http-equiv="Expires" content="-1">
http://www.metatags.org/meta_http_equiv_cache_control
Also, IE should give you the latest content for the main page. If you are having issues with external documents, like CSS and JS, add a dummy param at the end of your URLs with the current time in milliseconds so that it's never the same. This way IE, and other browsers, will always serve you the latest version. Here is an example:
<script src="mysite.com/js/myscript.js?12345">
UPDATE 1
After reading the comments I realize you wanted to programmatically erase the cache and not every time. What you could do is have a function in JS like:
eraseCache(){
window.location = window.location.href+'?eraseCache=true';
}
Then, in PHP let's say, you do something like this:
<head>
<?php
if (isset($_GET['eraseCache'])) {
echo '<meta http-equiv="Cache-control" content="no-cache">';
echo '<meta http-equiv="Expires" content="-1">';
$cache = '?' . time();
}
?>
<!-- ... other head HTML -->
<script src="mysite.com/js/script.js<?= $cache ?>"
</head>
This isn't tested, but should work. Basically, your JS function, if invoked, will reload the page, but adds a GET param to the end of the URL. Your site would then have some back-end code that looks for this param. If it exists, it adds the meta tags and a cache variable that contains a timestamp and appends it to the scripts and CSS that you are having caching issues with.
UPDATE 2
The meta tag indeed won't erase the cache on page load. So, technically you would need to run the eraseCache function in JS, once the page loads, you would need to load it again for the changes to take place. You should be able to fix this with your server side language. You could run the same eraseCache JS function, but instead of adding the meta tags, you need to add HTTP Cache headers:
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
?>
<!-- Here you'd start your page... -->
This method works immediately without the need for page reload because it erases the cache before the page loads and also before anything is run.
your initial request is "I have a large PDF file that is a floor map for a building. "
I am afraid to tell you this might be harder than you guess.
Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.
Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).
see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163
If you are trying to pull the value from a field, you could use:
select extract(month from [field_name])
from [table_name]
You can also insert day or year for the "month" extraction value above.
You should really use Angular UI for that needs. Check it out: Angular UI Dialog
In a nutshell, with Angular UI dialog, you can pass variable from a controller to the dialog controller using resolve
. Here's your "from" controller:
var d = $dialog.dialog({
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '<url_of_your_template>',
controller: 'MyDialogCtrl',
// Interesting stuff here.
resolve: {
username: 'foo'
}
});
d.open();
And in your dialog controller:
angular.module('mymodule')
.controller('MyDialogCtrl', function ($scope, username) {
// Here, username is 'foo'
$scope.username = username;
}
EDIT: Since the new version of the ui-dialog, the resolve entry becomes:
resolve: { username: function () { return 'foo'; } }
Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)
"Select destination and Press Enter or Choose Paste"
Then you press whether Enter or choose paste to paste the value of the cell.
If you didn't press Esc afterwards you will be able to paste the value of the cell several times
Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.
And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'
Look at this:
function isPalindrome(word){
if(word==null || word.length==0){
// up to you if you want true or false here, don't comment saying you
// would put true, I put this check here because of
// the following i < Math.ceil(word.length/2) && i< word.length
return false;
}
var lastIndex=Math.ceil(word.length/2);
for (var i = 0; i < lastIndex && i< word.length; i++) {
if (word[i] != word[word.length-1-i]) {
return false;
}
}
return true;
}
Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!
Since the string is an array of char no need to use charAt functions!!!
Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome
However, VolkerK's solution is the best to avoid miss couple between email and username. So you have to generate HTML code with PHP like this:
<? foreach ($i = 0; $i < $total_data; $i++) : ?>
<input type="text" name="name[<?= $i ?>]" />
<input type="text" name="email[<?= $i ?>]" />
<? endforeach; ?>
Change $total_data to suit your needs. To show it, just like this:
$output = array_map(create_function('$name, $email', 'return "The name is $name and email is $email, thank you.";'), $_POST['name'], $_POST['email']);
echo implode('<br>', $output);
Assuming the data was sent using POST method.
To select data in numerical range you can use BETWEEN
which is inclusive.
SELECT JOB FROM MYTABLE WHERE ID BETWEEN 10 AND 15;
Dir has also shorter syntax to get an array of all files from directory:
Dir['dir/to/files/*'].each do |fname|
# do something with fname
end
Prepend the url prefix git+
(See VCS Support):
pip install git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6
And specify the branch name without the leading /
.
Still missing this simple version:
SELECT * FROM myTable WHERE `col1` + 0 = `col1`
(addition should be faster as multiplication)
Or slowest version for further playing:
SELECT *,
CASE WHEN `col1` + 0 = `col1` THEN 1 ELSE 0 END AS `IS_NUMERIC`
FROM `myTable`
HAVING `IS_NUMERIC` = 1
The following answer could be helpful for the first part of your question:
Let me assume that you have done the 'this' binding of 'sendThru' function.
The below functions clears the input fields when the method is triggered.
sendThru() {
this.inputTitle.value = "";
this.inputEntry.value = "";
}
Refs can be written as inline function expression:
ref={el => this.inputTitle = el}
where el
refers to the component.
When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.
Read more about it here.
A char can hold a single character only, a character literal is a single character in single quote, i.e. '&'
- if you have more characters than one you want to use a string, for that you have to use double quotes:
case "&&":
You probably just need to provide a user name and password in your connectionstring and set Integrated Security=false
In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.
For eg:
public class MyClass
{
public int Id {get; set;}
}
MyClass myClass;
myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...
You will have to use:
myClass = new MyClass();
myClass.Id = 0;
Hope I made it clear..
Have a look at this list on Wikipedia about which browsers support SVG. It also provides links to more details in the footnotes. Firefox for example supports basic SVG, but at the moment lacks most animation features.
A tutorial about how to create SVG objects using Javascript can be found here:
var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
you can simply use varialbles and one file to check for running your program. when open the file contain a value and when program closes changes this value to another one.
I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
When using the .html()
method, a htmlString
must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text()
as suggested by farzad.
Example:
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>
<?php
// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
}
When tested on this file:
foozah
barzah
abczah
It outputs:
foozah
Update:
To show text if the text is not found, use something like this:
<?php
$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
echo $line;
}
}
// If the text was not found, show a message
if(!$found)
{
echo 'No match found';
}
Here I'm using the $found
variable to find out if a match was found.
My issue with this was caused by having a duplicate nib in the class folder that did not have the view set. xcode seemed to be choosing one nib for a build and then the other the next time I built the project. Just deleted the other one. Looks good. Doh!
Of course it does:
@Html.TextBoxFor(x => x.Email, new { @placeholder = "Email" })
It shouldn't matter if the word has an even or odd amount fo letters:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
Some more:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25
Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25
The Visual Studio Development Server option applies only when you are running (testing) the Web project in Visual Studio. Production Web applications always run under IIS.
To specify the Web server for a Web site project
- In Solution Explorer, right-click the name of the Web site project for which you want to specify a Web server, and then click Property Pages.
- In the Property Pages dialog box, click the Start Options tab.
- Under Server, click Use custom server.
- In the Base URL box, type the URL that Visual Studio should start when running the current project.
Note: If you specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.
To specify the Web server for a Web application project
- In Solution Explorer, right-click the name of the Web application project for which you want to specify a Web server, and then click Properties.
- In the Properties window, click the Web tab.
- Under Servers, click Use Visual Studio Development Server or Use Local IIS Web server or Use Custom Web server.
- If you clicked Local IIS Web server or Use Custom Web Server, in the Base URL box, type the URL that Visual Studio should start when running the current project.
Note: If you clicked Use Custom Web Server and specify the URL of a remote server (for example, an IIS Web application on another computer), be sure that the remote server is running at least the .NET Framework version 2.0.
(Source: https://msdn.microsoft.com/en-us/library/ms178108.aspx)
The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for
my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]
Ready-to-use solution:
public class GoogleServicesUtils {
public static void openAppInGooglePlay(Context context) {
final String appPackageName = context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
}
Based on Eric's answer.
using extern <variable type> <variable name>
in a header or another C file.
Try this simple, specific function:
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
It does not depend on the current distance from the top of the body being specified (in case your 300px changes).
EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.
For anyone looking to do this in vb (as I was and couldn't find anything)
From c In db.Company
Select c.Name Group By Name Into Group
Where Group.Count > 1
You should introduce a cast inside the click
event handler
MouseEventArgs me = (MouseEventArgs) e;
if($this->db->insert('Your_tablename', $your_data)) {
return $this->db->insert_id();
}
return false
One solution to this would be a list comprehension, with pattern matching inside your tuple:
>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]
Another way would be using map
and filter
:
>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]
Use \t
and enclose the string with double-quotes:
$chunk = "abc\tdef\tghi";
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
In curl request add time out 0 so its infinite time set like CURLOPT_TIMEOUT set 0
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
My JSON
file:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
I succeeded in integrating a JSON
file to HTML
table after working a day on it!!!
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
If you just want the button to have different styling while the mouse is pressed you can use the :active
pseudo class.
.button:active {
}
If on the other hand you want the style to stay after clicking you will have to use javascript.
use $BASHPID
or $$
See the [manual][1] for more information, including differences between the two.
TL;DRTFM
$$
Expands to the process ID of the shell.
()
subshell, it expands to the process ID of the invoking shell, not the subshell.$BASHPID
Expands to the process ID of the current Bash process (new to bash 4).
()
subshell, it expands to the process ID of the subshell
[1]: http://www.gnu.org/software/bash/manual/bashref.html#Bash-VariablesOne easy way is to add a pass of tr
to squeeze any repeated field separators out:
$ ps | egrep 11383 | tr -s ' ' | cut -d ' ' -f 4