isoformat()
Python's datetime
does not support the military timezone suffixes like 'Z' suffix for UTC. The following simple string replacement does the trick:
In [1]: import datetime
In [2]: d = datetime.datetime(2014, 12, 10, 12, 0, 0)
In [3]: str(d).replace('+00:00', 'Z')
Out[3]: '2014-12-10 12:00:00Z'
str(d)
is essentially the same as d.isoformat(sep=' ')
See: Datetime, Python Standard Library
strftime()
Or you could use strftime
to achieve the same effect:
In [4]: d.strftime('%Y-%m-%dT%H:%M:%SZ')
Out[4]: '2014-12-10 12:00:00Z'
Note: This option works only when you know the date specified is in UTC.
See: datetime.strftime()
Going further, you may be interested in displaying human readable timezone information, pytz
with strftime
%Z
timezone flag:
In [5]: import pytz
In [6]: d = datetime.datetime(2014, 12, 10, 12, 0, 0, tzinfo=pytz.utc)
In [7]: d
Out[7]: datetime.datetime(2014, 12, 10, 12, 0, tzinfo=<UTC>)
In [8]: d.strftime('%Y-%m-%d %H:%M:%S %Z')
Out[8]: '2014-12-10 12:00:00 UTC'
I have query,
$("#login-button").click(function(e){ alert("hiii");
var username = $("#username-field").val();
var password = $("#username-field").val();
alert(username);
alert("password" + password);
var markers = { "userName" : "admin","password" : "admin123"};
$.ajax({
type: "POST",
url: url,
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert("got the data"+data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
I'm posting the the login details in json and getting a string as "Success"
,but I'm not getting the response.
According to the Microsoft documentation, the TimeSpan structure exposes Hours, Minutes, Seconds, and Milliseconds as integer members. Maybe you want something like:
dateDifference.Hours.ToString() + " hrs, " + dateDifference.Minutes.ToString() + " mins, " + dateDifference.Seconds.ToString() + " secs"
I took a more compact approach to split an input resulting from a text area into a list of string . You can use this if suits your purpose.
the problem is you cannot split by \r\n so i removed the \n beforehand and split only by \r
var serials = model.List.Replace("\n","").Split('\r').ToList<string>();
I like this approach because you can do it in just one line.
If you want a list of strings containing your string:
var newList = myList.Where(x => x.Contains(myString)).ToList();
Another option is to use Linq FirstOrDefault
var element = myList.Where(x => x.Contains(myString)).FirstOrDefault();
Keep in mind that Contains
method is case sensitive.
From your Activity
, just pass in this
as the Context
for your layout:
ProfileView pv = new ProfileView(this, null, temp, tempPd);
Afterwards you will have a Context
in the layout, but you will know it is actually your Activity
and you can cast it so that you have what you need:
Activity activity = (Activity) context;
DEMO : https://jsfiddle.net/ipsjolly/xygr065w/
$(function(){
$("#submit").click(function(){
alert($('input:radio:checked').val());
});
});
public class MyToolbar extends android.support.v7.widget.Toolbar {
public MyToolbar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
AppCompatTextView textView = (AppCompatTextView) getChildAt(0);
if (textView!=null) textView.setTextAppearance(getContext(), R.style.TitleStyle);
}
}
Or simple use from MainActivity:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarMain);
setSupportActionBar(toolbar);
((AppCompatTextView) toolbar.getChildAt(0)).setTextAppearance(this, R.style.TitleStyle);
style.xml
<style name="TileStyle" parent="TextAppearance.AppCompat">
<item name="android:textColor">@color/White</item>
<item name="android:shadowColor">@color/Black</item>
<item name="android:shadowDx">-1</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">1</item>
</style>
Now i use this method based in Duncan Babbage response:
+ (UIImageView *) tintImageView: (UIImageView *)imageView withColor: (UIColor*) color{
imageView.image = [imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[imageView setTintColor:color];
return imageView;
}
I wanted to remove "www."
from a href so I did this:
const str = "https://www.example.com/path";
str.split("www.").join("");
// https://example.com/path
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
The problem might be your split()
call. Try just split(" ")
without the square brackets.
SELECT *
INTO #Temp
FROM
(SELECT
Received,
Total,
Answer,
(CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) AS application
FROM
FirstTable
WHERE
Recieved = 1 AND
application = 'MORESTUFF'
GROUP BY
CASE WHEN application LIKE '%STUFF%' THEN 'MORESTUFF' END) data
WHERE
application LIKE
isNull(
'%MORESTUFF%',
'%')
Use statistics.mean
:
import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335
It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats
. Just change statistics
to stats
.
The best way to get good control over the colorbar position is to give it its own axis. Like so:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)
# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)
The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.
If you get this error when you try to pipe/redirect output of your script
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
Just export PYTHONIOENCODING in console and then run your code.
export PYTHONIOENCODING=utf8
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
According to the Swift 2.2 Book published by apple:
“You indicate type methods by writing the static
keyword before the method’s func keyword. Classes may also use the class
keyword to allow subclasses to override the superclass’s implementation of that method.”
This simple extension worked beautifully for me. I just had to make sure that MyObject
was IComparable
. When the sort method is called on the observable collection of MyObjects
, the CompareTo
method on MyObject
is called, which calls my Logical Sort method. While it doesn't have all the bells and whistles of the rest of the answers posted here, it's exactly what I needed.
static class Extensions
{
public static void Sort<T>(this ObservableCollection<T> collection) where T : IComparable
{
List<T> sorted = collection.OrderBy(x => x).ToList();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
}
public class MyObject: IComparable
{
public int CompareTo(object o)
{
MyObject a = this;
MyObject b = (MyObject)o;
return Utils.LogicalStringCompare(a.Title, b.Title);
}
public string Title;
}
.
.
.
myCollection = new ObservableCollection<MyObject>();
//add stuff to collection
myCollection.Sort();
String user_email = email.getText().toString().trim();
firebaseAuth
.createUserWithEmailAndPassword(user_email,user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(RegistraionActivity.this, "Registration sucessful", Toast.LENGTH_SHORT).show();
startActivities(new Intent(RegistraionActivity.this,MainActivity.class));
}else{
Toast.makeText(RegistraionActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
});
Follow below gitbash commands to push the folder files on github repository :-
1.) $ git init
2.) $ git cd D:\FileFolderName
3.) $ git status
4.) If needed to switch the git branch, use this command :
$ git checkout -b DesiredBranch
5.) $ git add .
6.) $ git commit -m "added a new folder"
7.) $ git push -f https://github.com/username/MyTestApp.git TestBranch
(i.e git push origin branch)
You cannot directly access the table with the name 'customer'. Either it should be 'user1.customer' or create a synonym 'customer' for user2 pointing to 'user1.customer'. hope this helps..
There are a few ways to accomplish this, here's a few:
Written using State Hooks:
function Checkbox() {
const [checked, setChecked] = React.useState(true);
return (
<label>
<input type="checkbox"
defaultChecked={checked}
onChange={() => setChecked(!checked)}
/>
Check Me!
</label>
);
}
ReactDOM.render(
<Checkbox />,
document.getElementById('checkbox'),
);
Here is a live demo on JSBin.
Written using Components:
class Checkbox extends React.Component {
constructor(props) {
super(props);
this.state = {
isChecked: true,
};
}
toggleChange = () => {
this.setState({
isChecked: !this.state.isChecked,
});
}
render() {
return (
<label>
<input type="checkbox"
defaultChecked={this.state.isChecked}
onChange={this.toggleChange}
/>
Check Me!
</label>
);
}
}
ReactDOM.render(
<Checkbox />,
document.getElementById('checkbox'),
);
Here is a live demo on JSBin.
Swift 5:
func open(scheme: String) {
if let url = URL(string: scheme) {
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:],
completionHandler: {
(success) in
print("Open \(scheme): \(success)")
})
} else {
let success = UIApplication.shared.openURL(url)
print("Open \(scheme): \(success)")
}
}
}
Usage:
open(scheme: "http://www.bing.com")
Reference:
I had this exact problem.
The issue is that there is an old version of numpy in the default mac install, and that pip install pandas
sees that one first and fails -- not going on to see that there is a newer version that pip
herself has installed.
If you're on a default mac install, and you've done pip install numpy --upgrade
to be sure you're up to date, but pip install pandas
still fails due to an old numpy
, try the following:
$ cd /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/
$ sudo rm -r numpy
$ pip install pandas
This should now install / build pandas.
To check it out what we've done, do the following: start python, and import numpy
and import pandas
. With any luck, numpy.__version__
will be 1.6.2 (or greater), and pandas.__version__
will be 0.9.1 (or greater).
If you'd like to see where pip has put (found!) them, just print(numpy)
and print(pandas)
.
I also faced the same issue. After lot of hard work, I found what was wrong in my case. My device was connected to computer via USB cable. There are types for USB connections like Mass Storage, Media Device(MTP), Camera(PTP) etc. My connection type was - 'Mass Storage', and this was causing the problems. When I changed the connection type, the issue was solved.
Always remember while accessing filesystem on android device :-
DON'T CONNECT AS MASS STORAGE to the computer/pc.
The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.
So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?
You're trying to cherry pick fd9f578
, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m
option. For example, git cherry-pick -m 1 fd9f578
to use parent 1 as the base.
I can't say for sure for your particular situation, but using git merge
instead of git cherry-pick
is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
You could print the backspace character \b
as many times as the characters which were printed before.
System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");
Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?
void ltrim(char str[PATH_MAX])
{
int i = 0, j = 0;
char buf[PATH_MAX];
strcpy(buf, str);
for(;str[i] == ' ';i++);
for(;str[i] != '\0';i++,j++)
buf[j] = str[i];
buf[j] = '\0';
strcpy(str, buf);
}
public static T IsNull<T>(this T DefaultValue, T InsteadValue)
{
object obj="kk";
if((object) DefaultValue == DBNull.Value)
{
obj = null;
}
if (obj==null || DefaultValue==null || DefaultValue.ToString()=="")
{
return InsteadValue;
}
else
{
return DefaultValue;
}
}
//This method can work with DBNull and null value. This method is question's answer
Not sure if I completely understand the question, but you can modify instance properties at runtime with the built-in __dict__
of your class:
class C(object):
def __init__(self, ks, vs):
self.__dict__ = dict(zip(ks, vs))
if __name__ == "__main__":
ks = ['ab', 'cd']
vs = [12, 34]
c = C(ks, vs)
print(c.ab) # 12
Using the CLI, to create a functioning NUnit project is really easy. The template does everything for you.
dotnet new -i NUnit3.DotNetNew.Template
dotnet new nunit
On .NET Core, this is definitely my preferred way to go.
I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110
and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.
I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
For me I had a special characters in my password field, and I put it like $mail->Password = " por$ch3" which work for gmail smpt server but not for other; so I just changed double quotes to single quotes and it works for me. $mail->Password = ' por$ch3';
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML. Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
You can use one and more echo statement inside href
<a href="profile.php?usr=<?php echo $_SESSION['firstname']."&email=". $_SESSION['email']; ?> ">Link</a>
link : "/profile.php?usr=firstname&email=email"
I'm using UBUNTU and I got this same error. I restarted the set up using sudo and did a custom install. This solved my problem!
--More Specific--
re-installed using # sudo ./studio.sh
then I made sure to click "Custom Install"
then I made sure all packages were selected.
And I got this message Android virtual device Nexus_5_API_22_x86 was successfully created
The "trunk", "branches", and "tags" directories are conventions in Subversion. Subversion does not require you to have these directories nor assign special meaning to them. However, this convention is very common and, unless you have a really good reason, you should follow the convention. The book links that other readers have given describe the convention and how to use it.
The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections
in $qProvider configuration as suggested Cengkuru Michael
BUT this will only switch off logging. The error itself will remain
The better solution in this case will be - handling a rejection with .catch(fn)
method:
resource.get().$promise
.then(function (response) {})
.catch(function (err) {});
LINKS:
The following code will reduce the problem to check the protocol. The $_SERVER['APP_URL'] will display the domain name with the protocol
$_SERVER['APP_URL'] will return protocol://domain ( eg:-http://localhost)
$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else
$url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];
The output would be like this
Just window.location = "http://wherever.you.wanna.go.com/"
, or, for local links, window.location = "my_relative_link.html"
.
You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/"
.
Also note that the protocol part of the URL (http://
) is not optional for absolute links; omitting it will make javascript assume a relative link.
I took all of the podcasts from the answers scoring 5 or better (and those in the original question) and added them to an aggregated page on Cullect.com:
http://www.cullect.com/StackOverflow-Recommended-Podcasts
It provides a handy way to get a glimpse of these podcasts as well as a way to preview them if you're in a hurry or don't want to wade through all of the duplicates in the answers. I'm currently set up as the only curator of the "cullection", but if someone else wants to help keep it adjusted as the answers change, let me know.
echo '<a href="' . $folder_path . '">Link text</a>';
Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.
EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?
java.io.File
class contains four static separator variables. For better understanding, Let's understand with the help of some code
Note that all of these are final variables and system dependent.
Here is the java program to print these separator variables. FileSeparator.java
import java.io.File;
public class FileSeparator {
public static void main(String[] args) {
System.out.println("File.separator = "+File.separator);
System.out.println("File.separatorChar = "+File.separatorChar);
System.out.println("File.pathSeparator = "+File.pathSeparator);
System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
}
}
Output of above program on Unix system:
File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :
Output of the program on Windows system:
File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;
To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.
Here is the code snippet showing how to use separators correctly.
//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
The best way depends a lot on the platform(s) being targeted, debug vs. release usage etc.
I don't think there is one best way, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUG
or _DEBUG
), you could try std::getline
as follows
inline void wait_on_enter()
{
std::string dummy;
std::cout << "Enter to continue..." << std::endl;
std::getline(std::cin, dummy);
}
With our without the "enter to continue", as needed.
Just set the parent to display:flex;
and the child to margin-top:auto
. This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.
There is no need to try and calculate a value for margin-top
when you have a height on your parent element or another element greater than your child element of interest within your parent element.
this usage may solve your problem.
width: calc(100% - 100px);
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="UTF-8" />_x000D_
<title>Content with Menu</title>_x000D_
<style>_x000D_
.content .left {_x000D_
float: left;_x000D_
width: 100px;_x000D_
background-color: green;_x000D_
}_x000D_
_x000D_
.content .right {_x000D_
float: left;_x000D_
width: calc(100% - 100px);_x000D_
background-color: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="content">_x000D_
<div class="left">_x000D_
<p>Hi, Flo!</p>_x000D_
</div>_x000D_
<div class="right">_x000D_
<p>is</p>_x000D_
<p>this</p>_x000D_
<p>what</p>_x000D_
<p>you are looking for?</p>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I have to add to Collin Andersons answer that this method also takes into account if you have two interfaces and they're both showing as up.
ip route get 1 | awk '{print $NF;exit}'
I have been working on an application with Raspberry Pi's and needed the IP address that was actually being used not just whether it was up or not. Most of the other answers will return both IP address which isn't necessarily helpful - for my scenario anyway.
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
The error SELF_SIGNED_CERT_IN_CHAIN
means that you have self signed certificate in certificate chain which is basically not trusted by the system.
If that happens, basically something fishy is going on, therefore as people already commented, it is not recommended to just disable certificate checks, but better approach is to understand what is the problem and fix the cause of it.
This maybe related either to:
custom repository address which doesn't have the right certificate,
a corporate network with transparent proxy.
If you're behind a corporate web proxy, you should set-up the proper HTTP_PROXY
/HTTPS_PROXY
environment variables or set them via npm
:
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
See: How to setup Node.js and Npm behind a corporate web proxy
If you trust the host, you can export the self-signed certificate from the chain and import them into system, so they're marked as trusted.
This can be achieved by checking the certificates by (change example.com
into npm repo which is failing based on the npm-debug.log
):
openssl s_client -showcerts -connect example.com:443 < /dev/null
then save the certificate content (between BEGIN
and END
) into .crt
file in order to import it.
As per suggestion, you can add the below to the /etc/environment
file (Node 7.4+) to export your CA chain, like:
NODE_EXTRA_CA_CERTS=/etc/pki/ca-trust/source/anchors/yourCer??ts.pem
On CentOS 5 this can be appended into /etc/pki/tls/certs/ca-bundle.crt
file, e.g.
ex +'g/BEGIN CERTIFICATE/,/END CERTIFICATE/p' <(echo | openssl s_client -showcerts -connect example.com:443) -scq | sudo tee -a /etc/pki/tls/certs/ca-bundle.crt
sudo update-ca-trust force-enable
sudo update-ca-trust extract
npm install
Note: To export only first certificate, remove g
at the beginning.
In CentOS 6, the certificate file can be copied to /etc/pki/ca-trust/source/anchors/
.
In Ubuntu/Debian, copy CRT file into /usr/local/share/ca-certificates/
then run:
sudo update-ca-certificates
In macOS you can run:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/foo.crt
In Windows: certutil -addstore -f "ROOT" new-root-certificate.crt
See also: npm - Troubleshooting - SSL Error
You can bind an event handler to the "submit" JavaScript event using jQuery .submit
method and then get trimmed #log
text field value and check if empty of not like:
$('form').submit(function () {
// Get the Login Name value and trim it
var name = $.trim($('#log').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
If you are converting to HTML, you can set the size of the image using HTML syntax using:
<img src="path/to/image" height="400px" width="300px" />
or whatever height and width you would want to give.
int RandU(int nMin, int nMax)
{
return nMin + (int)((double)rand() / (RAND_MAX+1) * (nMax-nMin+1));
}
This is a mapping of 32768 integers to (nMax-nMin+1) integers. The mapping will be quite good if (nMax-nMin+1) is small (as in your requirement). Note however that if (nMax-nMin+1) is large, the mapping won't work (For example - you can't map 32768 values to 30000 values with equal probability). If such ranges are needed - you should use a 32-bit or 64-bit random source, instead of the 15-bit rand(), or ignore rand() results which are out-of-range.
Following could be one of ways:
dataframe = dataframe.sample(frac=1, random_state=42).reset_index(drop=True)
where
frac=1 means all rows of a dataframe
random_state=42 means keeping same order in each execution
reset_index(drop=True) means reinitialize index for randomized dataframe
The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.
//Visual Basic Implementation Request and Response String
Dim params = "key1=value1&key2=value2"
Dim byteArray = UTF8.GetBytes(params)
Dim url = "https://okay.com"
Dim client = WebRequest.Create(url)
client.Method = "POST"
client.ContentType = "application/x-www-form-urlencoded"
client.ContentLength = byteArray.Length
Dim stream = client.GetRequestStream()
//sending the data
stream.Write(byteArray, 0, byteArray.Length)
stream.Close()
//getting the full response in a stream
Dim response = client.GetResponse().GetResponseStream()
//reading the response
Dim result = New StreamReader(response)
//Writes response string to Console
Console.WriteLine(result.ReadToEnd())
Console.ReadKey()
Your CarBootSaleList
class is not a list. It is a class that contain a list.
You have three options:
Make your CarBootSaleList
object implement IEnumerable
or
make your CarBootSaleList inherit from List<CarBootSale>
or
if you are lazy this could almost do the same thing without extra coding
List<List<CarBootSale>>
**In this function you can able to split the function by golang using array of strings**
func SplitCmdArguments(args []string) map[string]string {
m := make(map[string]string)
for _, v := range args {
strs := strings.Split(v, "=")
if len(strs) == 2 {
m[strs[0]] = strs[1]
} else {
log.Println("not proper arguments", strs)
}
}
return m
}
In the C language as it was documented in 1974, all structure members shared a common namespace, and the meaning of "ptr->member" was defined as adding the member's displacement to "ptr" and accessing the resulting address using the member's type. This design made it possible to use the same ptr with member names taken from different structure definitions but with the same offset; programmers used that ability for a variety of purposes.
When structure members were assigned their own namespaces, it became impossible to declare two structure members with the same displacement. Adding unions to the language made it possible to achieve the same semantics that had been available in earlier versions of the language (though the inability to have names exported to an enclosing context may have still necessitated using a find/replace to replace foo->member into foo->type1.member). What was important was not so much that the people who added unions have any particular target usage in mind, but rather that they provide a means by which programmers who had relied upon the earlier semantics, for whatever purpose, should still be able to achieve the same semantics even if they had to use a different syntax to do it.
Instead of creating strange things, you can just filter()
and then map()
your result.
This is much more readable and sure. Streams will make it in only one loop.
Two things:
Use:
DECLARE @temp VARCHAR(10)
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
VARCHAR(10)
means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -
DECLARE @temp VARCHAR
SET @temp = 'm'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "yes"
DECLARE @temp VARCHAR
SET @temp = 'mtest'
IF @temp = 'm'
SELECT 'yes'
ELSE
SELECT 'no'
...will return "no".
I tried the following command to solve the issue and it worked for me:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall
If, like me, you're running gVim on Windows then your .vimrc file may be sourcing another 'example' Vimscript file that automatically sets textwidth
(in my case to 78
) for text files.
My answer to a similar question as this one – How to stop gVim wrapping text at column 80 – on the Vi and Vim Stack Exchange site:
In my case, Vitor's comment suggested I run the following:
:verbose set tw?
Doing so gave me the following output:
textwidth=78 Last set from C:\Program Files (x86)\Vim\vim74\vimrc_example.vim
In vimrc_example.vim, I found the relevant lines:
" Only do this part when compiled with support for autocommands. if has("autocmd") ... " For all text files set 'textwidth' to 78 characters. autocmd FileType text setlocal textwidth=78 ...
And I found that my .vimrc is sourcing that file:
source $VIMRUNTIME/vimrc_example.vim
In my case, I don't want
textwidth
to be set for any files, so I just commented out the relevant line in vimrc_example.vim.
If you are using bootstrap (I am using version 4.0), feel free to try the following code.
<input data-toggle="tooltip" data-placement="top" title="This is the text of the tooltip" value="44"/>
data-placement
can be top, right, bottom or left
[self dismissModalViewControllerAnimated:NO];
has been deprecated.
Use [self dismissViewControllerAnimated:NO completion:nil];
instead.
You could use the 'isActive' prop like so:
const { router } = this.context;
if (router.isActive('/login')) {
router.push('/');
}
isActive will return a true or false.
Tested with react-router 2.7
Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You'll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.
You can use this
string x = "ABCGH"
char[] charX = x.ToCharArray();
Array.Sort(charX);
This will sort your string.
let today = new Date()
let last30Days = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 30)
last30Days
will be in Date Object
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
If the dataframes DO NOT all have the same columns try the following:
df = pd.DataFrame.from_dict(map(dict,df_list))
The idea is to run a loop from i = 1 to floor(sqrt(n)) then check if squaring it makes n.
bool isPerfectSquare(int n)
{
for (int i = 1; i * i <= n; i++) {
// If (i * i = n)
if ((n % i == 0) && (n / i == i)) {
return true;
}
}
return false;
}
If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):
mokey 0 /home/jj33 > nslookup example.ad Server: 172.16.2.10 Address: 172.16.2.10#53 Non-authoritative answer: Name: example.ad Address: 172.16.6.2 Name: example.ad Address: 172.16.141.160 Name: example.ad Address: 172.16.7.9 Name: example.ad Address: 172.19.1.14 Name: example.ad Address: 172.19.1.3 Name: example.ad Address: 172.19.1.11 Name: example.ad Address: 172.16.3.2
Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.
I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.
In this model, you have publishers who will do some logic and publish an "event."
Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.
In C#, any object can publish a set of events to which other applications can subscribe.
When the publishing class raises an event, all the subscribed applications are notified.
The following figure shows this mechanism.
Simplest Example possible on Events and Delegates in C#:
code is self explanatory, Also I've added the comments to clear out the code.
using System;
public class Publisher //main publisher class which will invoke methods of all subscriber classes
{
public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate
public TickHandler Tick; //creating an object of delegate
public EventArgs e = null; //set 2nd paramter empty
public void Start() //starting point of thread
{
while (true)
{
System.Threading.Thread.Sleep(300);
if (Tick != null) //check if delegate object points to any listener classes method
{
Tick(this, e); //if it points i.e. not null then invoke that method!
}
}
}
}
public class Subscriber1 //1st subscriber class
{
public void Subscribe(Publisher m) //get the object of pubisher class
{
m.Tick += HeardIt; //attach listener class method to publisher class delegate object
}
private void HeardIt(Publisher m, EventArgs e) //subscriber class method
{
System.Console.WriteLine("Heard It by Listener");
}
}
public class Subscriber2 //2nd subscriber class
{
public void Subscribe2(Publisher m) //get the object of pubisher class
{
m.Tick += HeardIt; //attach listener class method to publisher class delegate object
}
private void HeardIt(Publisher m, EventArgs e) //subscriber class method
{
System.Console.WriteLine("Heard It by Listener2");
}
}
class Test
{
static void Main()
{
Publisher m = new Publisher(); //create an object of publisher class which will later be passed on subscriber classes
Subscriber1 l = new Subscriber1(); //create object of 1st subscriber class
Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class
l.Subscribe(m); //we pass object of publisher class to access delegate of publisher class
l2.Subscribe2(m); //we pass object of publisher class to access delegate of publisher class
m.Start(); //starting point of publisher class
}
}
Output:
Heard It by Listener
Heard It by Listener2
Heard It by Listener
Heard It by Listener2
Heard It by Listener . . . (infinite times)
For Django 2.1.1 add following lines to urls.py
from django.contrib import admin
# Admin Site Config
admin.sites.AdminSite.site_header = 'My site admin header'
admin.sites.AdminSite.site_title = 'My site admin title'
admin.sites.AdminSite.index_title = 'My site admin index'
Simply, @Id: This annotation specifies the primary key of the entity.
@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used.
GenerationType enum defines four strategies:
1. Generation Type . TABLE,
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY
4. Generation Type. AUTO
GenerationType.SEQUENCE
With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities.
GenerationType.TABLE
With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities.
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used.
Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html
using Eloquent
$data = array(
array('user_id'=>'Coder 1', 'subject_id'=> 4096),
array('user_id'=>'Coder 2', 'subject_id'=> 2048),
//...
);
Model::insert($data);
For anyone looking for a UI option using IIS Manager.
To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.
But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Replace your jquery files with followings :
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
On upgrading to Xcode 8, I got a message to upgrade to recommended settings. I accepted and everything was updated. I started getting compile time issue :
Duplicate symbol for XXXX Duplicate symbol for XXXX Duplicate symbol for XXXX
A total of 143 errors. Went to Target->Build settings -> No Common Blocks -> Set it to NO. This resolved the issue. The issue was that the integrated projects had code blocks in common and hence was not able to compile it. Explanation can be found here.
Of the options you asked about:
float:left;
float
concept was poorly designed in the CSS specs. Nothing we can do about that now though. But the important thing is it does work, and it works in all browsers (even IE6/7), so use it if you like it.The additional markup for clearing may not be necessary if you use the :after
selector to clear the floats, but this isn't an option if you want to support IE6 or IE7.
display:inline;
This shouldn't be used for layout, with the exception of IE6/7, where display:inline; zoom:1
is a fall-back hack for the broken support for inline-block
.
display:inline-block;
This is my favourite option. It works well and consistently across all browsers, with a caveat for IE6/7, which support it for some elements. But see above for the hacky solution to work around this.
The other big caveat with inline-block
is that because of the inline aspect, the white spaces between elements are treated the same as white spaces between words of text, so you can get gaps appearing between elements. There are work-arounds to this, but none of them are ideal. (the best is simply to not have any spaces between the elements)
display:table-cell;
table-cell
is designed to be used in a context of being inside elements that are styled as table
and table-row
; using table-cell
in isolation is not the intended way to do it, so you may experience different browsers treating it differently.Other techniques you may have missed? Yes.
Since you say this is for a multi-column layout, there is a CSS Columns feature that you might want to know about. However it isn't the most well supported feature (not supported by IE even in IE9, and a vendor prefix required by all other browsers), so you may not want to use it. But it is another option, and you did ask.
There's also CSS FlexBox feature, which is intended to allow you to have text flowing from box to box. It's an exciting feature that will allow some complex layouts, but this is still very much in development -- see http://html5please.com/#flexbox
Hope that helps.
setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.
After set listen_addresses = '*'
in postgresql.conf
Edit the pg_hba.conf file and add the following entry at the very end of file:
host all all 0.0.0.0/0 md5
host all all ::/0 md5
For finding the config files this link might help you.
This is bad style, but I'll assume you have a good reason for doing something similar.
<html>
<body>
<input type="text" id="userInput">give me input</input>
<button id="submitter">Submit</button>
<div id="output"></div>
<script>
var didClickIt = false;
document.getElementById("submitter").addEventListener("click",function(){
// same as onclick, keeps the JS and HTML separate
didClickIt = true;
});
setInterval(function(){
// this is the closest you get to an infinite loop in JavaScript
if( didClickIt ) {
didClickIt = false;
// document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
var o=document.getElementById("output"),v=document.getElementById("userInput").value;
if(o.textContent!==undefined){
o.textContent=v;
}else{
o.innerText=v;
}
}
},500);
</script>
</body>
</html>
The negative margin trick:
http://pastehtml.com/view/1dujbt3.html
Not elegant, I suppose, but it works in some cases.
You can use this
function LinkCheck(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Using MySQL inbuilt function group_concat() will be a good choice for getting the desired result. The syntax will be -
SELECT group_concat(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534
AND ISSUE = 19602
Before you execute the above command make sure you increase the size of group_concat_max_len else the the whole output may not fit in that cell.
To set the value of group_concat_max_len, execute the below command-
SET group_concat_max_len = 50000;
You can change the value 50000 accordingly, you increase it to a higher value as required.
You can specify the style
of the plotted line when calling df.plot
:
df.plot(x='col_name_1', y='col_name_2', style='o')
The style
argument can also be a dict
or list
, e.g.:
import numpy as np
import pandas as pd
d = {'one' : np.random.rand(10),
'two' : np.random.rand(10)}
df = pd.DataFrame(d)
df.plot(style=['o','rx'])
All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot
.
DONE=false
until $DONE
do
read line || DONE=true
echo $line
done < blah.txt
Update Sep 2017 - tl;dr
Download a single file from a remote ftp server to your machine:
sftp {user}@{host}:{remoteFileName} {localFileName}
Upload a single file from your machine to a remote ftp server:
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
Original answer:
Ok, so I feel a little dumb. But I figured it out. I almost had it at the top with:
sftp user@host remoteFile localFile
The only documentation shown in the terminal is this:
sftp [user@]host[:file ...]
sftp [user@]host[:dir[/]]
However, I came across this site which shows the following under the synopsis:
sftp [-vC1 ] [-b batchfile ] [-o ssh_option ] [-s subsystem | sftp_server ] [-B buffer_size ] [-F ssh_config ] [-P sftp_server path ] [-R num_requests ] [-S program ] host
sftp [[user@]host[:file [file]]]
sftp [[user@]host[:dir[/]]]
So the simple answer is you just do :
after your user and host then the remote file and local filename. Incredibly simple!
Single line, sftp copy remote file:
sftp username@hostname:remoteFileName localFileName
sftp kyle@kylesserver:/tmp/myLogFile.log /tmp/fileNameToUseLocally.log
Update Feb 2016
In case anyone is looking for the command to do the reverse of this and push a file from your local computer to a remote server in one single line sftp
command, user @Thariama below posted the solution to accomplish that. Hat tip to them for the extra code.
sftp {user}@{host}:{remote_dir} <<< $'put {local_file_path}'
@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.
nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.
nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.
Explicit conversion constructors (C++ only)
The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are conversion constructors.
class A
{
public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal:
A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A( 1 );
.
If you declare the constructor of the class as explicit
, the previous declarations would be illegal.
For example, if you declare the class as:
class A
{
public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.
For example, the following statements are legal:
A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast<A>(1);
if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...
If the above does not help then please provide more details since I am not sure what exactly the problem is you face...
another solution , you can add <br>
tag to your table
|Method name| Behavior |
|--|--|
| OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|
You can use the hasClass
method, eg.
$('li.menu').hasClass('active') // true|false
Or if you want to select it in one go, you can use:
$('li.menu.active')
If you don't want to modify the manifest file, you can manually store the context in a static variable in your initial activity:
public class App {
private static Context context;
public static void setContext(Context cntxt) {
context = cntxt;
}
public static Context getContext() {
return context;
}
}
And just set the context when your activity (or activities) start:
// MainActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set Context
App.setContext(getApplicationContext());
// Other stuff
}
Note: Like all other answers, this is a potential memory leak.
You must use %ld
to print a long int
, and %lld
to print a long long int
.
Note that only long long int
is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).
You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99
option to gcc). This is because the long long int
type was not introduced until C99; and although many compilers implement long long int
in C90 mode as an extension, the constant 2147483648
may have a type of unsigned int
or unsigned long
in C90. If this is the case in your implementation, then the value of -2147483648
will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.
Using regex to validate IP address is a bad idea - this will pass 999.999.999.999 as valid. Try this approach using socket instead - much better validation and just as easy, if not easier to do.
import socket
def valid_ip(address):
try:
socket.inet_aton(address)
return True
except:
return False
print valid_ip('10.10.20.30')
print valid_ip('999.10.20.30')
print valid_ip('gibberish')
If you really want to use parse-the-host approach instead, this code will do it exactly:
def valid_ip(address):
try:
host_bytes = address.split('.')
valid = [int(b) for b in host_bytes]
valid = [b for b in valid if b >= 0 and b<=255]
return len(host_bytes) == 4 and len(valid) == 4
except:
return False
import subprocess as sp
for v in str(sp.check_output('powershell "gps | where {$_.MainWindowTitle}"')).split(' '):
if len(v) is not 0 and '-' not in v and '\\r\\' not in v and 'iTunes' in v: print('Found !')
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd
and type hostname
(example result: LAPTOP-G666P000
, you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E
> right click 'This PC'
> press N
(It's Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U:
or G:
or Z:
or whatever you want
Example Address: \\LAPTOP-G666P000\c$\Users\username\
Then you can use <a href="file:///u:/2ndFile.html"><button type="submit">Local file</button>
like in your question
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
related2: I have used http://localhost/c$
etc before on some WAMP/apache servers too before, you can use .htaccess
for control/security but I recommend to not do so on a live/production machine -- or any other symlink documentroot example you can google
If you need to get scipy
in your Pyhton environment on Windows you can get the *.whl files here:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
Remember that you need to install numpy+mkl
before you can install scipy
.
http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
When you have downloaded the correct *.whl files just open a cmd prompt in the download directory and run pip install *.whl
.
If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string).
Simple example (linux version, see note):
import subprocess
print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])
Note that the ping command is using linux notation (-c
for count). If you try this on Windows remember to change it to -n
for same result.
As commented below you can find a more detailed explanation in this other answer.
Intellij v 13.1.4, OSX
The Open Symbol keyboard shortcut is command+shift+s
To disable ssl cert validation in client configuration.
<behaviors>
<endpointBehaviors>
<behavior name="DisableSSLCertificateValidation">
<clientCredentials>
<serviceCertificate>
<sslCertificateAuthentication certificateValidationMode="None" />
</serviceCertificate>
</clientCredentials>
</behavior>
Javascript 1.7 added destructured assignment which allows you to do essentially what you are after.
function getTuple(){
return ["Bob", 24];
}
var [a, b] = getTuple();
// a === "bob" , b === 24 are both true
dovers gives us his great answer and based on it you can try use it like
public static class CellDataFormat
{
public static string General { get { return "General"; } }
public static string Number { get { return "0"; } }
// Your custom format
public static string NumberDotTwoDigits { get { return "0.00"; } }
public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
public static string Date { get { return "m/d/yy"; } }
public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
public static string Percentage { get { return "0.00%"; } }
public static string Fraction { get { return "# ?/?"; } }
public static string Scientific { get { return "0.00E+00"; } }
public static string Text { get { return "@"; } }
public static string Special { get { return ";;"; } }
public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
I think the easiest way to match the characters like
\^$.?*|+()[
are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:
> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\
to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp
to see more info about this.
https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf
You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.
The map function is used to map one value to another, but it looks you actually want to filter the array, which a map function is not suitable for.
What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.
var arr = ['a','b',1];
var results = arr.filter(function(item){
return typeof item ==='string';
});
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me...
I would suggest:
SELECT DAY(EOMONTH(GETDATE()))
The particular .js file was in the sub folder (/src) of the application and Terminal was in general App folder.(which contains all package files,modules,public folder,src folder) it was throwing that error.Going to (/src) of application resolved my issue.
In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:
element.classList.contains('your-class-name')
Try this condition instead:
if (string.IsNullOrWhiteSpace(MaterialTextBox.Text)) {
// Message box
}
This will take care of some strings that only contain whitespace characters and you won't have to deal with string equality which can sometimes be tricky
Function expressions in the JSON are completely possible, just do not forget to wrap it in double quotes. Here is an example taken from noSQL database design:
{_x000D_
"_id": "_design/testdb",_x000D_
"views": {_x000D_
"byName": {_x000D_
"map": "function(doc){if(doc.name){emit(doc.name,doc.code)}}"_x000D_
}_x000D_
}_x000D_
}
_x000D_
Do keep in mind that the file.getContentType
could also output application/octet-stream instead of the required application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when you try to upload the file that is already open.
None of the answers worked for me since they all paused until a new line was encountered. I wrote a simple helper:
def print_no_newline(string):
import sys
sys.stdout.write(string)
sys.stdout.flush()
To test it:
import time
print_no_newline('hello ')
# Simulate a long task
time.sleep(2)
print('world')
"hello " will first print out and flush to the screen before the sleep. After that you can use standard print.
SOLUTION:
1- delete from "$HOME/.ssh/known_hosts" the line referring to the host towards which is impossible to connect.
2- execute this command: ssh-keygen -R "IP_ADDRESSorHOSTNAME" (substitute "IP_ADDRESSorHOSTNAME" with your destination ip or destination hostname)
3- Retry ssh connection (if it fails please check permission on .ssh directory, it has to be 700)
This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.
UPDATE: The way to get url formed outside of the page itself is well described in answers above.
Or you could do a oneliner like following:
new UrlHelper(actionExecutingContext.RequestContext).Action(
"SessionTimeout", "Home",
new {area = string.Empty},
actionExecutingContext.Request.Url!= null?
actionExecutingContext.Request.Url.Scheme : "http"
);
from filter or:
new UrlHelper(this.Request.RequestContext).Action(
"Details",
"Journey",
new { area = productType },
this.Request.Url!= null? this.Request.Url.Scheme : "http"
);
However quite often one needs to get the url of current page, for those cases using Html.Action
and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.
One way is to use JavaScript to get URL is window.location.href
another - document.URL
In my case, spring threw this because i forgot to make an inner class static.
When you found that it doesnt help even adding a no-arg constructor, please check your modifier.
As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce
in the global namespace.
A quick implementation might look like this:
from contextlib import contextmanager
@contextmanager
def noiters(*funcs):
if not funcs:
funcs = [map, filter, zip] # etc
from functools import reduce
globals()[reduce.__name__] = reduce
for func in funcs:
globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
try:
yield
finally:
del globals()[reduce.__name__]
for func in funcs: globals()[func.__name__] = func
With a usage that looks like this:
with noiters(map):
from operator import add
print(reduce(add, range(1, 20)))
print(map(int, ['1', '2']))
Which prints:
190
[1, 2]
Just my 2 cents :-)
A valid reason for wanting to free memory from any programm (java or not ) is to make more memory available to other programms on operating system level. If my java application is using 250MB I may want to force it down to 1MB and make the 249MB available to other apps.
If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:
$ date; sha1sum reallybigfile.txt; date
Which will result in the following output:
Tue Jun 2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0 reallybigfile.txt
Tue Jun 2 21:33:54 PDT 2015
Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.
If you are using custom TableViewCells, the generic
[self.tableView reloadData];
does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.
To successfully reload your first table view cell without switching views, use the following code:
//For iOS 5 and later
- (void)reloadTopCell {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):
- (void)refresh:(UIRefreshControl *)refreshControl {
//call to the method which will perform the function
[self reloadTopCell];
//finish refreshing
[refreshControl endRefreshing];
}
Now that you have that sorted, inside of your viewDidLoad
add the following:
//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the
[self.tableView reloadData];
to your new refresh method.
If you wish to reload the data every time you switch views, implement the method:
//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
The code below worked for me I used part of the code above inside the button class.
public Button signupB;
public void handleButtonClick (){
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("sceneNotAvailable.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 630, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
}
}
It sounds like something like the below will suit your needs:
With Sheets("Sheet1")
.Rows( X & ":" & .Rows.Count).Delete
End With
Where X is a variable that = the row number ( 415 )
If you are using Netbeans to develop, use jLabel and change it's icon property.
svn status | grep '^M' | sed -e 's/^.//' | xargs rm
svn update
Will remove any file which has been modified. I seem to remember having trouble with revert when files and directories may have been added.
You can type them manually but the editor will assist you.
http://developer.android.com/reference/android/Manifest.permission.html
You can see the snap sot below.
As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.
Behaviour subjects. I wrote a blog about that.
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private noId = new BehaviorSubject<number>(0);
defaultId = this.noId.asObservable();
newId(urlId) {
this.noId.next(urlId);
}
In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.
So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.
For example, I get the id from the URL and update the noid from the behavior subject.
public getId () {
const id = +this.route.snapshot.paramMap.get('id');
return id;
}
ngOnInit(): void {
const id = +this.getId ();
this.taskService.newId(id)
}
And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:
delete(task: Task): void {
//we save the id , cuz after the delete function, we gonna lose it
const oldId = task.id;
this.taskService.deleteTask(task)
.subscribe(task => { //we call the defaultId function from task.service.
this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task
.subscribe(urlId => {
this.urlId = urlId ;
if (oldId == urlId ) {
// Location.call('/home');
this.router.navigate(['/home']);
}
})
})
}
Open IIS manager, select Application Pools, select the application pool you are using, click on Advanced Settings in the right-hand menu. Under General, set "Enable 32-Bit Applications" to "True".
Try this tag. This will refresh the index.html
page every 30 seconds.
<meta http-equiv="refresh" content="30;url=index.html">
is_numeric()
tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.
The preg_match()
example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.
Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.
[EDIT]
As per your comment, a better regular expression might look like this:
/^[1-9][0-9]*$/
This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.
You're not worried about negatives, so that's not an issue.
You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:
/^[1-9][0-9]{0,15}$/
This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.
Hope that helps.
Mainly invalid query strings will give this warning.
Wrong due to a subtle syntax error (misplaced right parenthesis) when using INSTR
function:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active'>0);
Correct:
INSERT INTO users (user_name) SELECT name FROM site_users WHERE
INSTR(status, 'active')>0;
Add an = at the beginning. That makes it a function rather than an entry.
You can make use of java.util.Date instead of Timestamp :
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
routes.rb
get '*unmatched_route', to: 'main#not_found'
main_controller.rb
def not_found
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
git branch --set-upstream <<origin/branch>>
is officially not supported anymore and is replaced by git branch --set-upstream-to <<origin/branch>>
Code below creates Excel File and saves it in D: drive It uses Microsoft office 2007
FIRST ADD REFERRANCE (Microsoft office 12.0 object library ) to your project
Then Add code given bellow to the Export button click event-
Private Sub Export_Button_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles VIEW_Button.Click
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
xlApp = New Microsoft.Office.Interop.Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Next
Next
xlWorkSheet.SaveAs("D:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file D:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)
Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))
/// <summary>
/// <see cref="IUrlHelper"/> extension methods.
/// </summary>
public static class UrlHelperExtensions
{
/// <summary>
/// Generates a fully qualified URL to an action method by using the specified action name, controller name and
/// route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
/// <summary>
/// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
/// virtual (relative) path to an application absolute path.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="contentPath">The content path.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteContent(
this IUrlHelper url,
string contentPath)
{
HttpRequest request = url.ActionContext.HttpContext.Request;
return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
}
/// <summary>
/// Generates a fully qualified URL to the specified route by using the route name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteRouteUrl(
this IUrlHelper url,
string routeName,
object routeValues = null)
{
return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
}
}
You can't directly register an IUrlHelper
in the DI container. Resolving an instance of IUrlHelper
requires you to use the IUrlHelperFactory
and IActionContextAccessor
. However, you can do the following as a shortcut:
services
.AddSingleton<IActionContextAccessor, ActionContextAccessor>()
.AddScoped<IUrlHelper>(x => x
.GetRequiredService<IUrlHelperFactory>()
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));
UPDATE: This won't make ASP.NET Core 5
There are indications that you will be able to use LinkGenerator
to create absolute URL's without the need to provide a HttpContext
(This was the biggest downside of LinkGenerator
and why IUrlHelper
although more complex to setup using the solution below was easier to use) See "Make it easy to configure a host/scheme for absolute URLs with LinkGenerator".
I determined that this problem was a corrupt connection manager by identifying the specific connection that was failing. I'm working in SQL Server 2016 and I have created the SSISDB catalog and I am deploying my projects there.
Here's the short answer. Delete the connection manager and then re-create it with the same name. Make sure the packages using that connection are still wired up correctly and you should be good to go. If you're not sure how to do that, I've included the detailed procedure below.
To identify the corrupt connection, I did the following. In SSMS, I opened the Integration Services Catalogs folder, then the SSISDB folder, then the folder for my solution, and on down until I found my list of packages for that project.
By right clicking the package that failed, going to reports>standard reports>all executions, selecting the last execution, and viewing the "All Messages" report I was able to isolate which connection was failing. In my case, the connection manager to my destination. I simply deleted the connection manager and then recreated a new connection manager with the same name.
Subsequently, I went into my package, opened the data flow, found that some of my destinations had lit up with the red X. I opened the destination, re-selected the correct connection name, re-selected the target table, and checked the mappings were still correct. I had six destinations and only three had the red X but I clicked all of them and made sure they were still configured correctly.
While promises and callbacks work fine in many situations, it is a pain in the rear to express something like:
if (!name) {
name = async1();
}
async2(name);
You'd end up going through async1
; check if name
is undefined or not and call the callback accordingly.
async1(name, callback) {
if (name)
callback(name)
else {
doSomething(callback)
}
}
async1(name, async2)
While it is okay in small examples it gets annoying when you have a lot of similar cases and error handling involved.
Fibers
helps in solving the issue.
var Fiber = require('fibers')
function async1(container) {
var current = Fiber.current
var result
doSomething(function(name) {
result = name
fiber.run()
})
Fiber.yield()
return result
}
Fiber(function() {
var name
if (!name) {
name = async1()
}
async2(name)
// Make any number of async calls from here
}
You can checkout the project here.
Try This,
public View getView(final int position, View convertView,ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
}
Button Button1= (Button) convertView .findViewById(R.id.BUTTON1_ID);
Button1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Your code that you want to execute on this button click
}
});
return convertView ;
}
It may help you....
According to the docs, you can just do:
select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from USER_INDEXES
or
select INDEX_NAME, TABLE_OWNER, TABLE_NAME, UNIQUENESS from ALL_INDEXES
if you want all indexes...
Also, in your html, remember to delete all blanks / line feeds / tabs between the closing tag and the opening tag.
<img src='a.png' /> <img src='b.png' />
will always display a space between the images even if the border attribute is set to 0, whereas <img src='a.png' /><img src='b.png' />
will not.
Lets say your HTML looks something like this:
<div class="box">
<!-- stuff -->
<p class="bet_time">Bet 5 days ago</p>
</div>
Then, with CSS, you can make that text appear in the bottom right like so:
.box {
position:relative;
}
.bet_time {
position:absolute;
bottom:0;
right:0;
}
The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time
positions its right edge to the right edge of .box
and its bottom edge to the bottom edge of .box
If your terminal supports it, you can use ANSI escape codes to use color in your output. It generally works for Unix shell prompts; however, it doesn't work for Windows Command Prompt (Although, it does work for Cygwin). For example, you could define constants like these for the colors:
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
Then, you could reference those as necessary.
For example, using the above constants, you could make the following red text output on supported terminals:
System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);
Update: You might want to check out the Jansi library. It provides an API and has support for Windows using JNI. I haven't tried it yet; however, it looks promising.
Update 2: Also, if you wish to change the background color of the text to a different color, you could try the following as well:
public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";
For instance:
System.out.println(ANSI_GREEN_BACKGROUND + "This text has a green background but default text!" + ANSI_RESET);
System.out.println(ANSI_RED + "This text has red text but a default background!" + ANSI_RESET);
System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET);
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
This can be scripted in PL/SQL pretty simply based on the DBA/ALL/USER_CONSTRAINTS system view, but various details make not as trivial as it sounds. You have to be careful about the order in which it is done and you also have to take account of the presence of unique indexes.
The order is important because you cannot drop a unique or primary key that is referenced by a foreign key, and there could be foreign keys on tables in other schemas that reference primary keys in your own, so unless you have ALTER ANY TABLE privilege then you cannot drop those PKs and UKs. Also you cannot switch a unique index to being a non-unique index so you have to drop it in order to drop the constraint (for this reason it's almost always better to implement unique constraints as a "real" constraint that is supported by a non-unique index).
All of the information you are looking for can be found here and here (thanks Reed Copsey):
From the first link:
Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.
...
The access level for class members and struct members, including nested classes and structs, is private by default.
...
interfaces default to internal access.
...
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
From the second link:
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.
And for nested types:
Members of Default member accessibility ---------- ---------------------------- enum public class private interface public struct private
On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.
I found when I accessed here https://console.cloud.google.com/home/dashboard
Then I got redirected to my active project, which was something like https://console.cloud.google.com/home/dashboard?project={THE_ID_OF_YOUR_PROJECT}
Then right bellow the project info, there was this Manage Options (note: I'm using Portuguese language here "Gerenciar as configurações do projeto" means "Manage project settings")
Then, finally, the delete option ("Excluir Projeto" means Delete Project)
Yep, it was hard
DPI should not be stored in an bitmap image file, as most sources of data for bitmaps render it meaningless.
A bitmap image is stored as pixels. Pixels have no inherent size in any respect. It's only at render time - be it monitor, printer, or automated crossstitching machine - that DPI matters.
A 800x1000 pixel bitmap image, printed at 100 dpi, turns into a nice 8x10" photo. Printed at 200 dpi, the EXACT SAME bitmap image turns into a 4x5" photo.
Capture an image with a digital camera, and what does DPI mean? It's certainly not the size of the area focused onto the CCD imager - that depends on the distance, and with NASA returning images of galaxies that are 100,000 light years across, and 2 million light years apart, in the same field of view, what kind of DPI do you get from THAT information?
Don't fall victim to the idea of the DPI of a bitmap image - it's a mistake. A bitmap image has no physical dimensions (save for a few micrometers of storage space in RAM or hard drive). It's only a displayed image, or a printed image, that has a physical size in inches, or millimeters, or furlongs.
At the present time, Intel graphics chips do not support CUDA. It is possible that, in the nearest future, these chips will support OpenCL (which is a standard that is very similar to CUDA), but this is not guaranteed and their current drivers do not support OpenCL either. (There is an Intel OpenCL SDK available, but, at the present time, it does not give you access to the GPU.)
Newest Intel processors (Sandy Bridge) have a GPU integrated into the CPU core. Your processor may be a previous-generation version, in which case "Intel(HD) graphics" is an independent chip.
UINavigationController
is a subclass of UIViewController
(who knew )!
Therefore, when presenting view controllers embedded in navigation controllers, you're not really presenting the embedded view controllers; you're presenting the navigation controllers! UINavigationController
, as a subclass of UIViewController
, inherits preferredStatusBarStyle
and childForStatusBarStyle
, which you can set as desired.
Any of the following methods should work:
info.plist
, add the following property:
UIUserInterfaceStyle
(aka. "User Interface Style")Override preferredStatusBarStyle
within UINavigationController
preferredStatusBarStyle
(doc) - The preferred status bar style for the view controllerSubclass or extend UINavigationController
class MyNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
.lightContent
}
}
OR
extension UINavigationController {
open override var preferredStatusBarStyle: UIStatusBarStyle {
.lightContent
}
}
Override childForStatusBarStyle
within UINavigationController
childForStatusBarStyle
(doc) - Called when the system needs the view controller to use for determining status bar style"If your container view controller derives its status bar style from one of its child view controllers, [override this property] and return that child view controller. If you return nil or do not override this method, the status bar style for self is used. If the return value from this method changes, call the setNeedsStatusBarAppearanceUpdate() method."
Subclass or extend UINavigationController
class MyNavigationController: UINavigationController {
override var childForStatusBarStyle: UIViewController? {
topViewController
}
}
OR
extension UINavigationController {
open override var childForStatusBarStyle: UIViewController? {
topViewController
}
}
You can return any view controller you'd like above. I recommend one of the following:
topViewController
(of UINavigationController
) (doc) - The view controller at the top of the navigation stackvisibleViewController
(of UINavigationController
) (doc) - The view controller associated with the currently visible view in the navigation interface (hint: this can include "a view controller that was presented modally on top of the navigation controller itself")Note: If you decide to subclass UINavigationController
, remember to apply that class to your nav controllers through the identity inspector in IB.
P.S. This works on iOS 13
I just wanted to add the fix I found for this issue. I'm not sure why this worked. I had the correct version of jstl (1.2) and also the correct version of servlet-api (2.5)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I also had the correct address in my page as suggested in this thread, which is
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
What fixed this issue for me was removing the scope tag from my xml file in the pom for my jstl 1.2 dependency. Again not sure why that fixed it but just in case someone is doing the spring with JPA and Hibernate tutorial on pluralsight and has their pom setup this way, try removing the scope tag and see if that fixes it. Like I said it worked for me.
ffmpeg supports the mov_text
subtitle encoder which is about the only one supported in an MP4 container and playable by iTunes, Quicktime, iOS etc.
Your line would read:
ffmpeg -i input.mp4 -i input.srt -map 0:0 -map 0:1 -map 1:0 -c:s mov_text output.mp4
Where can I download (certified) 64 bit Apache httpd binaries for Windows?
Right now, there are none. The Apache Software Foundation produces Open Source Software. The 32 bit binaries provided are a courtesy of the community members.
Though there are some unofficial e.g. http://www.apachelounge.com/download/win64/, but I have no idea if they can be trusted.
you can add an edit text of size "0 dip" as the first control in ur xml, so, that will get the focus on render.(make sure its focusable and all...)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
i don't use ssl authentication and this jackson-databind contain jackson-core.jar and jackson-databind.jar, and then change the RequestMapping content like this:
@RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public @ResponseBody Customer findCustomer(@PathVariable int number){
Customer result = customerService.findById(number);
return result;
}
attention: if your produces is not "application/json" type and i had not noticed this and got an 406 error, help this can help you out.
Do you have this namespace setup? You will have to ensure that this namespace matches the message namespace. If you can update your question with the xml input and possibly your data object that would be helpful.
[DataContract(Namespace = "http://CompanyName.com.au/ProjectName")]
public class CustomFields
{
// ...
}
This would get you the index of the clicked row, starting with one:
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
<tr>_x000D_
<td>1</td><td>1</td><td>1</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2</td><td>2</td><td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td><td>3</td><td>3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you want to return the number stored in that first cell of each row:
$('#thetable').find('tr').click( function(){
var row = $(this).find('td:first').text();
alert('You clicked ' + row);
});
You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?
Since the version 22.1.0, the class ActionBarActivity
is deprecated. You should use AppCompatActivity
.
Try this command to include the jar:
java -cp yourJarName.jar your.package..your.MainClass
Try this snippet of code:
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
Date now = new Date(System.currentTimeMillis());
Log.d("Date", now.toString());
Make sure to add permission in Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
For Windows we can use
cd
and for Linux
pwd
command is there.
parseInt(value) or parseFloat(value)
This will work nicely.
If you are using a zsh terminal you're able to use wildcard magic:
sed -i "" "s/search/high-replace/g" *.txt
my code is
import { Component } from '@angular/core';
class model {
username : string;
password : string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
username : string;
password : string;
usermodel = new model();
login(){
if(this.usermodel.username == "admin"){
alert("hi");
}else{
alert("bye");
this.usermodel.username = "";
}
}
}
and the html goes like this :
<div class="login">
Usernmae : <input type="text" [(ngModel)]="usermodel.username"/>
Password : <input type="text" [(ngModel)]="usermodel.password"/>
<input type="button" value="Click Me" (click)="login()" />
</div>
Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):
Querying Relationships Using Joins
For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the
From.join
methods on the query root object, or anotherjoin
object. The join methods are similar to theJOIN
keyword in JPQL.The target of the join uses the Metamodel class of type
EntityType<T>
to specify the persistent field or property of the joined entity.The join methods return an object of type
Join<X, Y>
, whereX
is the source entity andY
is the target of the join.Example 23-10 Joining a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Pet, Owner> owner = pet.join(Pet_.owners);
Joins can be chained together to navigate to related entities of the target entity without having to create a
Join<X, Y>
instance for each join.Example 23-11 Chaining Joins Together in a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class); EntityType<Owner> Owner_ = m.entity(Owner.class); Root<Pet> pet = cq.from(Pet.class); Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);
That being said, I have some additional remarks:
First, the following line in your code:
Root entity_ = cq.from(this.baseClass);
Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_
in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.
Second, I really think you should forget this assay_id
foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.
Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.
To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.
Right click on My Computer >> Properties >> Advanced system settings >> System Properties window will get displayed Under Advanced >> Environment Variables
Click on New to set Environment Variables
Variable name: JAVA_HOME Variable value: C:\Program Files\Java\jdk1.8.0_121
Variable name: M2 Variable value: %M2_HOME%\bin
Variable name: M2_HOME Variable value: C:\Program Files\Apache Software Foundation\apache-maven-3.5.0
Variable name: Path Variable value: %M2_HOME%\bin
Then click on Ok, ok, ok. Now restart you command prompt and check again with “mvn –version” to verify the mvn is running, you may restart your system also.
It's Working...... Enjoy :)
Thanks Sandeep Nehte
After following the steps suggested by previous posters, do the following steps:
You should be good to go now.
Try this, this should work,
td input[type="checkbox"] {
float: left;
margin: 0 auto;
width: 100%;
}
After adding the reference, I had to use
Dim fso As New Scripting.FileSystemObject
For sql server (SSMS)
select MAX(LEN(ColumnName)) from table_name
This will returns number of characters.
select MAX(DATALENGTH(ColumnName)) from table_name
This will returns number of bytes used/required.
IF some one use varchar then use DATALENGTH
.More details
On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:
Content-Disposition: attachment; filename=quot.pdf;
See content-disposition on the wikipedia MIME page.
When configuring an console_scripts entrypoint in setup.py I found this issue existed when the endpoint was a module or package rather than a function within the module.
Traceback (most recent call last):
File "/Users/ubuntu/.virtualenvs/virtualenv/bin/mycli", line 11, in <module>
load_entry_point('my-package', 'console_scripts', 'mycli')()
TypeError: 'module' object is not callable
For example
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule]
},
# ...
)
Should have been
from setuptools import setup
setup (
# ...
entry_points = {
'console_scripts': [mycli=package.module.submodule:main]
},
# ...
)
So that it would refer to a callable function rather than the module itself. It seems to make no difference if the module has a if __name__ == '__main__':
block. This will not make the module callable.
As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.
foreach (var tempClass in macroClasses)
{
// using reflection I will be able to run the method as:
tempClass.GetMethod("Run").Invoke(null, null);
}
As the comment points out, you may want to ensure the method is static when calling GetMethod
:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
The other difference between divide and conquer and dynamic programming could be:
Divide and conquer:
Dynamic programming:
Use StadiumBorder
shape
OutlineButton(
onPressed: () {},
child: Text("Follow"),
borderSide: BorderSide(color: Colors.blue),
shape: StadiumBorder(),
)
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
Use the below function for Kotlin:
private fun animateColorValue(view: View) {
val colorAnimation =
ValueAnimator.ofObject(ArgbEvaluator(), Color.GRAY, Color.CYAN)
colorAnimation.duration = 500L
colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
colorAnimation.start()
}
Pass whatever view you want to change color of.
First, you show that it lies in NP at all.
Then you find another problem that you already know is NP complete and show how you polynomially reduce NP Hard problem to your problem.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
Remove all widths set using CSS and set white-space to nowrap like so:
.content-loader tr td {
white-space: nowrap;
}
I would also remove the fixed width from the container (or add overflow-x: scroll
to the container) if you want the fields to display in their entirety without it looking odd...
See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp
I made my own version here : http://androidblogger.blogspot.com/2009/12/how-to-improve-your-application-crash.html
It's basically the same thing, but I'm using a mail rather than a http connexion to send the report, and, more important, I added some informations like application version, OS version, Phone model, or avalaible memory to my report...
That method can't return true
. That's the point of Long.MAX_VALUE
. It would be really confusing if its name were... false. Then it should be just called Long.SOME_FAIRLY_LARGE_VALUE
and have literally zero reasonable uses. Just use Android's isUserAGoat
, or you may roll your own function that always returns false
.
Note that a long
in memory takes a fixed number of bytes. From Oracle:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As you may know from basic computer science or discrete math, there are 2^64 possible values for a long, since it is 64 bits. And as you know from discrete math or number theory or common sense, if there's only finitely many possibilities, one of them has to be the largest. That would be Long.MAX_VALUE
. So you are asking something similar to "is there an integer that's >0 and < 1?" Mathematically nonsensical.
If you actually need this for something for real then use BigInteger
class.
This proc correctly prints out VARCHAR(MAX)
parameter considering wrapping:
CREATE PROCEDURE [dbo].[Print]
@sql varchar(max)
AS
BEGIN
declare
@n int,
@i int = 0,
@s int = 0, -- substring start posotion
@l int; -- substring length
set @n = ceiling(len(@sql) / 8000.0);
while @i < @n
begin
set @l = 8000 - charindex(char(13), reverse(substring(@sql, @s, 8000)));
print substring(@sql, @s, @l);
set @i = @i + 1;
set @s = @s + @l + 2; -- accumulation + CR/LF
end
return 0
END
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
Check out the contents of your array with
echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';
Have a look at nlohmann's JSON Repository on GitHub. I have found that it is the most convenient way to work with JSON.
It is designed to behave just like an STL container, which makes its usage very intuitive.
I know it's tempting to use drag and drop angular modules created by other devs - but actually, unless you are doing something non-standard like dynamically adding / removing rows from the ng-repeated data set by calling $http
services chance are you really don't need a directive based solution, so if you do go this direction you probably just created extra watchers you don't actually need.
What this implementation provides:
The implementation is easy. Just use angular's version of jQuery dom ready from your view's controller:
Inside your controller:
'use strict';
var yourApp = angular.module('yourApp.yourController.controller', []);
yourApp.controller('yourController', ['$scope', '$http', '$q', '$timeout', function ($scope, $http, $q, $timeout) {
$scope.users = [
{
email: '[email protected]',
name: {
first: 'User',
last: 'Last Name'
},
phone: '(416) 555-5555',
permissions: 'Admin'
},
{
email: '[email protected]',
name: {
first: 'First',
last: 'Last'
},
phone: '(514) 222-1111',
permissions: 'User'
}
];
angular.element(document).ready( function () {
dTable = $('#user_table')
dTable.DataTable();
});
}]);
Now in your html view can do:
<div class="table table-data clear-both" data-ng-show="viewState === possibleStates[0]">
<table id="user_table" class="users list dtable">
<thead>
<tr>
<th>E-mail</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
<th>Permissions</th>
<th class="blank-cell"></th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in users track by $index">
<td>{{ user.email }}</td>
<td>{{ user.name.first }}</td>
<td>{{ user.name.last }}</td>
<td>{{ user.phone }}</td>
<td>{{ user.permissions }}</td>
<td class="users controls blank-cell">
<a class="btn pointer" data-ng-click="showEditUser( $index )">Edit</a>
</td>
</tr>
</tbody>
</table>
</div>
For historic reasons, I leave you the links to the last versions of ADT:
linux 64 bit:
http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20140702.ziplinux 32 bit:
http://dl.google.com/android/adt/adt-bundle-linux-x86-20140702.zipMacOS X:
http://dl.google.com/android/adt/adt-bundle-mac-x86_64-20140702.zipWin32:
http://dl.google.com/android/adt/adt-bundle-windows-x86-20140702.zipWin64:
http://dl.google.com/android/adt/adt-bundle-windows-x86_64-20140702.zipAfter that, you can update ADT plugin after 20140702 version. This answer was intended for the ones starting from zero.