Check what git remote -v
returns: the account used to push to an http url is usually embedded into the remote url itself.
https://[email protected]/...
If that is the case, put an url which will force Git to ask for the account to use when pushing:
git remote set-url origin https://github.com/<user>/<repo>
Or one to use the Fre1234 account:
git remote set-url origin https://[email protected]/<user>/<repo>
Also check if you installed your Git For Windows with or without a credential helper as in this question.
The OP Fre1234 adds in the comments:
I finally found the solution.
Go to:Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials
Under
Generic Credentials
there are some credentials related to Github,
Click on them and click "Remove
".
That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper
output (it should be manager
)
Phone regex only for ?Iran phone number
func isValidPhone(phone: String) -> Bool {
let PHONE_REGEX = "^09[0-9'@s]{9,9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: phone)
return result
}
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
// change "name" and "value" according to your array data.
// Change "yourDataArrayName" name accroding to your array(NSArray).
let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")
if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {
//enter code here.
print(sortedDta)
}
For me the reason why the error appeared was that the WebForm where the error was reported has been moved from another folder, but the name of its codefile class remained unchanged and didn't correspond to the actual path.
Initial state:
Original file path: /Folder1/Subfolder1/MyWebForm.aspx.cs
Original codefile class name: Folder1_Subfolder1_MyWebForm
After the file was moved:
File path: /Folder1/MyWebForm.aspx.cs
Codefile class name (unchanged, with the error shown): Folder1_Subfolder1_MyWebForm
The solution:
Rename your codefile class Folder1_Subfolder1_MyWebForm
to one corresponding with the new path: Folder1_MyWebForm
All at once - problem solved, no errors reporting..
I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.
There are a few things that can cause this problem, but before you get started with JDBC, you need to be sure that you can connect to the database using SQL*Plus. If you're not familiar with SQL*Plus, it's a command-line tool for connecting to Oracle databases that has been a standard part of Oracle for a long time and it is included with Oracle XE.
When connecting to an Oracle database using JDBC, you don't connect to the database directly. Instead, you connect to a TNS listener, which then connects you to the database. The error ORA-12505
means that the listener was up and you could connect to it, but it couldn't connect you to the database because it doesn't know that that database is up. There are two reasons for this:
ORA-12505 means that the listener knows about that database, but the listener hasn't received a notification from the database that the database is up. (If you were trying to connect to the wrong database, using the wrong SID, you would get an ORA-12154 error "TNS: could not resolve the connect identifier specified".)
What Oracle services are running in the Services snap-in? (Open this from Control Panel > Administrative Tools > Services, or just Start > Run > services.msc
.) You need the services OracleServiceXE and OracleXETNSListener to be running.
If the services have both been started, can you connect to the database in SQL*Plus using any of the following at a command prompt? (I'm assuming you're running these on the machine you've installed Oracle XE on.)
sqlplus system/system-password@XE
sqlplus system/system-password
sqlplus / as sysdba
(Replace system-password
with the password you set for the SYS and SYSTEM users during the Oracle XE installation.)
The first of these three connect via the TNS listener, but the second two connect directly to the database without going via the listener, and only work if you're on the same machine as the database. If the first one fails but the other two succeed, then JDBC connections will also fail. If so, connect to the database using either of the other two and run ALTER SYSTEM REGISTER
. Then exit from SQL*Plus and try the first form again.
If the third one fails but the second one works, add your user account to the ora_dba group. Do this in Control Panel > Computer Management > Local Users and Groups.
Once you can get connections of the form
sqlplus system/system-password@XE
to work, you ought to be able to connect to Oracle XE via JDBC. (Incidentally, you haven't shown us the JDBC code you're using to connect to the database, but I would suspect that it is quite probably correct; there would be various other errors if parts of the connection string were wrong.)
I had the similar issue. its resolved for me with a simple command.
lsnrctl start
The Network Adapter exception is caused because:
lsnrctl
utility.Try to start the listener using the command prompt:
cmd
in the search field, and when cmd
shows up in the list of options, right click it and select ‘Run as Administrator’.lsnrctl start
without the quotes and press Enter.Exit
and press Enter.Hope it helps.
The split
method will create an array. So you need to access the third element in your case..
(arrays are 0-indexed) You need to access result[2]
to get the url
var result = $(row).text().split('|');
alert( result[2] );
You do not give us enough information to know what row
is, exactly.. So depending on how you acquire the variable row
you might need to do one of the following.
row
is a string then row.split('|');
$(row).text().split('|');
input
element then $(row).val().split('|');
@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
public class Shop {
//...
}
for jackson 2.0 or later use @JsonInclude(Include.NON_NULL)
This will remove both empty and null Objects.
I solved by following these steps:
This fixes the "Deployment Assembly" settings of the project.
I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg
Try this instead:
<img src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />
UPDATE:
I don't know what your $PROJECTHOME
is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.
Then in your HTML you can simply reference the image within the images folder relative to the site, like so:
<img src="images/66.jpg" width="400" height="400" />
Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):
<img src="/images/66.jpg" width="400" height="400" />
The best and easiest way to clear a JLIST is:
myJlist.setListData(new String[0]);
import urllib
import urllib.request
from bs4 import BeautifulSoup
with urllib.request.urlopen("http://www.newegg.com/") as url:
s = url.read()
print(s)
soup = BeautifulSoup(s, "html.parser")
all_tag_a = soup.find_all("a", limit=10)
for links in all_tag_a:
#print(links.get('href'))
print(links)
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:
gcc -static -L/usr/lib -I/usr/lib main.c -ltommath
With Swift 3, when you want to filter an array of dictionaries with a predicate based on dictionary keys and values, you may choose one of the following patterns.
NSPredicate
init(format:arguments:)
initializerIf you come from Objective-C, init(format:arguments:)
offers a key-value coding style to evaluate your predicate.
Usage:
import Foundation
let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]
let predicate = NSPredicate(format: "key1 == %@", "value1")
//let predicate = NSPredicate(format: "self['key1'] == %@", "value1") // also works
let filteredArray = array.filter(predicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]
NSPredicate
init(block:)
initializerAs an alternative if you prefer strongly typed APIs over stringly typed APIs, you can use init(block:)
initializer.
Usage:
import Foundation
let array = [["key1": "value1", "key2": "value2"], ["key1": "value3"], ["key3": "value4"]]
let dictPredicate = NSPredicate(block: { (obj, _) in
guard let dict = obj as? [String: String], let value = dict["key1"] else { return false }
return value == "value1"
})
let filteredArray = array.filter(dictPredicate.evaluate)
print(filteredArray) // prints: [["key2": "value2", "key1": "value1"]]
You need to use a date formatting function for example to_char http://www.postgresql.org/docs/current/static/functions-formatting.html
I know this is a very old article, but I came across this article when trying to solve my trust anchor issues. I have posted how I fixed it. If you have pre-installed your Root CA you need to add a configuration to the manifest.
One way is to use the Extended State. This asks the underlying OS to maximize the JFrame.
setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
Other approach would be to manually maximize the screen for you requirement.
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);
But this has pitfalls in Ubuntu OS. The work around I found was this.
if (SystemHelper.isUnix()) {
getContentPane().setPreferredSize(
Toolkit.getDefaultToolkit().getScreenSize());
pack();
setResizable(false);
show();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, getContentPane());
Point l = getLocation();
l.x -= p.x;
l.y -= p.y;
setLocation(p);
}
});
}
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);
In Fedora the above problem is not present. But there are complications involved with Gnome or KDE. So better be careful. Hope this helps.
Try this
echo date('Y-m-d H:i:s',date(strtotime("+1 day", strtotime("2009-09-30 20:24:00"))));
I had the same problem while installing numpy
with pip install numpy
.
Then I tried
sudo -H pip3 install --upgrade pip
sudo -H pip3 install numpy
It worked well for me.
Explanation :
The -H
(HOME) option with sudo
sets the HOME environment variable to the home directory of the target user (root by default). By default, sudo does not modify HOME.
This command:
iconv -f utf-8 -t utf-8 -c file.txt
will clean up your UTF-8 file, skipping all the invalid characters.
-f is the source format
-t the target format
-c skips any invalid sequence
I had this error when going from version 10.0.0.0, i.e. "Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
to version 11.0.0.0, i.e.
"Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
It took a while until I understood that not only the version was changed but also the public token key, as you can see above.
For those who are able to access cpanel, there is a simpler way getting around it.
log in cpanel => "Remote MySQL" under DATABASES section:
Add the IPs / hostname which you are accessing from
done!!!
Just to add an "official" answer to this response, I'm copy/pasting the solution to set and retrieve cookies from MDN (here's the JSfiddle
document.cookie = "test1=Hello";
document.cookie = "test2=World";
var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
function alertCookieValue() {
alert(cookieValue);
}
In you particular case, you would use the following function
function getCookieValue() {
return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}
Note that i only replaced "test2" from the example, with "obligations".
A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());
Update Swift 3
navigationController?.navigationItem.rightBarButtonItem?.tintColor = UIColor.yellow
navigationController?.navigationBar.tintColor = UIColor.red
navigationController?.navigationBar.barTintColor = UIColor.gray
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.blue]
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
df.index.rename('new name', inplace=True)
Is the only one that does the job for me (pandas 0.22.0).
Without the inplace=True, the name of the index is not set in my case.
orphan removal has the same effect as ON DELETE CASCADE in the following scenario:- Lets say we have a simple many to one relationship between student entity and a guide entity, where many students can be mapped to the same guide and in database we have a foreign key relation between Student and Guide table such that student table has id_guide as FK.
@Entity
@Table(name = "student", catalog = "helloworld")
public class Student implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id")
private Integer id;
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
@JoinColumn(name = "id_guide")
private Guide guide;
// The parent entity
@Entity
@Table(name = "guide", catalog = "helloworld")
public class Guide implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 9017118664546491038L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "name", length = 45)
private String name;
@Column(name = "salary", length = 45)
private String salary;
@OneToMany(mappedBy = "guide", orphanRemoval=true)
private Set<Student> students = new HashSet<Student>(0);
In this scenario, the relationship is such that student entity is the owner of the relationship and as such we need to save the student entity in order to persist the whole object graph e.g.
Guide guide = new Guide("John", "$1500");
Student s1 = new Student(guide, "Roy","ECE");
Student s2 = new Student(guide, "Nick", "ECE");
em.persist(s1);
em.persist(s2);
Here we are mapping the same guide with two different student objects and since the CASCADE.PERSIST is used , the object graph will be saved as below in the database table(MySql in my case)
STUDENT table:-
1 Roy ECE 1
2 Nick ECE 1
1 John $1500
and Now if I want to remove one of the students, using
Student student1 = em.find(Student.class,1);
em.remove(student1);
and when a student record is removed the corresponding guide record should also be removed, that's where CASCADE.REMOVE attribute in the Student entity comes into picture and what it does is ;it removes the student with identifier 1 as well the corresponding guide object(identifier 1). But in this example, there is one more student object which is mapped to the same guide record and unless we use the orphanRemoval=true attribute in the Guide Entity , the remove code above will not work.
This is based off of "default locale"'s answer but it will remove invalid column names prior to setting ordinal. This is because if you accidentally send an invalid column name then it would fail and if you put a check to prevent it from failing then the index would be wrong since it would skip indices wherever an invalid column name was passed in.
public static class DataTableExtensions
{
/// <summary>
/// SetOrdinal of DataTable columns based on the index of the columnNames array. Removes invalid column names first.
/// </summary>
/// <param name="table"></param>
/// <param name="columnNames"></param>
/// <remarks> http://stackoverflow.com/questions/3757997/how-to-change-datatable-colums-order</remarks>
public static void SetColumnsOrder(this DataTable dtbl, params String[] columnNames)
{
List<string> listColNames = columnNames.ToList();
//Remove invalid column names.
foreach (string colName in columnNames)
{
if (!dtbl.Columns.Contains(colName))
{
listColNames.Remove(colName);
}
}
foreach (string colName in listColNames)
{
dtbl.Columns[colName].SetOrdinal(listColNames.IndexOf(colName));
}
}
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
var keys = ["foo", "bar", "baz"];
Then use that to get the proper value:
object[keys[0]]
you must do 4 following step :
create event
var event = new Event("change",{
detail: {
oldValue:yourValueVariable,
newValue:!yourValueVariable
},
bubbles: true,
cancelable: true
});
event.simulated = true;
let tracker = this.yourComponentDomRef._valueTracker;
if (tracker) {
tracker.setValue(!yourValueVariable);
}
bind value to component dom
this.yourComponentDomRef.value = !yourValueVariable;
bind element onchange to react onChange function
this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
dispatch event
this.yourComponentDomRef.dispatchEvent(event);
in above code yourComponentDomRef
refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>
The easiest way is to use eval
as in:
>>> eval("2 + 2")
4
Pay attention to the fact I included spaces in the string. eval
will execute a string as if it was a Python code, so if you want the input to be in a syntax other than Python, you should parse the string yourself and calculate, for example eval("2x7")
would not give you 14 because Python uses *
for multiplication operator rather than x
.
You can get the random number through urandom
head -200 /dev/urandom | cksum
Output:
3310670062 52870
To retrieve the one part of the above number.
head -200 /dev/urandom | cksum | cut -f1 -d " "
Then the output is
3310670062
To meet your requirement,
head -200 /dev/urandom |cksum | cut -f1 -d " " | awk '{print $1%63000+2001}'
There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.
When you do something like git add file
you add it to the index. And when you commit it, you add it to the tree as well.
It will probably help you to know the three more common flags in git reset
:
git reset [--
<mode>
] [<commit>
]This form resets the current branch head to
<commit>
and possibly updates the index (resetting it to the tree of<commit>
) and the working tree depending on<mode>
, which must be one of the following:
--softDoes not touch the index file nor the working tree at all (but resets the head to
<commit>
, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.--mixed
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since
<commit>
are discarded.
Now, when you do something like git reset HEAD
, what you are actually doing is git reset HEAD --mixed
and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add
). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add
was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD
is the exact opposite of git add
.
git rm
, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached
, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add
was used to add a new (previously untracked) file, then git rm --cached
is the exact opposite of git add
(and is pretty much identical to git reset HEAD
).
Git 2.25 introduced a new command for these cases, git restore
, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.
You could also give them all the same name so they are an array, but give them different values:
<div id="checkboxes">
<input type="checkbox" name="c_n[]" value="c_n_0" checked="checked" />Option 1
<input type="checkbox" name="c_n[]" value="c_n_1" />Option 2
<input type="checkbox" name="c_n[]" value="c_n_2" />Option 3
<input type="checkbox" name="c_n[]" value="c_n_3" checked="checked" />Option 4
</div>
You can then get only the value of only the ticked ones using map:
$('#checkboxes input:checked[name="c_n[]"]')
.map(function () { return $(this).val(); }).get()
This works:
for i,r in data[::-1].iterrows():
print(r['Odd'], r['Even'])
See my jsFiddle here: http://jsfiddle.net/fuDBL/
Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.
$('input[name="email"]').change(function(){
$('#regLink').attr('href')+$('input[name="email"]').val();
});
one liner simple way
var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicates
_x000D_
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
When your program is waiting for I/O (ie. a disk read/write or network read/write etc), the CPU is free to do other tasks even if your program is stopped. The speed of your program will mostly depend on how fast that IO can happen, and if you want to speed it up you will need to speed up the I/O.
If your program is running lots of program instructions and not waiting for I/O, then it is said to be CPU bound. Speeding up the CPU will make the program run faster.
In either case, the key to speeding up the program might not be to speed up the hardware, but to optimize the program to reduce the amount of IO or CPU it needs, or to have it do I/O while it also does CPU intensive stuff.
You must use some of the C # conversion systems:
string to boolean: True to true
string str = "True";
bool mybool = System.Convert.ToBoolean(str);
boolean to string: true to True
bool mybool = true;
string str = System.Convert.ToString(mybool);
//or
string str = mybool.ToString();
bool.Parse
expects one parameter which in this case is str, even .
Convert.ToBoolean
expects one parameter.
bool.TryParse
expects two parameters, one entry (str) and one out (result).
If TryParse
is true, then the conversion was correct, otherwise an error occurred
string str = "True";
bool MyBool = bool.Parse(str);
//Or
string str = "True";
if(bool.TryParse(str, out bool result))
{
//Correct conversion
}
else
{
//Incorrect, an error has occurred
}
Increasing number of max-connections will not solve the problem.
We were experiencing the same situation on our servers. This is what happens
User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.
You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour
SET interactive_timeout=3600
Very easy to use select option submit
<select name="sortby" onchange="this.form.submit()">
<option value="">Featured</option>
<option value="asc" >Price: Low to High</option>
<option value="desc">Price: High to Low</option>
</select>
This code use and enjoy now:
Read More: Go Link
The short answer is: if you're a beginner in C++, you should never be using new
or delete
yourself.
Instead, you should use smart pointers such as std::unique_ptr
and std::make_unique
(or less often, std::shared_ptr
and std::make_shared
). That way, you don't have to worry nearly as much about memory leaks. And even if you're more advanced, best practice would usually be to encapsulate the custom way you're using new
and delete
into a small class (such as a custom smart pointer) that is dedicated just to object lifecycle issues.
Of course, behind the scenes, these smart pointers are still performing dynamic allocation and deallocation, so code using them would still have the associated runtime overhead. Other answers here have covered these issues, and how to make design decisions on when to use smart pointers versus just creating objects on the stack or incorporating them as direct members of an object, well enough that I won't repeat them. But my executive summary would be: don't use smart pointers or dynamic allocation until something forces you to.
I believe the admin button will open the default configuration always. It simply contains a link to localhost/xampp
and it doesn't read the server configuration.
If you change the default settings, you know what you changed and you can enter the URL directly in the browser.
subscribe() -Invokes an execution of an Observable and registers Observer handlers for notifications it will emit. -Observable- representation of any set of values over any amount of time.
import re
my_string = """Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the
same as double quotes."""
# if we need to count the word python that ends with or without ',' or '.' at end
count = 0
for i in text:
if i.endswith("."):
text[count] = re.sub("^([a-z]+)(.)?$", r"\1", i)
count += 1
print("The count of Python : ", text.count("python"))
'use strict'
var fs = require("fs");
/***
* implementation of readFileSync
*/
var data = fs.readFileSync('input.txt');
console.log(data.toString());
console.log("Program Ended");
/***
* implementation of readFile
*/
fs.readFile('input.txt', function (err, data) {
if (err) return console.error(err);
console.log(data.toString());
});
console.log("Program Ended");
For better understanding run the above code and compare the results..
Your error is in UpdaterServiceManager in onCreate and showNotification method.
You are trying to show notification
from Service using Activity Context
. Whereas Every Service has its own Context,
just use the that. You don't need to pass a Service an Activity's Context.
I don't see why you need a specific Activity's Context to show Notification.
Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.
You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference
As others have said, there is now an option for Ctrl+Shf+V
for paste in Windows 10 Insider build #17643.
Unfortunately this isn't in my muscle memory and as a user of TTY terminals I'd like to use Shf+Ins
as I do on all the Linux boxes I connect to.
This is possible on Windows 10 if you install ConEmu which wraps the terminal in a new GUI and allows Shf+Ins
for paste. It also allows you to tweak the behaviour in the Properties.
Shf+Ins
works out of the box. I can't remember if you need to configure bash as one of the shells it uses but if you do, here is the task properties to add it:
Also allows tabbed Consoles (including different types, cmd.exe
, powershell
etc). I've been using this since early Windows 7 and in those days it made the command line on Windows usable!
For Swift 3 & Swift 4 :
Since UIAlertView is deprecated, there is the good way for display Alert on Swift 3
let alertController = UIAlertController(title: NSLocalizedString("No network connection",comment:""), message: NSLocalizedString("connected to the internet to use this app.",comment:""), preferredStyle: .alert)
let defaultAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: { (pAlert) in
//Do whatever you want here
})
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
Deprecated :
This is the swift version inspired by the checked response :
Display AlertView :
let alert = UIAlertView(title: "No network connection",
message: "You must be connected to the internet to use this app.", delegate: nil, cancelButtonTitle: "Ok")
alert.delegate = self
alert.show()
Add the delegate to your view controller :
class AgendaViewController: UIViewController, UIAlertViewDelegate
When user click on button, this code will be executed :
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
}
The easy way: Pick an alternative Color Scheme:
Preferences > Color Scheme > ...pick one
The more complicated way: Edit the current color scheme file:
Preferences > Browse Packages > Color Scheme - Default > ... edit the Color Scheme file you are using:
Looking at the structure of the XML, drill down into dict > settings > settings > dict >
Look for the key (or add it if it's missing): lineHighlight
. Add a string with an #RRGGBB
or #RRGGBBAA
format.
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
The code below has worked for me when I didn't know the specific SPID that was used to change into singleuser
mode.
use master
GO
select
d.name,
d.dbid,
spid,
login_time,
nt_domain,
nt_username,
loginame
from sysprocesses p
inner join sysdatabases d
on p.dbid = d.dbid
where d.name = 'dbname'
GO
kill 52 -- kill the number in spid field
GO
exec sp_dboption 'dbname', 'single user', 'FALSE'
GO
I use objects JSON style for dumb structs (no member functions).
Based on @Ryan Shillington answer above you may find this enhancment helpfull too. Think this is more secured then what was requeted on the original request in the question above.
//Password generated with at least 1 number, 1 upper case character, 1 lower case character and 1 Special character
function generatePassword()
{
var passwordLength = randomIntFromInterval(10,20);
var numberChars = "0123456789";
var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowerChars = "abcdefghijklmnopqrstuvwxyz";
var specialChars = "~!#$%&*-+|";
var allChars = numberChars + upperChars + lowerChars + specialChars;
var randPasswordArray = Array(passwordLength);
randPasswordArray[0] = numberChars;
randPasswordArray[1] = upperChars;
randPasswordArray[2] = lowerChars;
randPasswordArray[3] = specialChars;
randPasswordArray = randPasswordArray.fill(allChars, 4);
if(window.crypto && window.crypto.getRandomValues)
{
return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');
}
else if(window.msCrypto && window.msCrypto.getRandomValues)
{
return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.msCrypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');
}else{
return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
}
}
function shuffleArray(array)
{
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
//generate random number in the range (min and max included)
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
_x000D_
<input type='text' id='p9'/>
<input type='button' value ='pass generator' onclick='document.getElementById("p9").value = generatePassword()'>
_x000D_
One big difference that hasn't been mentioned is that process.stdout only takes strings as arguments (can also be piped streams), while console.log takes any Javascript data type.
e.g:
// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))
// any other data type passed as param will throw a TypeError
process.stdout.write('1')
// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks Includes ExecCGI
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Require all granted
Write above code inside following tags < Directory "c:\projects" > < / Directory > c:(you can add any directory d: e:) is drive where you have created your project folder.
Alias /projects "c:\projects"
Now you can access the pr0jects directory on your browser :
localhost/projects/
I faced this problem (404) too and the root cause was my file was named INDEX.md
. I was developing on Windows and my local Jekyll site worked (since Windows treats file names case insensitive by default). When pushed to Github, it didn't work. Once I renamed the INDEX.md
to index.md
, things worked well.
You need to specify the path where your chromedriver is located.
Place chromedriver on your system path, or where your code is.
If not using a system path, link your chromedriver.exe
(For non-Windows users, it's just called chromedriver
):
browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
(Set executable_path
to the location where your chromedriver is located.)
If you've placed chromedriver on your System Path, you can shortcut by just doing the following:
browser = webdriver.Chrome()
If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:
chmod +x chromedriver
That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium
Very simple don't make it complicated with lots of logic use simple attribute draggable and make it false
<img draggable="false" src="img/magician.jpg" alt="" />
Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available
echo $(date +%S) | grep -o .$ | sed s/0/10/
If by autostart you mean auto start on phone bootup then you should register a BroadcastReceiver for the BOOT_COMPLETED
Intent. Android systems broadcasts that intent once boot is completed.
Once you receive that intent you can launch a Service that can do whatever you want to do.
Keep note though that having a Service running all the time on the phone is generally a bad idea as it eats up system resources even when it is idle. You should launch your Service / application only when needed and then stop it when not required.
Just use mysql_query (or mysqli_query, even better, or use PDO, best of all) with:
SELECT DATABASE() FROM DUAL;
There is much discussion over whether or not FROM DUAL
should be included in this or not. On a technical level, it is a holdover from Oracle and can safely be removed. If you are inclined, you can use the following instead:
SELECT DATABASE();
That said, it is perhaps important to note, that while FROM DUAL
does not actually do anything, it is valid MySQL syntax. From a strict perspective, including braces in a single line conditional in JavaScript also does not do anything, but it is still a valid practice.
You can use git log
with the pathnames of the respective folders:
git log A B
The log will only show commits made in A
and B
. I usually throw in --stat
to make things a little prettier, which helps for quick commit reviews.
Add a reference to 'Microsoft.VisualStudio.QualityTools.UnitTestFramework" NuGet packet and it should successfully build it.
There is a JDK socket tutorial here, which covers both the server and client end. That looks exactly like what you want.
(from that tutorial) This sets up to read from an echo server:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
taking a stream of bytes and converts to strings via the reader and using a default encoding (not advisable, normally).
Error handling and closing sockets/streams omitted from the above, but check the tutorial.
The spec says seconds:
http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2
expires_in
OPTIONAL. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
I agree with OP that it's careless for Google to not document this.
tar -zcvf compressFileName.tar.gz folderToCompress
everything in folderToCompress will go to compressFileName
Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName
Actually, you don't have to use document.getElementById("mydiv")
.
You can simply use the id of the div, like:
var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.
Mamp user enable option Allow network access to MYSQL
If you are using Python selenium
bindings, nowadays, there is an extension to selenium
- selenium-requests
:
Extends Selenium WebDriver classes to include the request function from the Requests library, while doing all the needed cookie and request headers handling.
Example:
from seleniumrequests import Firefox
webdriver = Firefox()
response = webdriver.request('POST', 'url here', data={"param1": "value1"})
print(response)
There was a really nice post on the Spring Blog from Keith Donald detailing howto Obtain Spring 3 Aritfacts with Maven, with comments detailing when you'd need each of the dependencies...
<!-- Shared version number properties -->
<properties>
<org.springframework.version>3.0.0.RELEASE</org.springframework.version>
</properties>
<!-- Core utilities used by other modules.
Define this if you use Spring Utility APIs
(org.springframework.core.*/org.springframework.util.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Expression Language (depends on spring-core)
Define this if you use Spring Expression APIs
(org.springframework.expression.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Bean Factory and JavaBeans utilities (depends on spring-core)
Define this if you use Spring Bean APIs
(org.springframework.beans.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Aspect Oriented Programming (AOP) Framework
(depends on spring-core, spring-beans)
Define this if you use Spring AOP APIs
(org.springframework.aop.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context
(depends on spring-core, spring-expression, spring-aop, spring-beans)
This is the central artifact for Spring's Dependency Injection Container
and is generally always defined-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Various Application Context utilities, including EhCache, JavaMail, Quartz,
and Freemarker integration
Define this if you need any of these integrations-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Transaction Management Abstraction
(depends on spring-core, spring-beans, spring-aop, spring-context)
Define this if you use Spring Transactions or DAO Exception Hierarchy
(org.springframework.transaction.*/org.springframework.dao.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you use Spring's JdbcTemplate API
(org.springframework.jdbc.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA and iBatis.
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you need ORM (org.springframework.orm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX,
Castor, XStream, and XML Beans.
(depends on spring-core, spring-beans, spring-context)
Define this if you need OXM (org.springframework.oxm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and
Portlet Environments
(depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another
web framework with Spring (org.springframework.web.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Servlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Servlet Container such as
Apache Tomcat (org.springframework.web.servlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Portlet Container
(org.springframework.web.portlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and TestNG
This artifact is generally always defined with a 'test' scope for the
integration testing framework and unit testing stubs-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
You can use ng-include
directive.
Try something like this:
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.getContentUrl = function() {
return 'content/excerpts/hymn-' + attrs.ver + '.html';
}
},
template: '<div ng-include="getContentUrl()"></div>'
}
});
UPD. for watching ver
attribute
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
attrs.$observe("ver",function(v){
scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
});
Brute force it:
first_name_relation = User.where(:first_name => 'Tobias') # ActiveRecord::Relation
last_name_relation = User.where(:last_name => 'Fünke') # ActiveRecord::Relation
all_name_relations = User.none
first_name_relation.each do |ar|
all_name_relations.new(ar)
end
last_name_relation.each do |ar|
all_name_relations.new(ar)
end
The simplest way is like this:
import os
retvalue = os.popen("ps -p 2993 -o time --no-headers").readlines()
print retvalue
This will be returned as a list
The solution I post will consider a month with 30 days
select CONCAT (CONCAT (num_months,' MONTHS '), CONCAT ((days-(num_months)*30),' DAYS '))
from (
SELECT floor(Months_between(To_date('20120325', 'YYYYMMDD'),
To_date('20120101', 'YYYYMMDD')))
num_months,
( To_date('20120325', 'YYYYMMDD') - To_date('20120101', 'YYYYMMDD') )
days
FROM dual);
In ascending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
or in descending order you can use:
sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
@JsonFormat(shape= JsonFormat.Shape.OBJECT)
public enum SomeEnum
available since https://github.com/FasterXML/jackson-databind/issues/24
just tested it works with version 2.1.2
answer to TheZuck:
I tried your example, got Json:
{"events":[{"type":"ADMIN"}]}
My code:
@RequestMapping(value = "/getEvent") @ResponseBody
public EventContainer getEvent() {
EventContainer cont = new EventContainer();
cont.setEvents(Event.values());
return cont;
}
class EventContainer implements Serializable {
private Event[] events;
public Event[] getEvents() {
return events;
}
public void setEvents(Event[] events) {
this.events = events;
}
}
and dependencies are:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
<exclusions>
<exclusion>
<artifactId>jackson-annotations</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
<exclusion>
<artifactId>jackson-core</artifactId>
<groupId>com.fasterxml.jackson.core</groupId>
</exclusion>
</exclusions>
</dependency>
<jackson.version>2.1.2</jackson.version>
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
public static Node insertNodeAtTail(Node head,Object data) {
Node node = new Node(data);
node.next = null;
if (head == null){
return node;
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
return head;
}
}
I've created a FormValidationUtils class to validate email:
public static class FormValidationUtils
{
const string ValidEmailAddressPattern = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$";
public static bool IsEmailValid(string email)
{
var regex = new Regex(ValidEmailAddressPattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
}
I know the answer is quite late, but the best way to get rid of milliseconds is
var currentDateTime = DateTime.Now.ToString("s");
Try printing the value of the variable, it will show the date time, without milliseconds.
The field must be declared public
for proper visibility from the ASPX markup. In any case, you could declare a property:
private string clients;
public string Clients { get { return clients; } }
UPDATE: It can also be declared as protected
, as stated in the comments below.
Then, to call it on the ASPX side:
<%=Clients%>
Note that this won't work if you place it on a server tag attribute. For example:
<asp:Label runat="server" Text="<%=Clients%>" />
This isn't valid. This is:
<div><%=Clients%></div>
The List
interface already has this solved.
int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;
More can be found in the documentation about List.
Process text to and from Unicode at the I/O boundaries of your program using open
with the encoding
parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False)
is the encoding used), so I recommend always explicitly using the encoding
parameter for portability and clarity (Python 3 syntax below):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
If still using Python 2 or for Python 2/3 compatibility, the io
module implements open
with the same semantics as Python 3's open
and exists in both versions:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
Try something like this it will help you
$("#from").click(function () {
$('#from').attr('readonly', true);
});
Thanks
Sometimes you must change the name (or check to get it automatically from compiler).
Example:
Filename = amp2-rot.png
It is not working as:
PictureBoxName.Image = resources.GetObject("amp2-rot.png")
It works, just as amp2_rot
for me:
PictureBox_L1.Image = My.Resources.Resource.amp2_rot
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date
. If you make it null
means that it is not referring any instance of java.util.Date
.
You have tried date2="";
what you mean to do by this statement you want to reference the instance of String
to a variable that is suppose to store java.util.Date
. This is not possible as Java is Strongly Typed Language.
Edit
After seeing the comment posted to the answer of LastFreeNickname
I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it
I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null
as shown below:
if(textBox.getText() == null || textBox.getText().equals(""){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}
Also I can assume since you are asking user to enter a date in a TextBox
, you are using a DateFormat
to parse the text that is entered in the TextBox
. If this is the case you could simply call the dateFormat.parse()
which throws a ParseException
if the format in which the date was written is incorrect or is empty string. Here in the catch
block you could put the above statements as show below:
try{
date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}
With modern browsers, console.log(functor)
works perfectly (behaves the same was a console.dir
).
C++ doesn't have introspection, so you can't determine this kind of thing at run-time.
create a new database with same name copy the .frm .ibd files into xampp/mysql/data/[databasename]/
you will need ibdata file as well which is found inside
xampp/mysql/data/ copy the previous ibdata1 file paste in the paste the file and replace it with the existing ibdata file
[caution: you may loose the contents of the database which are newly created in the new ibdata file]
Could not edit the accepted response so adding it as an answer here,
to restore the file in git, use the following (note the '^' sign just after the SHA)
git checkout <SHA>^ -- /path/to/file
Try this:
Declare @Daytype varchar(15),
@StartDate datetime,
@EndDate datetime
set @Daytype = datename(dw, getdate())
if @Daytype= 'Monday'
begin
set @StartDate = getdate()-7
set @EndDate = getdate()-1
end
else if @Daytype = 'Tuesday'
begin
set @StartDate = getdate()-8
set @EndDate = getdate()-2
end
Else if @Daytype = 'Wednesday'
begin
set @StartDate = getdate()-9
set @EndDate = getdate()-3
end
Else if @Daytype = 'Thursday'
begin
set @StartDate = getdate()-10
set @EndDate = getdate()-4
end
Else if @Daytype = 'Friday'
begin
set @StartDate = getdate()-11
set @EndDate = getdate()-5
end
Else if @Daytype = 'Saturday'
begin
set @StartDate = getdate()-12
set @EndDate = getdate()-6
end
Else if @Daytype = 'Sunday'
begin
set @StartDate = getdate()-13
set @EndDate = getdate()-7
end
select @StartDate,@EndDate
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:
import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))
This prints:
z is: ['grape', 'cherry', 'mango']
Which is stored on disk as the filename: outfile.dat.npy
The important methods here are the tolist()
and np.array(...)
conversion functions.
As others have noted, in general use the -v
flag for the gem install
command.
If you're developing a gem locally, after cutting a gem from your gemspec:
$ gem install gemname-version.gem
Assuming version 0.8, it would look like this:
$ gem install gemname-0.8.gem
Output on Windows 7 (64-bit)
SpecialFolder.CommonApplicationData: C:\ProgramData
SpecialFolder.CommonDesktopDirectory: C:\Users\Public\Desktop
SpecialFolder.CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
SpecialFolder.CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86: C:\Program Files (x86)\Common Files
SpecialFolder.CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86: C:\Program Files (x86)
SpecialFolder.System: C:\Windows\system32
SpecialFolder.SystemX86: C:\Windows\SysWOW64
Output on Windows XP
SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data
SpecialFolder.CommonDesktopDirectory: C:\Documents and Settings\All Users\Desktop
SpecialFolder.CommonPrograms: C:\Documents and Settings\All Users\Start Menu\Programs
SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonStartMenu: C:\Documents and Settings\All Users\Start Menu
SpecialFolder.CommonStartup: C:\Documents and Settings\All Users\Start Menu\Programs\Startup
SpecialFolder.ProgramFiles: C:\Program Files
SpecialFolder.ProgramFilesX86:
SpecialFolder.System: C:\WINDOWS\system32
SpecialFolder.SystemX86: C:\WINDOWS\system32
What about this? I presume it can be counted on to handle dates before 1970 and after 2038.
target_date_time_ms = 200000 # or whatever
base_datetime = datetime.datetime( 1970, 1, 1 )
delta = datetime.timedelta( 0, 0, 0, target_date_time_ms )
target_date = base_datetime + delta
as mentioned in the Python standard lib:
fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It’s common for this to be restricted to years in 1970 through 2038.
The fleqn
option in the document class will apply left aligning setting in all equations of the document. You can instead use \begin{flalign}
. This will align only the desired equations.
Use this,
var currentDirectory = System.IO.Directory.GetCurrentDirectory();
You can use this as well.
var currentDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
This is how I did it for utf8 encoded table and utf8_unicode_ci column, which doesn't seem to have been posted exactly:
SELECT *
FROM table
WHERE UPPER(column) != BINARY(column)
The other answers here do a good job of explaining the issue, so I won't repeat that here. But there is one solution that can resolve it that isn't listed yet: simply run make clean
, then rerun make
.
Having make remove any already compiled files will prevent make from having any files to compare the timestamps of, resolving the warning.
SOLUTION 1 Purge out (or remove if you want to keep databases) any mysql packages to repeat the installation anew:
sudo apt purge "mysql*"
-Autoremove packages
sudo apt autoremove
-Stop the apparmor service
sudo systemctl stop apparmor
-Make apparmor drop its profiles (I thought with stop it was enough, but for me it wasn't. With systemctl it doesn't work)
sudo service apparmor teardown
-Reinstall mysql-server
sudo apt install mysql-server
-Install apparmor-utils, to create a profile for mysql in apparmor that allows mysql to run
sudo apt install apparmor-utils
-Check the status of mysql-server (must be Active(running))
sudo systemctl status mysql
-Generate a profile for mysql in apparmor
sudo aa-genprof mysql
-In other terminal run mysql (enter root password)
mysql -u root -p
-do things in MySQL while apparmor is generating the profile in the other terminal
mysql> CREATE DATABASE fooDB
-Swith to the other terminal and press "s" (the prompt tells you it's for "scan")
-Say yes to the policies from apparmor you see fit (I guess all of them for mysql), say yes pressing "a" for Allow
-Press "f" to Finish the apparmor profile
-Restart the apparmor service
sudo systemctl start apparmor
-Check to see if you still can use mysql in the other terminal
mysql>exit
mysql -u root -p
If all is well you can use mysql from the command line.
I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..
CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());
Open multiple instances of Toad and execute.
Well, this is not that different from what have been said, but this works very well in all browsers.
The idea is to delete any text which overflows the defined length.
function countTextAreaChar(txtarea, l){
var len = $(txtarea).val().length;
if (len > l) $(txtarea).val($(txtarea).val().slice(0, l));
else $('#charNum').text(l - len);
}
The HTMl code would be:
<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>
Here is a good example to demonstrate how Javascript works with static/instance variables and methods.
function Animal(name) {
Animal.count = Animal.count+1||1;// static variables, use function name "Animal"
this.name = name; //instance variable, using "this"
}
Animal.showCount = function () {//static method
alert(Animal.count)
}
Animal.prototype.showName=function(){//instance method
alert(this.name);
}
var mouse = new Animal("Mickey");
var elephant = new Animal("Haddoop");
Animal.showCount(); // static method, count=2
mouse.showName();//instance method, alert "Mickey"
mouse.showCount();//Error!! mouse.showCount is not a function, which is different from Java
i have made a github repository to show what i think is a good (or best practices) startup project structure...
https://github.com/StefanHeimberg/stackoverflow-1134894
some keywords:
Maven Output:
Reactor Summary:
MyProject - BOM .................................... SUCCESS [ 0.494 s]
MyProject - Parent ................................. SUCCESS [ 0.330 s]
MyProject - Common ................................. SUCCESS [ 3.498 s]
MyProject - Persistence ............................ SUCCESS [ 1.045 s]
MyProject - Business ............................... SUCCESS [ 1.233 s]
MyProject - Web .................................... SUCCESS [ 1.330 s]
MyProject - Application ............................ SUCCESS [ 0.679 s]
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 8.817 s
Finished at: 2015-01-27T00:51:59+01:00
Final Memory: 24M/207M
------------------------------------------------------------------------
While checking null or Empty
value for a column, I noticed that there are some support concerns in various Databases.
Every Database doesn't support TRIM
method.
Below is the matrix just to understand the supported methods by different databases.
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:
TRIM(), RTRIM(), LTRIM()
RTRIM(), LTRIM()
TRIM(), RTRIM(), LTRIM()
How to Check Empty/Null/Whitespace :-
Below are two different ways according to different Databases-
The syntax for these trim functions are:
Use of Trim to check-
SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL
Use of LTRIM & RTRIM to check-
SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL
Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName
from UserDetails
table if it has an empty LastName
Hoping this will help others too :)
From the CREATE TRIGGER documentation:
deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use:
SELECT * FROM deleted
So that at least gives you a way of seeing the new data.
I can't see anything in the docs which specifies that you won't see the inserted data when querying the normal table though...
This is the jQuery solution that worked for me. offsetWidth
etc. didn't work.
function is_overflowing(element, extra_width) {
return element.position().left + element.width() + extra_width > element.parent().width();
}
If this doesn't work, ensure that elements' parent has the desired width (personally, I had to use parent().parent())
. position
is relative to the parent. I've also included extra_width
because my elements ("tags") contain images which take small time to load, but during the function call they have zero width, spoiling the calculation. To get around that, I use the following calling code:
var extra_width = 0;
$(".tag:visible").each(function() {
if (!$(this).find("img:visible").width()) {
// tag image might not be visible at this point,
// so we add its future width to the overflow calculation
// the goal is to hide tags that do not fit one line
extra_width += 28;
}
if (is_overflowing($(this), extra_width)) {
$(this).hide();
}
});
Hope this helps.
I agree with much that Manuel has said. In fact, his comments refer to this url...
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
... which states:
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
However, for me it would come down to tool/framework support.
If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.
Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.
You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.
Given a form like:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
The straight DOM way:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
Simple DOM way. This may not work in older browsers that don't like file inputs:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
The jQuery way:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947
("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);
You should use @RequestParam
on those resources with method = RequestMethod.GET
In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType
).
Typically, multipart/form-data is used to upload files.
declare @EventId int
CREATE TABLE #EventId (EventId int)
insert into #EventId exec rptInputEventId
set @EventId = (select * from #EventId)
drop table #EventId
You can simply delete the /var/mail/username
file to delete all emails for a specific user. Also, emails that are outgoing but have not yet been sent will be stored in /var/spool/mqueue
.
Reason for error:
The query from p in dc.BlogPosts where p.BlogPostID == ID select p
returns a sequence.
Single()
tries to retrieve an element from the sequence returned in step1.
As per the exception - The sequence returned in step1 contains no elements.
Single() tries to retrieve an element from the sequence returned in step1 which contains no elements.
Since Single()
is not able to fetch a single element from the sequence returned in step1, it throws an error.
Fix:
Make sure the query (from p in dc.BlogPosts where p.BlogPostID == ID select p)
returns a sequence with at least one element.
When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.
styles.xml:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
<item name="android:editTextColor">#295055</item>
<item name="android:textColorPrimary">#295055</item>
<item name="android:textColorSecondary">#295055</item>
<item name="android:textColorTertiary">#295055</item>
<item name="android:textColorPrimaryInverse">#295055</item>
<item name="android:textColorSecondaryInverse">#295055</item>
<item name="android:textColorTertiaryInverse">#295055</item>
<item name="android:windowBackground">@drawable/custom_background</item>
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
parent="@android:style/Theme.Light"
is Google’s native colors. Here is a reference of what the native styles are:
https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml
The default Android style is also called “Theme”. So you calling it Theme probably confused the program.
name="Theme.AppBaseTheme"
means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light"
.
This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">
@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.
#295055 is a dark blue color.
My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).
Then in Android Manifest, remember to include the code:
<application
android:theme="@style/Theme.AppBaseTheme">
There are many paths through your code whereby your variables are not initialized, which is why the compiler complains.
Specifically, you are not validating the user input for creditPlan
- if the user enters a value of anything else than "0","1","2" or "3"
, then none of the branches indicated will be executed (and creditPlan
will not be defaulted to zero as per your user prompt).
As others have mentioned, the compiler error can be avoided by either a default initialization of all derived variables before the branches are checked, OR ensuring that at least one of the branches is executed (viz, mutual exclusivity of the branches, with a fall through else
statement).
I would however like to point out other potential improvements:
CreditPlan
appears to have a finite domain and is better suited to an enumeration
or Dictionary
than a string
. Financial data and percentages should always be modelled as decimal
, not double
to avoid rounding issues, and 'status' appears to be a boolean.monthlyCharge = balance * annualRate * (1/12))
is common to more than one branch. For maintenance reasons, do not duplicate this code.e.g. here is an alternative representation of your model:
// Keep all Credit Plan parameters together in a model
public class CreditPlan
{
public Func<decimal, decimal, decimal> MonthlyCharge { get; set; }
public decimal AnnualRate { get; set; }
public Func<bool, Decimal> LateFee { get; set; }
}
// DRY up repeated calculations
static private decimal StandardMonthlyCharge(decimal balance, decimal annualRate)
{
return balance * annualRate / 12;
}
public static Dictionary<int, CreditPlan> CreditPlans = new Dictionary<int, CreditPlan>
{
{ 0, new CreditPlan
{
AnnualRate = .35M,
LateFee = _ => 0.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 1, new CreditPlan
{
AnnualRate = .30M,
LateFee = late => late ? 0 : 25.0M,
MonthlyCharge = StandardMonthlyCharge
}
},
{ 2, new CreditPlan
{
AnnualRate = .20M,
LateFee = late => late ? 0 : 35.0M,
MonthlyCharge = (balance, annualRate) => balance > 100
? balance * annualRate / 12
: 0
}
},
{ 3, new CreditPlan
{
AnnualRate = .15M,
LateFee = _ => 0.0M,
MonthlyCharge = (balance, annualRate) => balance > 500
? (balance - 500) * annualRate / 12
: 0
}
}
};
As mentioned in other answers ORDER BY 1
orders by the first column.
I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name
in the below.
SELECT Name, Name FROM Segment ORDER BY 1
On my Linux system (Red Hat Enterprise 6.9), the split
command does not have the command-line options for either -n
or --additional-suffix
.
Instead, I've used this:
split -d -l NUM_LINES really_big_file.txt split_files.txt.
where -d
is to add a numeric suffix to the end of the split_files.txt.
and -l
specifies the number of lines per file.
For example, suppose I have a really big file like this:
$ ls -laF
total 1391952
drwxr-xr-x 2 user.name group 40 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group 4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt
This file has 100,000 lines, and I want to split it into files with at most 30,000 lines. This command will run the split and append an integer at the end of the output file pattern split_files.txt.
.
$ split -d -l 30000 really_big_file.txt split_files.txt.
The resulting files are split correctly with at most 30,000 lines per file.
$ ls -laF
total 2783904
drwxr-xr-x 2 user.name group 156 Sep 14 15:43 ./
drwxr-xr-x 3 user.name group 4096 Sep 14 15:39 ../
-rw-r--r-- 1 user.name group 1425352817 Sep 14 14:01 really_big_file.txt
-rw-r--r-- 1 user.name group 428604626 Sep 14 15:43 split_files.txt.00
-rw-r--r-- 1 user.name group 427152423 Sep 14 15:43 split_files.txt.01
-rw-r--r-- 1 user.name group 427141443 Sep 14 15:43 split_files.txt.02
-rw-r--r-- 1 user.name group 142454325 Sep 14 15:43 split_files.txt.03
$ wc -l *.txt*
100000 really_big_file.txt
30000 split_files.txt.00
30000 split_files.txt.01
30000 split_files.txt.02
10000 split_files.txt.03
200000 total
This is what you need in 1 line of code.
Route::get('/groups/{groupId}', 'GroupsController@getShow');
Suggestion: Use CamelCase as opposed to underscores, try & follow PSR-* guidelines.
Hope it helps.
The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.
You need to do the redirect in JavaScript too
$('.entry a:first').click(function()
{
window.location.replace("http://www.google.com");
});
var arr_select_val=[];
$("select").each(function() {
var name=this.name;
arr_select_val[name]=$('select option:first-child').val();
});
// Process the array object
$('.orders_status_summary_div').print(arr_select_val);
Set the id
attribute of the input
to txtJob
. Your browser is acting quirky when you call getElementById
.
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
Your best bet over here to install XAMPP..Follow the link download it , it has an instruction file as well. You can setup your own MY SQL database and then connect to on your local machine.
This is a simple solution where we do not need to use JSON
public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
@Field("name") String name,
@Field("username") String username,
@Field("password") String password,
@Field("email") String email,
Callback<Response> callback);
}
method to send data
private void insertUser(){
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
editTextName.getText().toString(),
editTextUsername.getText().toString(),
editTextPassword.getText().toString(),
editTextEmail.getText().toString(),
//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
Now we can get the post request using php aur any other server side scripting.
Source Android Retrofit Tutorial
An alternative - which may work for you depending on what you're trying to do - is to have the HTML in place and then use the CSS to show or hide it depending on the class of a parent element.
OR
Use jQuery append()
When using MVC in .NET with Angular you can always use OrderByDecending() when doing your db query like this:
var reversedList = dbContext.GetAll().OrderByDecending(x => x.Id).ToList();
Then on the Angular side, it will already be reversed in some browsers (IE). When supporting Chrome and FF, you would then need to add orderBy:
<tr ng-repeat="item in items | orderBy:'-Id'">
In this example, you'd be sorting in descending order on the .Id property. If you're using paging, this gets more complicated because only the first page would be sorted. You'd need to handle this via a .js filter file for your controller, or in some other way.
If you are using MinGW toolchain for CDT, make.exe is found at C:\MinGW\msys\1.0\bin
(or search the make.exe in MinGW folder.)
Add this path in eclipse window->preferences->environment
If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.
UPDATE table_mame SET field_name= 0;
After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.
ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;
I think it will help you.
Sybase :
% : Matches any string of zero or more characters.
_ : Matches a single character.
[specifier] : Brackets enclose ranges or sets, such as [a-f]
or [abcdef].Specifier can take two forms:
rangespec1-rangespec2:
rangespec1 indicates the start of a range of characters.
- is a special character, indicating a range.
rangespec2 indicates the end of a range of characters.
set:
can be composed of any discrete set of values, in any
order, such as [a2bR].The range [a-f], and the
sets [abcdef] and [fcbdae] return the same
set of values.
Specifiers are case-sensitive.
[^specifier] : A caret (^) preceding a specifier indicates
non-inclusion. [^a-f] means "not in the range
a-f"; [^a2bR] means "not a, 2, b, or R."
The following code works at both Chrome and Firefox
<a href="#"><img src="me-more-smile.jpg" onmouseover="this.src='me-thinking-about-a-date.jpg'" onmouseout="this.src='me-more-smile.jpg'" border="0" alt=""/></a>
Look for "Windows x86", it's the 32 bit version.
mwebView.setDownloadListener(new DownloadListener()
{
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition,
mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}});
instead of
listItems.add("New Item");
adapter.notifyDataSetChanged();
you can directly call
adapter.add("New Item");
htons
is host-to-network short
This means it works on 16-bit short integers. i.e. 2 bytes.
This function swaps the endianness of a short.
Your number starts out at:
0001 0011 1000 1001 = 5001
When the endianness is changed, it swaps the two bytes:
1000 1001 0001 0011 = 35091
you can find Java Communications API 2.0 in below link
Maybe I am wrong, but as far as I can see Access-Control-Allow-Origin
has an "origin-list"
as parameter.
By definition an origin-list
is:
origin = "origin" ":" 1*WSP [ "null" / origin-list ]
origin-list = serialized-origin *( 1*WSP serialized-origin )
serialized-origin = scheme "://" host [ ":" port ]
; <scheme>, <host>, <port> productions from RFC3986
And from this, I argue different origins are admitted and should be space separated.
MyClass
and YourClass
could both be derived from SomeonesClass
which has an abstract (virtual) Callback
method. Your addHandler
would accept objects of type SomeonesClass
and MyClass
and YourClass
can override Callback
to provide their specific implementation of callback behavior.
deleting tensorflow from cDrive/users/envs/tensorflow and after that
conda create -n tensorflow python=3.6
activate tensorflow
pip install --ignore-installed --upgrade tensorflow
now its working for newer versions of python thank you
Found one from Flickr that doesn't need registration / api.
Basic sample, Fiddle: http://jsfiddle.net/Braulio/vDr36/
More info: post
Pasted sample
HTML
<div id="images">
</div>
Javascript
// Querystring, "tags" search term, comma delimited
var query = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?";
// This function is called once the call is satisfied
// http://stackoverflow.com/questions/13854250/understanding-cross-domain-xhr-and-xml-data
var mycallback = function (data) {
// Start putting together the HTML string
var htmlString = "";
// Now start cycling through our array of Flickr photo details
$.each(data.items, function(i,item){
// I only want the ickle square thumbnails
var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
// Here's where we piece together the HTML
htmlString += '<li><a href="' + item.link + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
htmlString += '" alt="'; htmlString += item.title + '" />';
htmlString += '</a></li>';
});
// Pop our HTML in the #images DIV
$('#images').html(htmlString);
};
// Ajax call to retrieve data
$.getJSON(query, mycallback);
Another very interesting is Star Wars Rest API:
Delete all invisible characters (whitespace) around that area, then give it another try.
I've seen that error in Safari when copy/pasting code. You can pick up some invalid (and unfortunately invisible) characters.
Used to happen to me a lot when copying from jsFiddle.
There is my working solution for sending image with post, using apache http libraries (very important here is boundary add It won't work without it in my connection):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setBoundary(boundary)
.addPart("group", sbGroup)
.addPart("owner", sbOwner)
.addPart("image", bab)
.build();
httpPost.setEntity(entity);
try {
HttpResponse response = httpclient.execute(httpPost);
...then reading response
I'd use SimpleXMLElement.
<?php
$xml = new SimpleXMLElement('<xml/>');
for ($i = 1; $i <= 8; ++$i) {
$track = $xml->addChild('track');
$track->addChild('path', "song$i.mp3");
$track->addChild('title', "Track $i - Track Title");
}
Header('Content-type: text/xml');
print($xml->asXML());
I tried to add another join(), and it seems worked. Here is code
from threading import Thread
from time import sleep
def function01(arg,name):
for i in range(arg):
print(name,'i---->',i,'\n')
print (name,"arg---->",arg,'\n')
sleep(1)
def test01():
thread1 = Thread(target = function01, args = (10,'thread1', ))
thread1.start()
thread2 = Thread(target = function01, args = (10,'thread2', ))
thread2.start()
thread1.join()
thread2.join()
print ("thread finished...exiting")
test01()
Just add
white-space: initial;
to the text, a line text will come automatically in the next line.
I'm not sure but:
If you call the delete method with a non transient object, this means first fetched the object from the DB. So it is normal to see a select statement. Perhaps in the end you see 2 select + 1 delete?
If you call the delete method with a transient object, then it is possible that you have a cascade="delete"
or something similar which requires to retrieve first the object so that "nested actions" can be performed if it is required.
Edit: Calling delete() with a transient instance means doing something like that:
MyEntity entity = new MyEntity();
entity.setId(1234);
session.delete(entity);
This will delete the row with id 1234, even if the object is a simple pojo not retrieved by Hibernate, not present in its session cache, not managed at all by Hibernate.
If you have an entity association Hibernate probably have to fetch the full entity so that it knows if the delete should be cascaded to associated entities.
Following on from the examples already given, I'd say, it's best practice to also wrap the response in a using like this
public bool IsValidUrl(string url)
{
try
{
var request = WebRequest.Create(url);
request.Timeout = 5000;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
response.Close();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch (Exception exception)
{
return false;
}
}
For windows you can either use the full path with '\\' ('/' for Linux and Mac) as separator of you can use os.getcwd to get the current working directory and give path in reference to the current working directory
data_dir = os.getcwd()+'\\child_directory'
file = open(data_dir+'\\filename.txt', 'r')
When I tried to give the path of child_diectory entirely it resulted in error. For e.g. in this case:
file = open('child_directory\\filename.txt', 'r')
Resulted in error. But I think it must work or I am doing it somewhat wrong way but it doesn't work for me. The about way always works.
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
What kind of object are you using for databinding? Typically I use Collection<T>, List<T>, or Queue<T> (depending on circumstances). These are relatively easy to sort using a custom delegate. See MSDN documentation on the Comparison(T) delegate.
If you want to use the same drawer as lollipop then let me tell you that's not a static image. That image is drawn in real time by a class called DrawerArrowDrawableToggle
. So there is no "hamburger" icon for that.
However if you want the hamburger icon with no animation you can find it here:
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
You could also use matrix multiplication (aka dot product):
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)
numpy.dot(c,a)
Which is more elegant is probably a matter of taste.
In PHP use the function htmlspecialchars() to escape <
and >
.
htmlspecialchars('<strong>something</strong>')
Posting this because unlike the previous answers this one is generic, no external libraries, O(n), actually filters out the duplicate and keeps the order the OP is asking for (by placing the last matching element in place of first appearance):
function unique(array, keyfunc) {
return array.reduce((result, entry) => {
const key = keyfunc(entry)
if(key in result.seen) {
result.array[result.seen[key]] = entry
} else {
result.seen[key] = result.array.length
result.array.push(entry)
}
return result
}, { array: [], seen: {}}).array
}
Usage:
var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"})
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"})
var arr3 = unique([...arr1, ...arr2], x => x.name)
/* arr3 == [
{name: "lang", value: "German"},
{name: "age", value: "18"},
{name: "childs", value: "5"}
]*/
In the project I'm working on, audit log also started from the very minimalistic design, like the one you described:
event ID
event date/time
event type
user ID
description
The idea was the same: to keep things simple.
However, it quickly became obvious that this minimalistic design was not sufficient. The typical audit was boiling down to questions like this:
Who the heck created/updated/deleted a record
with ID=X in the table Foo and when?
So, in order to be able to answer such questions quickly (using SQL), we ended up having two additional columns in the audit table
object type (or table name)
object ID
That's when design of our audit log really stabilized (for a few years now).
Of course, the last "improvement" would work only for tables that had surrogate keys. But guess what? All our tables that are worth auditing do have such a key!
ASCII is at the start of UNICODE, so you can do something like this:
(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'
I'm sure you can figure out the other values...
I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space
git rebase origin
means "rebase from the tracking branch of origin
", while git rebase origin/master
means "rebase from the branch master
of origin
"
You must have a tracking branch in ~/Desktop/test
, which means that git rebase origin
knows which branch of origin
to rebase with. If no tracking branch exists (in the case of ~/Desktop/fallstudie
), git doesn't know which branch of origin
it must take, and fails.
To fix this, you can make the branch track origin/master
with:
git branch --set-upstream-to=origin/master
Or, if master
isn't the currently checked-out branch:
git branch --set-upstream-to=origin/master master
turn on display errors in your ini
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
(For who ever got here due to wrong table style) Change Table style from plain to grouped, via the attributes inspector, or via code:
let tableView = UITableView(frame: .zero, style: .grouped)
Followed the steps.
DevKit
to path C:\Ruby193\DevKit
cd C:\Ruby192\DevKit
ruby dk.rb init
ruby dk.rb review
ruby dk.rb install
Then I wrote the command
gem install rails -r -y
Try this Function :
public int indexOfArray(String input){
for(int i=0;i<TYPES,length();i++)
{
if(TYPES[i].equals(input))
{
return i ;
}
}
return -1 // if the text not found the function return -1
}
You can use $addToSet with the aggregation framework to count distinct objects.
For example:
db.collectionName.aggregate([{
$group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])
No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.
At this point the best you can do is GetXXX style extension methods.
I solved this problem by enabling WCF Services
Programs and Features > NET Framework 4.5 Services > WCF Services> HTTP Activation node
But you have to admit it guys this ENTIRE IIS setup configure/guess/trial and see/try this/try that spends 4 or 5 of our days trying to find a solution around approach IS A COMPLETE AND UTTER JOKE.
SURELY, 'IIS' IS THE BIGGEST CONFIDENCE TRICK EVER PLAYED ON MANKIND TO DATE
You could use the FOR /F loop, to assign the output to a variable.
I use the cmd-variable
, so it's not neccessary to escape the pipe or other characters in the cmd-string, as the delayed expansion passes the string "unchanged" to the FOR-Loop.
@echo off
cls
setlocal EnableDelayedExpansion
set "cmd=findstr /R /N "^^" file.txt | find /C ":""
for /f %%a in ('!cmd!') do set number=%%a
echo %number%
Thus, to summarise the existing discussion, adding
cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5
to your plot, where 1.5 could be 2, 3, etc. and a value of 1 is the default will increase the font size.
x <- rnorm(100)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE,
cex=1.5)
hist(x, xlim=range(x),
xlab= "Variable Lable", ylab="density", main="Title of plot", prob=TRUE,
cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)
Embedded environment, sometime, there is no MMU, less memory, less storage space. In C programming level, almost same, cross compiler do their job.
I asked the original question - @Trott's answer is surely the best.
However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof
operator can fail especially in front-end development when crossing boundaries such as iframes. See:
https://github.com/mrdoob/three.js/issues/5886
If you are ok with duck typing, this should be good:
let isError = function(e){
return e && e.stack && e.message;
}
I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.
if you wanted to get a little more precise, you could do this:
let isError = function(e){
return e && e.stack && e.message && typeof e.stack === 'string'
&& typeof e.message === 'string';
}
Code for Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Output
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
In my case, I was getting this exact error running on port 443, and (for reasons I won't go into here) switching to a different port was not an option. In order to get IIS Express to work on port 443, I had to run this command...
C:\Program Files\IIS Express>IisExpressAdminCmd.exe setupsslUrl -url:https://localhost:443/ -UseSelfSigned
Much thanks to Robert Muehsig for originally posting this solution here.
You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:
class IEqualityComparer {
public function equals($x, $y) {
throw new Exception("Not implemented!");
}
public function getHashCode($obj) {
throw new Exception("Not implemented!");
}
}
class HashMap {
private $map = array();
private $comparer;
public function __construct(IEqualityComparer $keyComparer) {
$this->comparer = $keyComparer;
}
public function has($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return true;
}
}
return false;
}
public function get($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return $item['value'];
}
}
return false;
}
public function del($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
unset($this->map[$hash][$index]);
if (count($this->map[$hash]) == 0)
unset($this->map[$hash]);
return true;
}
}
return false;
}
public function put($key, $value) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
$this->map[$hash] = array();
}
$newItem = array('key' => $key, 'value' => $value);
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
$this->map[$hash][$index] = $newItem;
return;
}
}
$this->map[$hash][] = $newItem;
}
}
For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)
Here is an example:
class IntArrayComparer extends IEqualityComparer {
public function equals($x, $y) {
if (count($x) !== count($y))
return false;
foreach ($x as $key => $value) {
if (!isset($y[$key]) || $y[$key] !== $value)
return false;
}
return true;
}
public function getHashCode($obj) {
$hash = 0;
foreach ($obj as $key => $value)
$hash ^= $key ^ $value;
return $hash;
}
}
$hashmap = new HashMap(new IntArrayComparer());
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
$hashmap->put(array($i, $j), $i * 10 + $j);
}
}
echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";
$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
Which gives as output:
37
51
true
false
false
false
false
you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".
In case there are many people using your vagrant file - you might want to set name dynamically. Below is the example how to do it using username from your HOST machine as the name of the box and hostname:
require 'etc'
vagrant_name = "yourProjectName-" + Etc.getlogin
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.hostname = vagrant_name
config.vm.provider "virtualbox" do |v|
v.name = vagrant_name
end
end
I am using these ones (decimal format, with 6 decimal digits):
^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$
^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$
Here is a gist that tests both, reported here also, for ease of access. It's a Java TestNG test. You need Slf4j, Hamcrest and Lombok to run it:
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.*;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import lombok.extern.slf4j.Slf4j;
import org.testng.annotations.Test;
@Slf4j
public class LatLongValidationTest {
protected static final String LATITUDE_PATTERN="^(\\+|-)?(?:90(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\\.[0-9]{1,6})?))$";
protected static final String LONGITUDE_PATTERN="^(\\+|-)?(?:180(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\\.[0-9]{1,6})?))$";
@Test
public void latitudeTest(){
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.UP);
double step = 0.01;
Double latitudeToTest = -90.0;
while(latitudeToTest <= 90.0){
boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
assertThat(result, is(true));
latitudeToTest += step;
}
latitudeToTest = -90.1;
while(latitudeToTest >= -200.0){
boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
assertThat(result, is(false));
latitudeToTest -= step;
}
latitudeToTest = 90.01;
while(latitudeToTest <= 200.0){
boolean result = df.format(latitudeToTest).matches(LATITUDE_PATTERN);
log.info("Latitude: tested {}. Result (matches regex): {}", df.format(latitudeToTest), result);
assertThat(result, is(false));
latitudeToTest += step;
}
}
@Test
public void longitudeTest(){
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.UP);
double step = 0.01;
Double longitudeToTest = -180.0;
while(longitudeToTest <= 180.0){
boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
assertThat(result, is(true));
longitudeToTest += step;
}
longitudeToTest = -180.01;
while(longitudeToTest >= -300.0){
boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
assertThat(result, is(false));
longitudeToTest -= step;
}
longitudeToTest = 180.01;
while(longitudeToTest <= 300.0){
boolean result = df.format(longitudeToTest).matches(LONGITUDE_PATTERN);
log.info("Longitude: tested {}. Result (matches regex): {}", df.format(longitudeToTest), result);
assertThat(result, is(false));
longitudeToTest += step;
}
}
}
Here is a simple solution I like:
Put your DB connection info in a YAML file in a secure location (do not version it in the code repo).
---
host: 'hostname'
port: port_number_integer
database: 'databasename'
user: 'username'
password: 'password'
Then load the conf in a dictionary, open the db connection and load the result set of the SQL query in a data frame:
import yaml
import pymysql
import pandas as pd
db_conf_path = '/path/to/db-conf.yaml'
# Load DB conf
with open(db_conf_path) as db_conf_file:
db_conf = yaml.safe_load(db_conf_file)
# Connect to the DB
db_connection = pymysql.connect(**db_conf)
# Load the data into a DF
query = '''
SELECT *
FROM my_table
LIMIT 10
'''
df = pd.read_sql(query, con=db_connection)
With androidx, the classic support libraries no longer work.
Simple solution is to use following code
In your build.gradle
file
android{
...
...
defaultConfig {
...
...
multiDexEnabled true
}
...
}
dependencies {
...
...
implementation 'androidx.multidex:multidex:2.0.1'
}
And in your manifest just add name attribute to the application tag
<manifest ...>
<application
android:name="androidx.multidex.MultiDexApplication"
...
...>
...
...
</application>
</manifest>
If your application is targeting API 21 or above multidex is enables by default.
Now if you want to get rid of many of the issues you face trying to support multidex - first try using code shrinking by setting minifyEnabled true
.
$('.class').length
This one does not work for me. I'd rather use this:
$('.class').children().length
I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
This works:
assertThat(list,IsEmptyCollection.empty())
Everyone is answering correctly about the transparency but not listening to what the guy needs in regards to the list scrolling behind the footer.
You need to make the footer part of your ListView
. At the moment the list won't scroll behind because the layout of the ListView does not go behind the footer view with the transparency. Make a RelativeLayout
and position the transparency at the bottom.
0 values of basic types (1)(2)map to false
.
Other values map to true
.
This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.
It's a common error to assume that as function return values, false
indicates failure. But in particular from main
it's false
that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.
There's no need to cast to bool
for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x
, works nicely. One can read !!
as a “convert to bool
” operator, much as -->
can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)
1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false
; any other value is converted to true
. For direct-initialization (8.5), a prvalue of type std::nullptr_t
can be converted to a prvalue of type bool
; the resulting value is false
.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool
, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”
viewDidLoad()
—Called when the view controller’s content view (the top of its view hierarchy) is created and loaded from a storyboard. … Use this method to perform any additional setup required by your view controller.
viewWillAppear()
—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen
viewDidAppear()
—Called just after the view controller’s content view has been added to the app’s view hierarchy. Use this method to trigger any operations that need to occur as soon as the view is presented onscreen, such as fetching data or showing an animation.
viewWillDisappear()
—Called just before the view controller’s content view is removed from the app’s view hierarchy. Use this method to perform cleanup tasks like committing changes or resigning the first responder status.
viewDidDisappear()
—Called just after the view controller’s content view has been removed from the app’s view hierarchy. Use this method to perform additional teardown activities.
You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.
str=xpath.replaceAll("\\.", "/*/"); //replaces a literal . with /*/
Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}
It is kind of a hack but wrapping it in a timeout seems to accomplish what you are looking for:
angular.module('myApp', [])
.controller('Ctrl', ['$scope', '$timeout', function ($scope, $timeout) {
$scope.todos = [{
'text': "get milk",
'done': true
}, {
'text': "get milk2",
'done': false
}];
$scope.onCompleteTodo = function (todo) {
$timeout(function(){
console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text);
$scope.doneAfterClick = todo.done;
$scope.todoText = todo.text;
});
};
}]);
I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="sysBlack">#FF000000</color>
<color name="sysBlue">#FF0000FF</color>
<color name="sysCyan">#FF00FFFF</color>
<color name="sysDkGray">#FF444444</color>
<color name="sysGray">#FF888888</color>
<color name="sysGreen">#FF00FF00</color>
<color name="sysLtGray">#FFCCCCCC</color>
<color name="sysMagenta">#FFFF00FF</color>
<color name="sysRed">#FFFF0000</color>
<color name="sysTransparent">#00000000</color>
<color name="sysWhite">#FFFFFFFF</color>
<color name="sysYellow">#FFFFFF00</color>
</resources>
Of course, this is used like this:
android:textColor="@color/sysGray"
It's simple. Just add display:table-cell
in your main class.
.main {
height: 72px;
vertical-align: middle;
display:table-cell;
border: 1px solid #000000;
}
Check out this jsfiddle!
It looks like there's something else called Afisho_rankimin
in your DB so the function is not being created. Try calling your function something else. E.g.
CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
Note that you need to call this only once, not every time you call the function. After that try calling
SELECT dbo.Afisho_rankimin1(5) AS Rankimi
You have to read the data too.
Check out : http://www.doughellmann.com/PyMOTW/urllib2/ to understand it.
response = urllib2.urlopen(..)
headers = response.info()
data = response.read()
Of course, what you want is to render it in browser and aaronasterling's answer is what you want.
Options -Indexes perfectly works for me ,
here is .htaccess
file :
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes <---- This Works for Me :)
</IfModule>
....etc stuff
</IfModule>
After :
"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."
from http://api.jquery.com/jquery.each/
Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:
function findXX(word) {_x000D_
$.each(someArray, function(index, value) {_x000D_
$('body').append('-> ' + index + ":" + value + '<br />');_x000D_
return !(value == word);_x000D_
});_x000D_
}_x000D_
$(function() {_x000D_
someArray = new Array();_x000D_
someArray[0] = 't5';_x000D_
someArray[1] = 'z12';_x000D_
someArray[2] = 'b88';_x000D_
someArray[3] = 's55';_x000D_
someArray[4] = 'e51';_x000D_
someArray[5] = 'o322';_x000D_
someArray[6] = 'i22';_x000D_
someArray[7] = 'k954';_x000D_
findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
A bit more with comments:
function findXX(myA, word) {_x000D_
let br = '<br />';//create once_x000D_
let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
let found = false;//default return_x000D_
$.each(myA, function(index, value) {_x000D_
found = (value == word);_x000D_
myHolder.append('-> ' + index + ":" + value + br);_x000D_
return !found;_x000D_
});_x000D_
$('body').append(myHolder.html());// hit DOM once_x000D_
return found;_x000D_
}_x000D_
$(function() {_x000D_
// no horrid global array, easier array setup;_x000D_
let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
// pass the array and the value we want to find, return back a value_x000D_
let test = findXX(someArray, 'o322');_x000D_
$('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
NOTE: array .includes()
may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Or just .find()
to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
atan(x) Returns the principal value of the arc tangent of x, expressed in radians.
atan2(y,x) Returns the principal value of the arc tangent of y/x, expressed in radians.
Notice that because of the sign ambiguity, a function cannot determine with certainty in which quadrant the angle falls only by its tangent value (atan alone). You can use atan2 if you need to determine the quadrant.
It's true that Messagebox.show("dd");
is not a part of using System.Web;
,
I felt the same situation for most of time. If you want to do this then do the following steps.
go for add reference, then choose .NET tab
And select, System.windows.forms (press 's' to find quickly)
u can get the namespace, now u can use Messagebox.show("dd");
But I recommend to go with javascript alert for this.
it's possible with v2 = Convert.ToInt32(v1);
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477
Or you can read it there ==>
When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.
From the documentation Restore activity UI state using saved instance state it is stated as:
Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null:
IMO, this is more clear way than checking this at onCreate, and better fits with single responsiblity principle.
<body onload="window.print()">
or
window.onload = function() { window.print(); }
Since the question got bumped I will go ahead and post my solution.
using (var finished = new CountdownEvent(1))
{
for (DataObject data in dataList)
{
finished.AddCount();
var localData = (DataObject)data.Clone();
var thread = new Thread(
delegate()
{
try
{
DoThreadStuff(localData);
threadFinish.Set();
}
finally
{
finished.Signal();
}
}
);
thread.Start();
}
finished.Signal();
finished.Wait(YOUR_TIMEOUT);
}
I combined some of Flavio's answer to this small solution.
.hidden-ul-bullets li {
list-style: none;
}
.hidden-ul-bullets ul {
margin-left: 0.25em; // for my purpose, a little indentation is wished
}
The decision about bullets is made at an enclosing element, typically a div
. The drawback (or todo) of my solution is that the liststyle removal also applies to ordered lists.