I also experienced an issue like this, my workspace was corrupted and didn't do all the important things anymore.
For some reason, I had a corrupt resource on one of my projects. It didn't show up in the package tree, but it did show in the error log in Eclipse as
Error while creating a link for external folder X:\somefolder
After checking every project (because the error didn't point to one), I indeed found this resource in one of the build paths (in Configure Build Path menu it did show an error icon!) and deleted it.
See Eclipse (Kepler) Workspace acting weird (type hierarchy, searching for references not working) for a wider description of my issue if you're experiencing something similar.
Posted this for future developers to reference.
I believe this to be one of the better extension for Visual Studio 2012, it's called Code Compare and can be found here.
If you're looking for a portable C compiled tool:
http://stedolan.github.com/jq/
From the website:
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you’d expect.
Tutorial: http://stedolan.github.com/jq/tutorial/
Manual: http://stedolan.github.com/jq/manual/
Download: http://stedolan.github.com/jq/download/
randojs makes this a little more simple and readable:
console.log( rando(['January', 'February', 'March']).value );
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
To add to the above answer (do steps 1-5).
Try the --force
option. svn help checkout
gives the details.
You should use live method for elements which are rendered later, like colorbox, hidden fields or iframe
$(".inverter-value").live("change",function() {
elem = this
$.ajax({
url: '/main/invertor_attribute/',
type: 'POST',
aysnc: false,
data: {id: $(this).val() },
success: function(data){
// code
},
dataType: 'html'
});
});
Here's another solution using the bin_data()
function from the mltools package.
library(mltools)
# Resulting bins have an equal number of observations in each group
das[, "wt2"] <- bin_data(das$wt, bins=3, binType = "quantile")
# Resulting bins are equally spaced from min to max
das[, "wt3"] <- bin_data(das$wt, bins=3, binType = "explicit")
# Or if you'd rather define the bins yourself
das[, "wt4"] <- bin_data(das$wt, bins=c(-Inf, 250, 322, Inf), binType = "explicit")
das
anim wt wt2 wt3 wt4
1 1 181.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
2 2 179.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
3 3 180.5 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
4 4 201.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
5 5 201.5 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
6 6 245.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
7 7 246.4 [245.466666666667, 394] [179, 250.666666666667) [-Inf, 250)
8 8 189.3 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
9 9 301.0 [245.466666666667, 394] [250.666666666667, 322.333333333333) [250, 322)
10 10 354.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
11 11 369.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
12 12 205.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
13 13 199.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
14 14 394.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
15 15 231.3 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
That is because is does not exist, since it is bounded to Windows.
Use the standard functions from <stdio.h>
instead, such as getc
The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.
Element.scrollHeight
is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow
and height
to auto
, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.
A .jar file is akin to a .exe file. In essence, they are both executable zip files (different zip algorithms).
In a jar file, you will see folders and class files. Each class file is similar to your .o file, and is a compiled java archive.
If you wanted to see the code in a jar file, download a java decompiler (located here: http://java.decompiler.free.fr/?q=jdgui) and a .jar extractor (7zip works fine).
Boostrap has a class for that called navbar-right
. So your code will look as follows:
<ul class="nav navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" href="#" data-toggle="dropdown">Link</a>
<ul class="dropdown-menu">
<li>...</li>
</ul>
</li>
</ul>
None of the above solution work for me. I tried and very frustrated until I watched the following video: https://www.youtube.com/watch?v=tGinfzlp0fE
pip uninstall mysql-connector
work on some computer and it might not work for other computer.
I did the followings:
pip uninstall mysql-connector
pip uninstall mysql-connector-python
pip install mysql-connector-python
In the case of most major browsers, having an input outside of and not connected to any forms whatsoever tricks the browser into thinking there was no submission. In this case, you would have to use pure JS validation for your login and encryption of your passwords would be necessary as well.
Before:
<form action="..."><input type="password"/></form>
After:
<input type="password"/>
Converting our integer value to std::string so we can know how long (how long number of digits).
Then we creating char array length of string letter size +1, so we can copy our value to string then char array.
#include <string>
char* intToStr(int data) {
std::string strData = std::to_string(data);
char* temp = new char[strData.length() + 1];
strcpy(temp, strData.c_str());
return temp;
}
This is a Python solution.
import re
line ="""Subject:
Security ID: S-1-5-21-3368353891-1012177287-890106238-22451
Account Name: ChamaraKer
Account Domain: JIC
Logon ID: 0x1fffb
Object:
Object Server: Security
Object Type: File
Object Name: D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
Handle ID: 0x11dc"""
regex = (r'Object Name:\s+(.*)')
match1= re.findall(regex,line)
print (match1)
*** Remote Interpreter Reinitialized ***
>>>
['D:\\ApacheTomcat\x07pache-tomcat-6.0.36\\logs\\localhost.2013-07-01.log']
>>>
The powerful command installs and replaces the last package.
I had a similar problem. I fixed it.
npm install -g @angular/cli@latest
and
npm install --save-dev @angular/cli@latest
Try one of these two methods:
string get_file_string(){
std::ifstream ifs("path_to_file");
return string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
}
string get_file_string2(){
ifstream inFile;
inFile.open("path_to_file");//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
return strStream.str();//str holds the content of the file
}
If you need url, not route name, you do not need to use/require any other classes:
url()->current();
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
One important thing I missed from the tutorials for a while (stolen from http://www.tramontana.co.hu/wix/lesson4.php) which resulted in the "Another version of this product is already installed" errors:
*Small updates mean small changes to one or a few files where the change doesn't warrant changing the product version (major.minor.build). You don't have to change the Product GUID, either. Note that you always have to change the Package GUID when you create a new .msi file that is different from the previous ones in any respect. The Installer keeps track of your installed programs and finds them when the user wants to change or remove the installation using these GUIDs. Using the same GUID for different packages will confuse the Installer.
Minor upgrades denote changes where the product version will already change. Modify the Version attribute of the Product tag. The product will remain the same, so you don't need to change the Product GUID but, of course, get a new Package GUID.
Major upgrades denote significant changes like going from one full version to another. Change everything: Version attribute, Product and Package GUIDs.
Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.
Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.
The answer to my question is at Ansible: best practice for maintaining list of sudoers.
The Ansible playbook code fragment looks like this from my problem:
- name: Make sure we have a 'wheel' group
group:
name: wheel
state: present
- name: Allow 'wheel' group to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
regexp: '^%wheel'
line: '%wheel ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'
- name: Add sudoers users to wheel group
user:
name=deployer
groups=wheel
append=yes
state=present
createhome=yes
- name: Set up authorized keys for the deployer user
authorized_key: user=deployer key="{{item}}"
with_file:
- /home/railsdev/.ssh/id_rsa.pub
And the best part is that the solution is idempotent. It doesn't add the line
%wheel ALL=(ALL) NOPASSWD: ALL
to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.
In my case I had to run php artisan optimize:clear
in order to make everything to work again.
Manage multiple java version in MAC using jenv
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install jenv
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
brew tap homebrew/cask-versions
brew search java
brew install cask java6
jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home
jenv add /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Note:- if you get error like “”ln: /Users//.jenv/versions/oracle64-1.8.0.231: No such file or directory, then run following:-
mkdir -p /Users//.jenv/versions/oracle64-1.8.0.231
jenv rehash
jenv versions
jenv global oracle64-1.8.0.231
jenv local oracle64-1.6.0.65
jenv exec bash
echo $JAVA_HOME
import pandas as pd
df = pd.DataFrame([{'Product': 'Coke', 'Prices': [100,123,101,105,99,94,98]},{'Product': 'Pepsi', 'Prices': [101,104,104,101,99,99,99]}])
print(df)
df = df.assign(Prices=df.Prices.str.split(',')).explode('Prices')
print(df)
Try this in pandas >=0.25 version
On advice from http://for-ref-only.blogspot.de/2012/08/installing-beautifulsoup-for-python-3.html, I used the Windows command prompt with:
C:\Python\Scripts\easy_install c:\Python\BeautifulSoup\beautifulsoup4-4.3.1
where BeautifulSoup\beautifulsoup4-4.3.1 is the downloaded and extracted beautifulsoup4-4.3.1.tar file. It works.
tf.nn.softmax
computes the forward propagation through a softmax layer. You use it during evaluation of the model when you compute the probabilities that the model outputs.
tf.nn.softmax_cross_entropy_with_logits
computes the cost for a softmax layer. It is only used during training.
The logits are the unnormalized log probabilities output the model (the values output before the softmax normalization is applied to them).
It depends. In a debug build, I want to see the original stack trace with as little effort as possible. In that case, "throw;" fits the bill. In a release build, however, (a) I want to log the error with the original stack trace included, and once that's done, (b) refashion the error handling to make more sense to the user. Here "Throw Exception" makes sense. It's true that rethrowing the error discards the original stack trace, but a non-developer gets nothing out of seeing stack trace information so it's okay to rethrow the error.
void TrySuspectMethod()
{
try
{
SuspectMethod();
}
#if DEBUG
catch
{
//Don't log error, let developer see
//original stack trace easily
throw;
#else
catch (Exception ex)
{
//Log error for developers and then
//throw a error with a user-oriented message
throw new Exception(String.Format
("Dear user, sorry but: {0}", ex.Message));
#endif
}
}
The way the question is worded, pitting "Throw:" vs. "Throw ex;" makes it a bit of a red-herring. The real choice is between "Throw;" and "Throw Exception," where "Throw ex;" is an unlikely special case of "Throw Exception."
When you have many HTML inputs named C[]
what you get in the POST array on the other end is an array of these values in $_POST['C']
. So when you echo
that, you are trying to print an array, so all it does is print Array
and a notice.
To print properly an array, you either loop through it and echo
each element, or you can use print_r
.
Alternatively, if you don't know if it's an array or a string or whatever, you can use var_dump($var)
which will tell you what type it is and what it's content is. Use that for debugging purposes only.
It's a new 'feature' of vagrant. Take a look here: https://github.com/mitchellh/vagrant/issues/3329
They will change the 'Error' to 'Warning'. It's just telling you that the machine isn't booted yet, and it's trying to connect...
It is so much late but this can be helpful for someone. We can use RegEx as bellow.
Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
String[] Fields = CSVParser.Split(Test);
As per the DOM structure you can use below code:
var x = document.getElementById('mySelect');
var txt = "";
var val = "";
for (var i = 0; i < x.length; i++) {
txt +=x[i].text + ",";
val +=x[i].value + ",";
}
The man page makes it pretty clear. If you want to pass two arguments (-rpath
and .
) to the linker you can write
-Wl,-rpath,.
or alternatively
-Wl,-rpath -Wl,.
The arguments -Wl,-rpath .
you suggested do NOT make sense to my mind. How is gcc supposed to know that your second argument (.
) is supposed to be passed to the linker instead of being interpreted normally? The only way it would be able to know that is if it had insider knowledge of all possible linker arguments so it knew that -rpath
required an argument after it.
You can use this sql statement to get the history for any date:
SELECT * FROM V$SQL V where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60
When I debug, I use following to construct the externally callable URL, but you could just use first 2 lines to get your public IP:
public static string ExternalAction(this UrlHelper helper, string actionName, string controllerName = null, RouteValueDictionary routeValues = null, string protocol = null)
{
#if DEBUG
var client = new HttpClient();
var ipAddress = client.GetStringAsync("http://ipecho.net/plain").Result;
// above 2 lines should do it..
var route = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, helper.RouteCollection, helper.RequestContext, true);
if (route == null)
{
return route;
}
if (string.IsNullOrEmpty(protocol) && string.IsNullOrEmpty(ipAddress))
{
return route;
}
var url = HttpContext.Current.Request.Url;
protocol = !string.IsNullOrWhiteSpace(protocol) ? protocol : Uri.UriSchemeHttp;
return string.Concat(protocol, Uri.SchemeDelimiter, ipAddress, route);
#else
helper.Action(action, null, null, HttpContext.Current.Request.Url.Scheme)
#endif
}
Use controller.controller_name
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>
I found pretty useful to use latex syntax on jupyter notebooks cells, like:
![good-boy](https://i.imgur.com/xtoLyW2.jpg "Good boy on boat")
$$\text{This is some centered text}$$
The short answer is that the parent doesn't have a size until the child has a size.
The way layout works in Flutter is that each widget provides constraints to each of its children, like "you can be up to this wide, you must be this tall, you have to be at least this wide", or whatever (specifically, they get a minimum width, a maximum width, a minimum height, and a maximum height). Each child takes those constraints, does something, and picks a size (width and height) that matches those constraints. Then, once each child has done its thing, the widget can can pick its own size.
Some widgets try to be as big as the parent allows. Some widgets try to be as small as the parent allows. Some widgets try to match a certain "natural" size (e.g. text, images).
Some widgets tell their children they can be any size they want. Some give their children the same constraints that they got from their parent.
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
when you are using dependencies so your methods increased! google has a solution for that. that called Multidex!
NOTE: be sure that min SDK is over 14.
in your build.gradle :
android {
defaultConfig {
...
minSdkVersion 15
targetSdkVersion 28
multiDexEnabled true
}
...
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
}
FOR androidX USE :
def multidex_version = "2.0.1"
implementation 'androidx.multidex:multidex:$multidex_version'
For more information please go to the orginal link :
How about RapidXML? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments, computer games, or any other applications where available memory or CPU processing power comes at a premium. RapidXML is licensed under Boost Software License and its source code is freely available.
Features
Limitations
Source: wikipedia.org://Rapidxml
Depending on you use, you may use an XML Data Binding? CodeSynthesis XSD is an XML Data Binding compiler for C++ developed by Code Synthesis and dual-licensed under the GNU GPL and a proprietary license. Given an XML instance specification (XML Schema), it generates C++ classes that represent the given vocabulary as well as parsing and serialization code.
One of the unique features of CodeSynthesis XSD is its support for two different XML Schema to C++ mappings: in-memory C++/Tree and stream-oriented C++/Parser. The C++/Tree mapping is a traditional mapping with a tree-like, in-memory data structure. C++/Parser is a new, SAX-like mapping which represents the information stored in XML instance documents as a hierarchy of vocabulary-specific parsing events. In comparison to C++/Tree, the C++/Parser mapping allows one to handle large XML documents that would not fit in memory, perform stream-oriented processing, or use an existing in-memory representation.
In some cases this is the best way because your code may have change something and j=i+1 won't check that.
for (int i = 0; i < list.size(); i++){
for (int j = 0; j < list.size(); j++) {
if(i == j) {
//to do code here
continue;
}
}
}
The CAST() function does not support the "official" data type "INT" in MySQL, it's not in the list of supported types. With MySQL, "SIGNED" (or "UNSIGNED") could be used instead:
CAST(columnName AS SIGNED)
However, this seems to be MySQL-specific (not standardized), so it may not work with other databases. At least this document (Second Informal Review Draft) ISO/IEC 9075:1992, Database does not list "SIGNED"/"UNSIGNED" in section 4.4 Numbers
.
But DECIMAL is both standardized and supported by MySQL, so the following should work for MySQL (tested) and other databases:
CAST(columnName AS DECIMAL(0))
According to the MySQL docs:
If the scale is 0, DECIMAL values contain no decimal point or fractional part.
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as np import cv2 # Read the image image = cv2.imread( 'digits.png' ) # gray scale conversion gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # We will divide the image # into 5000 small dimensions # of size 20x20 divisions = list (np.hsplit(i, 100 ) for i in np.vsplit(gray_img, 50 )) # Convert into Numpy array # of size (50,100,20,20) NP_array = np.array(divisions) # Preparing train_data # and test_data. # Size will be (2500,20x20) train_data = NP_array[:,: 50 ].reshape( - 1 , 400 ).astype(np.float32) # Size will be (2500,20x20) test_data = NP_array[:, 50 : 100 ].reshape( - 1 , 400 ).astype(np.float32) # Create 10 different labels # for each type of digit k = np.arange( 10 ) train_labels = np.repeat(k, 250 )[:,np.newaxis] test_labels = np.repeat(k, 250 )[:,np.newaxis] # Initiate kNN classifier knn = cv2.ml.KNearest_create() # perform training of data knn.train(train_data, cv2.ml.ROW_SAMPLE, train_labels) # obtain the output from the # classifier by specifying the # number of neighbors. ret, output ,neighbours, distance = knn.findNearest(test_data, k = 3 ) # Check the performance and # accuracy of the classifier. # Compare the output with test_labels # to find out how many are wrong. matched = output = = test_labels correct_OP = np.count_nonzero(matched) #Calculate the accuracy. accuracy = (correct_OP * 100.0 ) / (output.size) # Display accuracy. print (accuracy) |
Output
91.64
Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data
file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF
helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers
.
(Although I didn't understand some of the features at the end)
2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)
I took the below image for my training data:
(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).
To prepare the data for training, I made a small code in OpenCV. It does the following things:
key press manually
. This time we press the digit key ourselves corresponding to the letter in the box..txt
files.At the end of the manual classification of digits, all the digits in the training data (train.png
) are labeled manually by ourselves, image will look like below:
Below is the code I used for the above purpose (of course, not so clean):
import sys
import numpy as np
import cv2
im = cv2.imread('pitrain.png')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ###################
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
samples = np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
cv2.imshow('norm',im)
key = cv2.waitKey(0)
if key == 27: # (escape to quit)
sys.exit()
elif key in keys:
responses.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"
np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)
Now we enter in to training and testing part.
For the testing part, I used the below image, which has the same type of letters I used for the training phase.
For training we do as follows:
.txt
files we already saved earlierFor testing purposes, we do as follows:
I included last two steps (training and testing) in single code below:
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)
And it worked, below is the result I got:
Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.
But anyway, this is a good start to go for beginners (I hope so).
Solution 1: cast
String temp=(String)data.getParameterValue("request");
Solution 2: use typed map:
Map<String, String> param;
So you change Change the return type of your function
public String getParameterValue(String key)
{
if(params.containsKey(key))
{
return params.get(key);
}
return null;
}
and then no need for cast or toString
String temp=data.getParameterValue("request");
Did you see ExpandoObject class?
Directly from MSDN description: "Represents an object whose members can be dynamically added and removed at run time."
With it you can write code like this:
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
((IDictionary<String, Object>)employee).Remove("Name");
Here is how to create a DataFrame where each series is a row.
For a single Series (resulting in a single-row DataFrame):
series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])
For multiple series with identical indices:
cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)
For multiple series with possibly different indices:
list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()
To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose()
. However, the latter approach is inefficient if the columns have different data types.
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
I had the same issue - a .dll working all the time, then my computer crashed and afterwards I had this problem of 'could not load file or assembly ....dll'
Two possible solutions: when the computer crashed there may be some inconsistent files in
C:\Users\<yourUserName>\AppData\Local\Temp\Temporary ASP.NET Files
Deleting that folder, recompiling and the error was gone.
Once I had also to delete my packages folder (I had read that somewhere else). Allow Visual Studio / nuget to install missing packages (or manually reinstall) and afterwards everything was fine again.
Since multi-window mode is available now, your app may not have statusbar on top.
Following solution handle all the cases automatically for you.
android:fitsSystemWindows="true"
or programatically
findViewById(R.id.your_root_view).setFitsSystemWindows(true);
you may also get root view by
findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)
For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177
You might want to look at "JavaScript HTML DOM Events" for a general overview of events:
http://www.w3schools.com/jsref/dom_obj_event.asp
PrimeFaces is built on jQuery, so here's jQuery's "Events" documentation:
http://api.jquery.com/category/events/
http://api.jquery.com/category/events/form-events/
http://api.jquery.com/category/events/keyboard-events/
http://api.jquery.com/category/events/mouse-events/
http://api.jquery.com/category/events/browser-events/
Below, I've listed some of the more common events, with comments about where they can be used (taken from jQuery documentation).
Mouse Events
(Any HTML element can receive these events.)
click
dblclick
mousedown
mousemove
mouseover
mouseout
mouseup
Keyboard Events
(These events can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for these event types.)
keydown
keypress
keyup
Form Events
blur
(In recent browsers, the domain of the event has been extended to include all element types.)
change
(This event is limited to <input>
elements, <textarea>
boxes and <select>
elements.)
focus
(This event is implicitly applicable to a limited set of elements, such as form elements (<input>
, <select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.)
select
(This event is limited to <input type="text">
fields and <textarea>
boxes.)
submit
(It can only be attached to <form>
elements.)
if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId,true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Generally, the system should be handling view controller instantiation with a storyboard. What you want is to traverse the viewController hierarchy by grabbing a reference to the self.window.rootViewController
as opposed to initializing view controllers, which should already be initialized correctly if you've setup your storyboard properly.
So, let's say your rootViewController
is a UINavigationController and then you want to send something to its top view controller, you would do it like this in your AppDelegate's didFinishLaunchingWithOptions
:
UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
MyViewController *myVC = (MyViewController *)nav.topViewController;
myVC.data = self.data;
In Swift if would be very similar:
let nav = self.window.rootViewController as! UINavigationController;
let myVC = nav.topViewController as! MyViewController
myVc.data = self.data
You really shouldn't be initializing view controllers using storyboard id's from the app delegate unless you want to bypass the normal way storyboard is loaded and load the whole storyboard yourself. If you're having to initialize scenes from the AppDelegate you're most likely doing something wrong. I mean imagine you, for some reason, want to send data to a view controller way down the stack, the AppDelegate shouldn't be reaching way into the view controller stack to set data. That's not its business. It's business is the rootViewController. Let the rootViewController handle its own children! So, if I were bypassing the normal storyboard loading process by the system by removing references to it in the info.plist file, I would at most instantiate the rootViewController using instantiateViewControllerWithIdentifier:
, and possibly its root if it is a container, like a UINavigationController. What you want to avoid is instantiating view controllers that have already been instantiated by the storyboard. This is a problem I see a lot. In short, I disagree with the accepted answer. It is incorrect unless the posters means to remove loading of the storyboard from the info.plist since you will have loaded 2 storyboards otherwise, which makes no sense. It's probably not a memory leak because the system initialized the root scene and assigned it to the window, but then you came along and instantiated it again and assigned it again. Your app is off to a pretty bad start!
none of the above answers worked for me. This one did:
=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)
I have solved this if you are using array called for 2 tables. Example you have,
$tableA['yellow']
and $tableA['blue']
. You are getting these 2 values and you want to add another element inside them to separate them by their type
.
foreach ($tableA['yellow'] as $value) {
$value->type = 'YELLOW'; //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
$value->type = 'BLUE'; //you are adding new element named 'type'
}
So, both of the tables value will have new element called type
.
I don't not agree with vipin cp.
The true is that first bit is used for represent the sign. But 1 is for negative and 0 is for positive values. More over negative values are coded in different way (two's complement). Example with TINYINT:
The sign bit
|
1000 0000b = -128d
...
1111 1101b = -3d
1111 1110b = -2d
1111 1111b = -1d
0000 0000b = 0d
0000 0001b = 1d
0000 0010b = 2d
...
0111 1111b = 127d
In my case, I had CUDA already installed from the Ubuntu version and cmake would detect that one instead of the newly installed version using the NVidia SDK Manager.
I ran dpkg -l | grep cuda
and could see both versions.
What I had to do is uninstall the old CUDA (version 9.1 in my case) and leave the new version alone (version 10.2). I used the purge command like so:
sudo apt-get purge libcudart9.1 nvidia-cuda-dev nvidia-cuda-doc \
nvidia-cuda-gdb nvidia-cuda-toolkit
Please verify that the package names match the version you want to remove from your installation.
I had to rerun cmake
from a blank BUILD
directory to redirect all the #include
and libraries to the SDK version (since the old paths were baked in the existing build environment).
This solution really works, try it. Tested in IE8
.dash-overlay{
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#4C000000,endColorstr=#4C000000)";
}
For this true mysql style use this function below: 2019/02/28 15:33:12
function getDateTime() {_x000D_
var now = new Date(); _x000D_
var year = now.getFullYear();_x000D_
var month = now.getMonth()+1; _x000D_
var day = now.getDate();_x000D_
var hour = now.getHours();_x000D_
var minute = now.getMinutes();_x000D_
var second = now.getSeconds(); _x000D_
if(month.toString().length == 1) {_x000D_
month = '0'+month;_x000D_
}_x000D_
if(day.toString().length == 1) {_x000D_
day = '0'+day;_x000D_
} _x000D_
if(hour.toString().length == 1) {_x000D_
hour = '0'+hour;_x000D_
}_x000D_
if(minute.toString().length == 1) {_x000D_
minute = '0'+minute;_x000D_
}_x000D_
if(second.toString().length == 1) {_x000D_
second = '0'+second;_x000D_
} _x000D_
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; _x000D_
return dateTime;_x000D_
}_x000D_
_x000D_
// example usage: realtime clock_x000D_
setInterval(function(){_x000D_
currentTime = getDateTime();_x000D_
document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
}, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
Swift 4 / 5:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)
@objc func checkAction(sender : UITapGestureRecognizer) {
// Do what you want
}
Swift 3:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)
func checkAction(sender : UITapGestureRecognizer) {
// Do what you want
}
Please Try this one.
ImageView imageview1 = findViewById(R.id.imageView1);
imageview1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(YourActivity.this, "Here is your Text",Toast.LENGTH_SHORT).show();
}
});
I think that in this case using polar coordinates is a way of complicate the problem, it would be much easier if you pick random points into a square with sides of length 2R and then select the points (x,y)
such that x^2+y^2<=R^2
.
If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.
For example, this
#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'
will give this:
double quotes gives you sometext
single quotes gives you $MYVAR
Man, check the doc.
for example:
var arr = [ 4, "Pete", 8, "John" ];
console.log(jQuery.inArray( "John", arr ) == 3);
Done as a answer so I can do formatting...
This is the the process you need to go through. Looping through an array for the specifics.
create an empty array
loop through array1, element by element. {
loop through array2, element by element {
if array1.element == array2.element {
add to your new array
}
}
}
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.You don't need to add extra two classes (button button-primary), you just use the child class (button-primary) with css and it will apply parent as well as child css class. Here is the link:
Thanks to Jacob Lichner!
This simple solution posted here Force page refresh on back button worked ...
I've tried to force a page to be downloaded again by browser when user clicks back button, but nothing worked. I appears that modern browsers have separate cache for pages, which stores complete state of a page (including JavaScript generated DOM elements), so when users presses back button, previous page is shown instantly in state the user has left it. If you want to force browser to reload page on back button, add onunload="" to your (X)HTML body element:
<body onunload="">
This disables special cache and forces page reload when user presses back button. Think twice before you use it. Fact of needing such solution is a hint your site navigation concept is flawed.
This works for me in Swift 4 and iOS 11. Most commonly I need to do this when the user taps on a row in a table view and a new view controller is pushed onto the navigation stack. Usually I want the back button to be the name or some attribute of the object represented by the row that was tapped. So I usually do this in didSelectRowAt...
like this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let object = // get the object this row represents
let backButton = UIBarButtonItem()
backButton.title = object.name // or whatever
self.navigationItem.backBarButtonItem = backButton
// now show or segue to the next view controller
}
If you're trying to do stuff with the Java default system keystore (cacerts
), then the default password is changeit
.
You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.
(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)
You want an independent for loop for all the rows in grid view, then refer the below link
http://nikhilsreeni.wordpress.com/asp-net/checkbox/
Select all checkbox in Gridview
CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);
cb.Checked = ((CheckBox)sender).Checked;
}
Select checked rows to a dataset; For gridview multiple edit
CheckBox cb = default(CheckBox);
foreach (GridViewRow row in grdforumcomments.Rows)
{
cb = (CheckBox)row.FindControl("cbsel");
if (cb.Checked)
{
drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
}
}
Just set one up yourself. Copy this snippet to your webserver.
echo "<pre>"; print_r($_POST); echo "</pre>";
Just post what you want to that page. Done.
For a project hosted on GitHub, here's what people usually do:
github.com/
laike9m/
myproject/
mylib/
mylib.go
...
main.go
mylib.go
package mylib
...
main.go
import "github.com/laike9m/myproject/mylib"
...
Code to add audio to video using ffmpeg.
If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};
private void execFFmpegBinaryShortest(final String[] command) {
final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");
String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};
try {
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
System.out.println("on failure----"+s);
}
@Override
public void onSuccess(String s) {
System.out.println("on success-----"+s);
}
@Override
public void onProgress(String s) {
//Log.d(TAG, "Started command : ffmpeg "+command);
System.out.println("Started---"+s);
}
@Override
public void onStart() {
//Log.d(TAG, "Started command : ffmpeg " + command);
System.out.println("Start----");
}
@Override
public void onFinish() {
System.out.println("Finish-----");
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
System.out.println("exceptio :::"+e.getMessage());
}
}
Fiddler is the winner every time when comparing to Charles.
The "customize rules" feature of fiddler is unparalleled in any http debugger. The ability to write code to manipulate http requests and responses on-the-fly is invaluable to me and the work I do in web development.
There are so many features to fiddler that charles just does not have, and likely won't ever have. Fiddler is light-years ahead.
Wanted to comment on the last answer, but without login it’s only possible to make an answer:
To get rid of the "read only error" just stop the device immediately after it’s ready. My script looks as follows:
#!/bin/bash
~/bin/AndroidSdk/tools/emulator @Nexus_6P_API_23 -no-boot-anim &
adb wait-for-device
adb shell stop
adb remount
adb push GmsCore.apk /system/priv-app
adb push GoogleServicesFramework.apk /system/priv-app
adb push GoogleLoginService.apk /system/priv-app
adb push Phonesky.apk /system/priv-app
adb shell start
Another interesting solution where you want to retain the ViewPager while removing the action bar is to have a style as show
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBarOverlay">true</item>
<item name="android:actionBarStyle">@style/NoActionBarStyle</item>
<item name="android:windowContentOverlay">@null</item>
</style>
<style name="NoActionBarStyle" parent="android:Widget.Holo.ActionBar">
<item name="android:backgroundSplit">@null</item>
<item name="android:displayOptions"></item>
</style>
This is the way most of the Dialer applications in android is showing the ViewPager without the action bar.
Ref: https://github.com/CyanogenMod/android_packages_apps_Dialer
Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:
create table foo (
bar int[] default '{}'
);
select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
create index on foo using gin (bar); -- allows to use an index in the above query
But as the prior answer suggests, it will be better to normalize properly.
This is what you're looking for:
List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");
boolean contains = dan.contains(say.getText());
If you have a list of not repeated values, prefer using a Set<String>
which has the same contains method
I had the same problem today.
Bootstrap 4
It's a native functionality: https://getbootstrap.com/docs/4.0/components/navbar/#responsive-behaviors
You have to use .navbar-expand{-sm|-md|-lg|-xl}
classes:
<nav class="navbar navbar-expand-md navbar-light bg-light">
Bootstrap 3
@media (max-width: 991px) {
.navbar-header {
float: none;
}
.navbar-toggle {
display: block;
}
.navbar-collapse {
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
}
.navbar-collapse.collapse {
display: none!important;
}
.navbar-nav {
float: none!important;
margin: 7.5px -15px;
}
.navbar-nav>li {
float: none;
}
.navbar-nav>li>a {
padding-top: 10px;
padding-bottom: 10px;
}
.navbar-text {
float: none;
margin: 15px 0;
}
/* since 3.1.0 */
.navbar-collapse.collapse.in {
display: block!important;
}
.collapsing {
overflow: hidden!important;
}
}
Just change 991px
by 1199px
for md
sizes.
Petr Krampl's answer is the best in my opinion, but more needs to be said about the nature of loops and how to optimize the use of the system. Beginners who happen upon this thread may be further confused by the logical and algorithmic errors in the question and existing answers.
First, let's look at what your code does as you originally wrote it:
while True:
test = 0
if test == 5:
break
test = test - 1
If you say while True
in a loop context, normally your intention is to stay in the loop forever. If that's not your intention, you should consider other options for the structure of the loop. Petr Krampl showed you a perfectly reasonable way to handle this that's much more clear to someone else who may read your code. In addition, it will be more clear to you several months later should you need to revisit your code to add or fix something. Well-written code is part of your documentation. There are usually multiple ways to do things, but that doesn't make all of the ways equally valid in all contexts. while true
is a good example of this especially in this context.
Next, we will look at the algorithmic error in your original code. The very first thing you do in the loop is assign 0 to test
. The very next thing you do is to check if the value of test
is 5, which will never be the case unless you have multiple threads modifying the same memory location. Threading is not in scope for this discussion, but it's worth noting that the code could technically work, but even with multiple threads a lot would be missing, e.g. semaphores. Anyway, you will sit in this loop forever regardless of the fact that the sentinel is forcing an infinite loop.
The statement test = test - 1
is useless regardless of what it does because the variable is reset at the beginning of the next iteration of the loop. Even if you changed it to be test = 5
, the loop would still be infinite because the value is reset each time. If you move the initialization statement outside the loop, then it will at least have a chance to exit. What you may have intended was something like this:
test = 0
while True:
test = test - 1
if test == 5:
break
The order of the statements in the loop depends on the logic of your program. It will work in either order, though, which is the main point.
The next issue is the potential and probable logical error of starting at 0, continually subtracting 1, and then comparing with a positive number. Yes, there are occasions where this may actually be what you intend to do as long as you understand the implications, but this is most likely not what you intended. Newer versions of python will not wrap around when you reach the 'bottom' of the range of an integer like C and various other languages. It will let you continue to subtract 1 until you've filled the available memory on your system or at least what's allocated to your process. Look at the following script and the results:
test = 0
while True:
test -= 1
if test % 100 == 0:
print "Test = %d" % test
if test == 5:
print "Test = 5"
break
which produces this:
Test = -100
Test = -200
Test = -300
Test = -400
...
Test = -21559000
Test = -21559100
Test = -21559200
Test = -21559300
...
The value of test
will never be 5, so this loop will never exit.
To add to Petr Krampl's answer, here's a version that's probably closer to what you actually intended in addition to exiting the loop after a certain period of time:
import time
test = 0
timeout = 300 # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
if test == 5:
break
test -= 1
It still won't break based on the value of test
, but this is a perfectly valid loop with a reasonable initial condition. Further boundary checking could help you to avoid execution of a very long loop for no reason, e.g. check if the value of test is less than 5 upon loop entry, which would immediately break the loop.
One other thing should be mentioned that no other answer has addressed. Sometimes when you loop like this, you may not want to consume the CPU for the entire allotted time. For example, say you are checking the value of something that changes every second. If you don't introduce some kind of delay, you would use every available CPU cycle allotted to your process. That's fine if it's necessary, but good design will allow a lot of programs to run in parallel on your system without overburdening the available resources. A simple sleep statement will free up the vast majority of the CPU cycles allotted to your process so other programs can do work.
The following example isn't very useful, but it does demonstrate the concept. Let's say you want to print something every second. One way to do it would be like this:
import time
tCurrent = time.time()
while True:
if time.time() >= tCurrent + 1:
print "Time = %d" % time.time()
tCurrent = time.time()
The output would be this:
Time = 1498226796
Time = 1498226797
Time = 1498226798
Time = 1498226799
And the process CPU usage would look like this:
That's a huge amount of CPU usage for doing basically no work. This code is much nicer to the rest of the system:
import time
tCurrent = time.time()
while True:
time.sleep(0.25) # sleep for 250 milliseconds
if time.time() >= tCurrent + 1:
print "Time = %d" % time.time()
tCurrent = time.time()
The output is the same:
Time = 1498226796
Time = 1498226797
Time = 1498226798
Time = 1498226799
and the CPU usage is way, way lower:
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php
and pass the serialized form to it so the PHP can read those values. Anything getResult.php
echos will be returned to the JavaScript function in the result
variable back on test.php
and (in this case) shown in an alert box.
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:
spring:
# (DataSourceAutoConfiguration & DataSourceProperties)
datasource:
name: ds-h2
url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
username: h2
password: h2
driver-class: org.h2.Driver
Custom DataSource
@Configuration
@Component
public class DataSourceBean {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
@Primary
public DataSource getDataSource() {
return DataSourceBuilder
.create()
// .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
// .username("h2")
// .password("h2")
// .driverClassName("org.h2.Driver")
.build();
}
}
For the second part of your question, see the array page of the manual, which states (quoting) :
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
And the given example :
<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 is changed,
// $arr1 is still array(2, 3)
$arr3 = &$arr1;
$arr3[] = 4; // now $arr1 and $arr3 are the same
?>
For the first part, the best way to be sure is to try ;-)
Consider this example of code :
function my_func($a) {
$a[] = 30;
}
$arr = array(10, 20);
my_func($arr);
var_dump($arr);
It'll give this output :
array
0 => int 10
1 => int 20
Which indicates the function has not modified the "outside" array that was passed as a parameter : it's passed as a copy, and not a reference.
If you want it passed by reference, you'll have to modify the function, this way :
function my_func(& $a) {
$a[] = 30;
}
And the output will become :
array
0 => int 10
1 => int 20
2 => int 30
As, this time, the array has been passed "by reference".
Don't hesitate to read the References Explained section of the manual : it should answer some of your questions ;-)
The modern (systemctl
) way of doing it:
systemctl is-active nginx
You can use the exit value in your shell scripts as follows:
systemctl -q is-active nginx && echo "It is active, do something"
<?php
$terms = get_the_terms($product->ID, 'product_cat');
foreach ($terms as $term) {
$product_cat = $term->name;
echo $product_cat;
break;
}
?>
As far as I know, currently (Android Studio 2.3) there is no way to do this.
As per Android Studio documentation:
"Note: Only one debugger can be connected to your device at a time."
When you attempt to connect Android Device Monitor it disconnects Android Studio's debug session and vice versa, when you attempt to connect Android Studio's debugger, it disconnects Android Device Monitor.
Fortunately the new version of Android Studio (3.0) will feature a Device File Explorer that will allow you to pull files from within Android Studio without the need to open the Android Device Monitor which should resolve the problem.
Imagine a counter with an initial value of 0
.
For every loop, increment the counter value by 1 using $counter = 0;
The final counter value returned by the loop will be the number of iterations of your for loop. Find the code below:
$counter = 0;
foreach ($Contents as $item) {
$counter++;
$item[number];// if there are 15 $item[number] in this foreach, I want get the value `: 15`
}
Try that.
Use linq and set the data table as Enumerable and select the fields from the data table field that matches what you are looking for.
Example
I want to get the currency Id and currency Name from the currency table where currency is local currency, and assign the currency id and name to a text boxes on the form:
DataTable dt = curData.loadCurrency();
var curId = from c in dt.AsEnumerable()
where c.Field<bool>("LocalCurrency") == true
select c.Field<int>("CURID");
foreach (int cid in curId)
{
txtCURID.Text = cid.ToString();
}
var curName = from c in dt.AsEnumerable()
where c.Field<bool>("LocalCurrency") == true
select c.Field<string>("CurName");
foreach (string cName in curName)
{
txtCurrency.Text = cName.ToString();
}
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
It seems that you catch not the exception you wanna catch out there :)
if the s
is a socket.socket()
object, then the right way to call .connect
would be:
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# originally, it was
# except Exception, e:
# but this syntax is not supported anymore.
except Exception as e:
print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
s.close()
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except
statement for each one of them - this way you'll be able to react differently for different kind of problems.
In my case, everything was working properly then suddenly stopped worked because I think Resharper altered some changes which caused the problem. My project was divided into the data layer, service and presentation layer. I had Entity framework installed and referenced in my data layer but still the error didn't go away. Uninstalling and reinstalling didn't work either. Finally, I solved it by making the data layer the Startup project, making migration, updating the database and changing the Startup project back to my presentation layer.
Try this:
<div style="background:transparent !important" class="jumbotron">
<h1>Welcome!</h1>
<p>We're an awesome company that creates virtual things for portable devices.</p>
<p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
Inline CSS gets preference over classes defined in a .css
file and the classes declared inside <style>
In short, use:
list
- if you require an ordered sequence of items.
dict
- if you require to relate values with keys
set
- if you require to keep unique elements.
A list is a mutable sequence, typically used to store collections of homogeneous items.
A list implements all of the common sequence operations:
x in l
and x not in l
l[i]
, l[i:j]
, l[i:j:k]
len(l)
, min(l)
, max(l)
l.count(x)
l.index(x[, i[, j]])
- index of the 1st occurrence of x
in l
(at or after i
and before j
indeces)A list also implements all of the mutable sequence operations:
l[i] = x
- item i
of l
is replaced by x
l[i:j] = t
- slice of l
from i
to j
is replaced by the contents of the iterable t
del l[i:j]
- same as l[i:j] = []
l[i:j:k] = t
- the elements of l[i:j:k]
are replaced by those of t
del l[i:j:k]
- removes the elements of s[i:j:k]
from the listl.append(x)
- appends x
to the end of the sequence l.clear()
- removes all items from l
(same as del l[:]
)l.copy()
- creates a shallow copy of l
(same as l[:]
)l.extend(t)
or l += t
- extends l
with the contents of t
l *= n
- updates l
with its contents repeated n
timesl.insert(i, x)
- inserts x
into l
at the index given by i
l.pop([i])
- retrieves the item at i
and also removes it from l
l.remove(x)
- remove the first item from l
where l[i]
is equal to xl.reverse()
- reverses the items of l
in placeA list could be used as stack by taking advantage of the methods append
and pop
.
A dictionary maps hashable values to arbitrary objects. A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key.
In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.
A set is an unordered collection of distinct hashable objects. A set is commonly used to include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.
I removed this error by write the following code
Open Terminal
openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt
Now use the server.crt and key.pem file
app.js or server.js file
var https = require('https');
var https_options = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('server.crt', 'utf8')
};
var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);
It works but the certificate is not trusted. You can view the image in image file.
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
Or no float conversion at all by just specifying floats in the list.
l = [-1.2, 0.0, 1]
x = min(l)
or
l = min([-1.2, 0.0, 1])
For database list:
show databases
show dbs
For table/collection list:
show collections
show tables
db.getCollectionNames()
Each jar version has a unique checksum. You can calculate the checksum for you jar (that had no version info) and compare it with the different versions of the jar. We can also search a jar using checksum.
Refer this Question to calculate checksum: What is the best way to calculate a checksum for a file that is on my machine?
I had this problem while trying to mix figures and text. What worked for me was the 'H' option without the '!' option.
\begin{figure}[H]
'H' tries to forces the figure to be exactly where you put it in the code.
This requires you include
\usepackage{float}
The options are explained here
You have to instantiate the object first. The simplest way is:
var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++) {
data.push({label: lab[i], value: val[i]});
}
Or an other, less concise way, but closer to your original code:
for(var i=0; i<4; i++) {
data[i] = {}; // creates a new object
data[i].label = lab[i];
data[i].value = val[i];
}
array()
will not create a new array (unless you defined that function). Either Array()
or new Array()
or just []
.
I recommend to read the MDN JavaScript Guide.
Try this
console.log(moment().format("MM ddd, YYYY HH:mm:ss a"));
console.log(moment().format("MM ddd, YYYY hh:mm:ss a"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)
So you can't do anything about it, it is the issue of the server.
But you could use try .. except
block to handle that exception:
from socket import error as SocketError
import errno
try:
response = urllib2.urlopen(request).read()
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
Make sure the Excel file isn't open.
Give them a default value:
double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
Basically, all possible paths don't initialize these variables.
too good !!! it's working and resolved my one day old problem easily
Dim b1 As Button
Set b1 = ActiveSheet.Buttons("Button 1")
b1.Enabled = False
Okay you must try this guys it works for me:
ping
is available on almost every OS. So you could make a system call and fetch the result.
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode
. $contractorCompanies
contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies)
doesn't escape them because its valid JSON.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
Output buffering is used by PHP to improve performance and to perform a few tricks.
You can have PHP store all output into a buffer and output all of it at once improving network performance.
You can access the buffer content without sending it back to browser in certain situations.
Consider this example:
<?php
ob_start( );
phpinfo( );
$output = ob_get_clean( );
?>
The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.
Consider this example:
<?php
ob_start( );
echo "Hello World";
if ( $some_error )
{
header( "Location: error.php" );
exit( 0 );
}
?>
I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.
With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.
In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder
Examples of jersey Rest client :
Adding dependency :
<!-- jersey -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
ForGetMethod and passing two parameter :
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/AddGroup/"
+ userN + "/" + groupName);
ClientResponse response1 = webResource1.get(ClientResponse.class);
System.out.println("responser is" + response1);
GetMethod passing one parameter and Getting a Respone of List :
Client client = Client.create();
WebResource webResource1 = client
.resource("http://localhost:10102/NewsTickerServices/GetAssignedUser/"+grpName);
//value changed
String response1 = webResource1.type(MediaType.APPLICATION_JSON).get(String.class);
List <String > Assignedlist =new ArrayList<String>();
JSONArray jsonArr2 =new JSONArray(response1);
for (int i =0;i<jsonArr2.length();i++){
Assignedlist.add(jsonArr2.getString(i));
}
In Above It Returns a List which we are accepting as a List and then converting it to Json Array and then Json Array to List .
If Post Request passing Json Object as Parameter :
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:10102/NewsTickerServices/CreateJUser");
// value added
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class,mapper.writeValueAsString(user));
if (response.getStatus() == 500) {
context.addMessage(null, new FacesMessage("User already exist "));
}
private void parseExceptionContents(
final Exception exception,
final OutputStream out)
{
final StackTraceElement[] stackTrace = exception.getStackTrace();
int index = 0;
for (StackTraceElement element : stackTrace)
{
final String exceptionMsg =
"Exception thrown from " + element.getMethodName()
+ " in class " + element.getClassName() + " [on line number "
+ element.getLineNumber() + " of file " + element.getFileName() + "]";
try
{
out.write((headerLine + newLine).getBytes());
out.write((headerTitlePortion + index++ + newLine).getBytes() );
out.write((headerLine + newLine).getBytes());
out.write((exceptionMsg + newLine + newLine).getBytes());
out.write(
("Exception.toString: " + element.toString() + newLine).getBytes());
}
catch (IOException ioEx)
{
System.err.println(
"IOException encountered while trying to write "
+ "StackTraceElement data to provided OutputStream.\n"
+ ioEx.getMessage() );
}
}
}
following script will use to create any kind of file, with user input as extension
import sys
def create():
print("creating new file")
name=raw_input ("enter the name of file:")
extension=raw_input ("enter extension of file:")
try:
name=name+"."+extension
file=open(name,'a')
file.close()
except:
print("error occured")
sys.exit(0)
create()
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer
serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type
header to text/html
if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>
a Content-Type: text/html
would output:
test
whereas Content-Type: text/plain
would output:
<b><i>test</i></b>
TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.
In my opinion, directories should not be considered targets of your makefile, either in technical or in design sense. You should create files and if a file creation needs a new directory then quietly create the directory within the rule for the relevant file.
If you're targeting a usual or "patterned" file, just use make
's internal variable $(@D)
, that means "the directory the current target resides in" (cmp. with $@
for the target). For example,
$(OUT_O_DIR)/%.o: %.cpp
@mkdir -p $(@D)
@$(CC) -c $< -o $@
title: $(OBJS)
Then, you're effectively doing the same: create directories for all $(OBJS)
, but you'll do it in a less complicated way.
The same policy (files are targets, directories never are) is used in various applications. For example, git
revision control system doesn't store directories.
Note: If you're going to use it, it might be useful to introduce a convenience variable and utilize make
's expansion rules.
dir_guard=@mkdir -p $(@D)
$(OUT_O_DIR)/%.o: %.cpp
$(dir_guard)
@$(CC) -c $< -o $@
$(OUT_O_DIR_DEBUG)/%.o: %.cpp
$(dir_guard)
@$(CC) -g -c $< -o $@
title: $(OBJS)
I ran into this exception when try to remove x last items from list.
myList.subList(lastIndex, myList.size()).clear();
was the only solution that worked for me.
The comment states
// Determines what character(s) are used to terminate each line in new files.
// Valid values are 'system' (whatever the OS uses), 'windows' (CRLF) and
// 'unix' (LF only).
You are setting
"default_line_ending": "LF",
You should set
"default_line_ending": "unix",
getElementsByName()
method accesses all elements with the
specified name.
this method returns collection of elements that is an array.getElementsByTagName()
method accesses all elements with the
specified tagname.
this method returns collection of elements that is an array.eg:
<script type="text/javascript">
function getElements() {
var x=document.getElementById("y");
alert(x.value);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
This will return a single HTML element and display the value attribute of it.
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("x");
alert(x.length);
}
</script>
</head>
<body>
<input name="x" id="y" type="text" size="20" /><br />
<input name="x" id="y" type="text" size="20" /><br />
this will return an array of HTML elements and number of elements that match the name attribute.
Extracted from w3schools.
Take a look at this project: http://code.google.com/p/tarlog-plugins/downloads/detail?name=tarlog.eclipse.plugins_1.4.2.jar&can=2&q=
It has some other features, but most importantly, it has Ctrl++ and Ctrl+- to change the font size, it's awesome.
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.
It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
RowCount = RowCount + 1
Next rw
MsgBox (RowCount)
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
Like this:
@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True"},
new SelectListItem{Text="Deactive", Value="False"}},"Select One")
If you want Active to be selected by default then use Selected
property of SelectListItem
:
@Html.DropDownListFor(model => model.Status, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True",Selected=true},
new SelectListItem{Text="Deactive", Value="False"}},"Select One")
If using SelectList
, then you have to use this overload and specify SelectListItem
Value
property which you want to set selected:
@Html.DropDownListFor(model => model.title,
new SelectList(new List<SelectListItem>
{
new SelectListItem { Text = "Active" , Value = "True"},
new SelectListItem { Text = "InActive", Value = "False" }
},
"Value", // property to be set as Value of dropdown item
"Text", // property to be used as text of dropdown item
"True"), // value that should be set selected of dropdown
new { @class = "form-control" })
What i came up with is :
1) Make a position:fixed
<div>
with width:100%
(id=zoomdiv)
2) when the page loads :
zoomlevel=$("#zoomdiv").width()*1.0 / screen.availWidth
And it worked for me for ctrl+
and ctrl-
zooms.
or i can add the line to a $(window).onresize()
event to get the active zoom level
Code:
<script>
var zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
$(window).resize(function(){
zoom=$("#zoomdiv").width()*1.0 / screen.availWidth;
alert(zoom);
});
</script>
<body>
<div id=zoomdiv style="width:100%;position:fixed;"></div>
</body>
P.S. : this is my first post, pardon any mistakes
I recently had to create a solution with a fixed header group and a fixed first column. I split my table into div's and used jquery to capture window scrolling.
http://jsfiddle.net/TinT/EzXub/2346/
var prevTop = 0;
var prevLeft = 0;
$(window).scroll(function(event){
var currentTop = $(this).scrollTop();
var currentLeft = $(this).scrollLeft();
if(prevLeft !== currentLeft) {
prevLeft = currentLeft;
$('.header').css({'left': -$(this).scrollLeft()})
}
if(prevTop !== currentTop) {
prevTop = currentTop;
$('.leftCol').css({'top': -$(this).scrollTop() + 40})
}
});
As a sub form i think it's not gonna Start in the middle of the parent form until you Show it as a Dialog.
..........
Form2.ShowDialog();
i was about to make About Form. and this is perfect that's i am searching for. and untill you close the About_form you cant Touch/click anythings of parents Form once you Click for About_Form (in my case) .Coz its Showing as Dialog
This code:
$monthly_index = array_shift(unpack('H*', date('m/Y')));
Need to be changed into:
$date_time = date('m/Y');
$unpack = unpack('H*', $date_time);
array_shift($unpack);
A simple way can be to split the string on each character and join the parts using space as the delimiter.
Demo:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:
J A Y A R A M
I had through the same situation. I solved using two Promise.All().
I think was really good solution, so I published it on npm: https://www.npmjs.com/package/promise-foreach
I think your code will be something like this
var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
[function (jsonItems){
return new Promise(function(resolve, reject){
if(jsonItems.type === 'file'){
jsonItems.getFile().then(function(file){ //or promise.all?
resolve(file.getSize())
})
}
})
}],
function (result, current) {
return {
type: current.type,
size: jsonItems.result[0]
}
},
function (err, newList) {
if (err) {
console.error(err)
return;
}
console.log('new jsonItems : ', newList)
})
To increase the Heap size in eclipse change the eclipse.ini file.
refer to
http://wiki.eclipse.org/FAQ_How_do_I_increase_the_heap_size_available_to_Eclipse%3F
BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.
The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
[HtmlTargetElement("li", Attributes = "active-when")]
public class LiTagHelper : TagHelper
{
public string ActiveWhen { get; set; }
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContextData { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (ActiveWhen == null)
return;
var targetController = ActiveWhen.Split("/")[1];
var targetAction = ActiveWhen.Split("/")[2];
var currentController = ViewContextData.RouteData.Values["controller"].ToString();
var currentAction = ViewContextData.RouteData.Values["action"].ToString();
if (currentController.Equals(targetController) && currentAction.Equals(targetAction))
{
if (output.Attributes.ContainsName("class"))
{
output.Attributes.SetAttribute("class", $"{output.Attributes["class"].Value} active");
}
else
{
output.Attributes.SetAttribute("class", "active");
}
}
}
}
Include into your _ViewImports.cs:
@addTagHelper *, YourAssemblyName
Usage:
<li active-when="/Home/Index">
In my case the problem was that I started to create an MVC Alloy sample project from scratch in using Visual Studio/Episerver extension and it worked fine when executed using local Visual studio iis express. However by default it points the sql database to LocalDB and when I deployed the site to local IIS it started giving errors some of the initial errors I resolved by: 1.adding the local site url binding to C:/Windows/System32/drivers/etc/hosts 2. Then by editing the application.config found the file location by right clicking on IIS express in botton right corner of the screen when running site using Visual studio and added binding there for local iis url. 3. Finally I was stuck with "unable to access database errors" for which I created a blank new DB in Sql express and changed connection string in web config to point to my new DB and then in package manager console (using Visual Studio) executed Episerver DB commands like - 1. initialize-epidatabase 2. update-epidatabase 3. Convert-EPiDatabaseToUtc
The code in my previous answer can be simplified to:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction)
And if afunction takes arguments, just pass them into assertRaises like this:
def test_afunction_throws_exception(self):
self.assertRaises(ExpectedException, afunction, arg1, arg2)
Although keeping this in mind http://xkcd.com/1179/
In the end I decided to use the format YYYYMMDD
in all CSV files, which doesn't convert to date in Excel, but can be read by all our applications correctly.
According to my perspective, the main difference between script and program:
Scripts can be used with the other technologies. Example: PHP scripts, Javascripts, etc. can be used within HTML.
Programs are stand-alone chunks of code that can never be embedded into the other technologies.
If I am wrong at any place please correct me.I will admire your correction.
Function that will tokenize string into two parts, first word and remaining string.
Return Value: It will have first
and remaining
key in $return
array respectively.
first check strpos( $title," ") !== false
is mandatory in case when string has only one word and no space in it.
function getStringFirstWord( $title ){
$return = [];
if( strpos( $title," ") !== false ) {
$firstWord = strstr($title," ",true);
$remainingTitle = substr(strstr($title," "), 1);
if( !empty( $firstWord ) ) {
$return['first'] = $firstWord;
}
if( !empty( $remainingTitle ) ) {
$return['remaining'] = $remainingTitle;
}
}
else {
$return['first'] = $title;
}
return $return;
}
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
If you want the basic answer to have the files on the left-hand side, just go on "View" then "Tool Buttons", you will then be able to choose "project".
Your post contains several questions, so I'll try to answer them one at a time:
Although the documentation is a little hard to find (likely due to all the name changes), the PA API is very well documented and rather elegant. With a modicum of elbow grease and some previous experience in calling out to web services, you shouldn't have any trouble getting the information you need from the API.
map.setZoom(map.getZoom());
For some reasons, resize
trigger did not work for me, and this one worked.
You need to checkout the branch:
git checkout master
See the Git cheat sheets for more information.
Edit: Please note that git does not manage empty directories, so you'll have to manage them yourself. If your directory is empty, just remove it directly.
inspired by Sammys answer above:
margins = { # vvv margin in inches
"left" : 1.5 / figsize[0],
"bottom" : 0.8 / figsize[1],
"right" : 1 - 0.3 / figsize[0],
"top" : 1 - 1 / figsize[1]
}
fig.subplots_adjust(**margins)
Where figsize is the tuple that you used in fig = pyplot.figure(figsize=...)
Try like this,
jQuery('.leaderMultiSelctdropdown').select2('data');
The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.
I found myself in a similar predicament today while trying to run a command through a Node.js module:
I was using the PowerShell and trying to run:
command -e 'func($a)'
But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:
command -e `"func($a)`"
Android SDK
Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
Cordova requires the ANDROID_HOME
environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk
directory (for example c:\android\android-sdk).
Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME
, you would add both %ANDROID_HOME%\tools
and %ANDROID_HOME%\platform-tools
.
Reference : http://ionicframework.com/docs/v1/guide/installation.html
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
In GNU/Linux you can use this command
/etc/init.d/virtualbox
Options
for example
/etc/init.d/virtualbox force-reload
Good Luck
Try this;
var data = "";
data = "<option value = Some value> Some Option </option>";
options = [];
options.push(data);
select = document.getElementById("drop_down_id");
select.innerHTML = optionsHTML.join('\n');
Let's stick to the solution from the linked question (Changing color scale in seaborn bar plot). You want to use argsort to determine the order of the colors to use for colorizing the bars. In the linked question argsort is applied to a Series object, which works fine, while here you have a DataFrame. So you need to select one column of that DataFrame to apply argsort on.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = sns.load_dataset("tips")
groupedvalues=df.groupby('day').sum().reset_index()
pal = sns.color_palette("Greens_d", len(groupedvalues))
rank = groupedvalues["total_bill"].argsort().argsort()
g=sns.barplot(x='day',y='tip',data=groupedvalues, palette=np.array(pal[::-1])[rank])
for index, row in groupedvalues.iterrows():
g.text(row.name,row.tip, round(row.total_bill,2), color='black', ha="center")
plt.show()
rank()
starts at 1
instead of zero. So one has to subtract 1 from the array. Also for indexing we need integer values, so we need to cast it to int
.
rank = groupedvalues['total_bill'].rank(ascending=True).values
rank = (rank-1).astype(np.int)
int myInt = 65;
char myChar = (char)myInt; // myChar should now be the letter A
char[20] myString = {0}; // make an empty string.
myString[0] = myChar;
myString[1] = myChar; // Now myString is "AA"
This should all be found in any intro to C book, or by some basic online searching.
Try
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).
Finally, the constructor we are passing these iterators into is a string constructor of the form:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial: http://docs.python-guide.org/en/latest/starting/install3/osx/.
To run the program you can then copy and paste in this code:
python /Users/luca/Documents/python/gameover.py
Or you can go to the directory of the file with cd
followed by the folder. When you are in the folder you can then python YourFile.py
.
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Their are two methods you can use to pass an integer. One is as shown below.
A.class
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
B.class
Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);
The other method converts the integer to a string and uses the following code.
A.class
Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);
The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.
B.class
Bundle extras = getIntent().getExtras();
String stringVariableName = extras.getString("StringVariableName");
int intVariableName = Integer.parseInt(stringVariableName);
To somewhat expand on earlier answers, there are a few complications.
telnet
is not particularly scriptable; you might prefer to use nc
(aka netcat
) instead, which handles non-terminal input and signals better.
Also, unlike telnet
, nc
actually allows SSL (and so https
instead of http
traffic -- you need port 443 instead of port 80 then).
There is a difference between HTTP 1.0 and 1.1. The recent version of the protocol requires the Host:
header to be included in the request on a separate line after the POST
or GET
line, and to be followed by an empty line to mark the end of the request headers.
The HTTP protocol requires carriage return / line feed line endings. Many servers are lenient about this, but some are not. You might want to use
printf "%\r\n" \
"GET /questions HTTP/1.1" \
"Host: stackoverflow.com" \
"" |
nc --ssl stackoverflow.com 443
If you fall back to HTTP/1.0 you don't always need the Host:
header, but many modern servers require the header anyway; if multiple sites are hosted on the same IP address, the server doesn't know from GET /foo HTTP/1.0
whether you mean http://site1.example.com/foo
or http://site2.example.net/foo
if those two sites are both hosted on the same server (in the absence of a Host:
header, a HTTP 1.0 server might just default to a different site than the one you want, so you don't get the contents you wanted).
The HTTPS protocol is identical to HTTP in these details; the only real difference is in how the session is set up initially.
Why can't I define a static method in a Java interface?
Actually you can in Java 8.
As per Java doc:
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods
In Java 8 an interface can have default methods and static methods. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.
list.sort(ordering);
instead of
Collections.sort(list, ordering);
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
I am assuming from context and the tags you used that you are writing a .NET C# app. In this case, you can subscribe to the text changed event, and validate each key stroke.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
You are using Python 2 methodology instead of Python 3.
Change:
outfile=open('./immates.csv','wb')
To:
outfile=open('./immates.csv','w')
and you will get a file with the following output:
SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....
In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.
Edited to Add
Here is the code I ran:
url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
list_of_cells=[]
for cell in row.findAll('td'):
list_of_cells.append(cell.text)
list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
To search the whole computer:
gdr -PSProvider 'FileSystem' | %{ ls -r $_.root} 2>$null | where { $_.name -eq "httpd.exe" }
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
In this specific case, note that bash has a variable called PWD
that contains the current directory: $PWD
is equivalent to `pwd`
. (So do other shells, this is a standard feature.) So you can write your script like this:
#!/bin/bash
until [ "$PWD" = "/" ]; do
echo "$PWD"
ls && cd .. && ls
done
Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*
), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo"
and command substitutions "$(foo)"
(unless you specifically know you have not to).
In the general case, as other answers have mentioned already:
var=value
, not var = value
$
means “take the value of this variable”, so you don't use it when assigning: var=value
, not $var=value
For anyone interested in a 16-bit x86 solution, there is a piece of code by JasonKnight here1 (he also includes a signed multiply piece, which I haven't tested). However, that code has issues with large inputs, where the "add bx,bx" part would overflow.
The fixed version:
softwareMultiply:
; INPUT CX,BX
; OUTPUT DX:AX - 32 bits
; CLOBBERS BX,CX,DI
xor ax,ax ; cheap way to zero a reg
mov dx,ax ; 1 clock faster than xor
mov di,cx
or di,bx ; cheap way to test for zero on both regs
jz @done
mov di,ax ; DI used for reg,reg adc
@loop:
shr cx,1 ; divide by two, bottom bit moved to carry flag
jnc @skipAddToResult
add ax,bx
adc dx,di ; reg,reg is faster than reg,imm16
@skipAddToResult:
add bx,bx ; faster than shift or mul
adc di,di
or cx,cx ; fast zero check
jnz @loop
@done:
ret
Or the same in GCC inline assembly:
asm("mov $0,%%ax\n\t"
"mov $0,%%dx\n\t"
"mov %%cx,%%di\n\t"
"or %%bx,%%di\n\t"
"jz done\n\t"
"mov %%ax,%%di\n\t"
"loop:\n\t"
"shr $1,%%cx\n\t"
"jnc skipAddToResult\n\t"
"add %%bx,%%ax\n\t"
"adc %%di,%%dx\n\t"
"skipAddToResult:\n\t"
"add %%bx,%%bx\n\t"
"adc %%di,%%di\n\t"
"or %%cx,%%cx\n\t"
"jnz loop\n\t"
"done:\n\t"
: "=d" (dx), "=a" (ax)
: "b" (bx), "c" (cx)
: "ecx", "edi"
);
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
The working version of your code (from the errors pointed out by BoltClock):
<?php
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
?>
The stray "{" is difficult to see, especially without a decent PHP editor (in my case). So I post the corrected version here.
If your key has a fixed number of digits, you should probably store as text rather than as numeric data. You can use the converters
argument or read_excel
for this.
Or, if this does not work, just manipulate your data once it's read into your dataframe:
df['key_zfill'] = df['key'].astype(str).str.zfill(4)
names key key_zfill
0 abc 5 0005
1 def 4962 4962
2 ghi 300 0300
3 jkl 14 0014
4 mno 20 0020
There is a limit on the number of half-open connections, but afaik not for active connections. Although it appears to depend on the type of Windows 2008 server, at least according to this MSFT employee:
It depends on the edition, Web and Foundation editions have connection limits while Standard, Enterprise, and Datacenter do not.
The input won't have a value if it doesn't exist. Try this...
if($('.input1').val())
You could simply use
return
which does exactly the same as
return None
Your function will also return None
if execution reaches the end of the function body without hitting a return
statement. Returning nothing is the same as returning None
in Python.
I was facing this issue in my angular 5
application today. And the fix which helped me, was simple. I added "moduleResolution": "node"
to the compilerOptions
in the tsconfig.json
file. My complete tsconfig.json
file content is below.
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}
The moduleResolution
specify module resolution strategy. The value of this settings can be node
or classic
. You may read more about this here.
See this related thread. Basically, os.environ
is found on import, and os.getenv
is a wrapper to os.environ.get
, at least in CPython.
EDIT: To respond to a comment, in CPython, os.getenv
is basically a shortcut to os.environ.get
; since os.environ
is loaded at import of os
, and only then, the same holds for
os.getenv
.
use this filter nav_menu_css_class
as shown below
function add_classes_on_li($classes, $item, $args) {
$classes[] = 'nav-item';
return $classes;
}
add_filter('nav_menu_css_class','add_classes_on_li',1,3);
UPDATE
To use this filter with specific menu
if ( 'main-menu' === $args->theme_location ) { //replace main-menu with your menu
$classes[] = "nav-item";
}
To list files based on size in asending order.
find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}' | sort -n\
You could also use the TextBox's On Key Press event handler:
'Keycode for "Enter" is 13
Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
Logincode_Click
End If
End Sub
Textbox1 is an example. Make sure you choose the textbox you want to refer to and also Logincode_Click is an example sub which you call (run) with this code. Make sure you refer to your preferred sub
I was able to invoke a shell script using this command:
ssh ${serverhost} "./sh/checkScript.ksh"
Of course, checkScript.ksh
must exist in the $HOME/sh
directory.
Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:
onmouseover="this.bgColor='white'; this.style.color='black'"
onmouseout="this.bgColor='black'; this.style.color='white'"
It's not entirely clear from your question whether you want a logged x-axis or a logged y-axis. A logged y-axis is not a good idea when using bars because they are anchored at zero, which becomes negative infinity when logged. You can work around this problem by using a frequency polygon or density plot.
The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format
<TextBox Text="{Binding Value, StringFormat={}{0:#,0.0}}"
This is a new feature of C# 6 called an expression bodied member that allows you to define a getter only property using a lambda like function.
While it is considered syntactic sugar for the following, they may not produce identical IL:
public int MaxHealth
{
get
{
return Memory[Address].IsValid
? Memory[Address].Read<int>(Offs.Life.MaxHp)
: 0;
}
}
It turns out that if you compile both versions of the above and compare the IL generated for each you'll see that they are NEARLY the same.
Here is the IL for the classic version in this answer when defined in a class named TestClass
:
.property instance int32 MaxHealth()
{
.get instance int32 TestClass::get_MaxHealth()
}
.method public hidebysig specialname
instance int32 get_MaxHealth () cil managed
{
// Method begins at RVA 0x2458
// Code size 71 (0x47)
.maxstack 2
.locals init (
[0] int32
)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0007: ldarg.0
IL_0008: ldfld int64 TestClass::Address
IL_000d: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_0012: ldfld bool MemoryAddress::IsValid
IL_0017: brtrue.s IL_001c
IL_0019: ldc.i4.0
IL_001a: br.s IL_0042
IL_001c: ldarg.0
IL_001d: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0022: ldarg.0
IL_0023: ldfld int64 TestClass::Address
IL_0028: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_002d: ldarg.0
IL_002e: ldfld class Offs TestClass::Offs
IL_0033: ldfld class Life Offs::Life
IL_0038: ldfld int64 Life::MaxHp
IL_003d: callvirt instance !!0 MemoryAddress::Read<int32>(int64)
IL_0042: stloc.0
IL_0043: br.s IL_0045
IL_0045: ldloc.0
IL_0046: ret
} // end of method TestClass::get_MaxHealth
And here is the IL for the expression bodied member version when defined in a class named TestClass
:
.property instance int32 MaxHealth()
{
.get instance int32 TestClass::get_MaxHealth()
}
.method public hidebysig specialname
instance int32 get_MaxHealth () cil managed
{
// Method begins at RVA 0x2458
// Code size 66 (0x42)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0006: ldarg.0
IL_0007: ldfld int64 TestClass::Address
IL_000c: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_0011: ldfld bool MemoryAddress::IsValid
IL_0016: brtrue.s IL_001b
IL_0018: ldc.i4.0
IL_0019: br.s IL_0041
IL_001b: ldarg.0
IL_001c: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
IL_0021: ldarg.0
IL_0022: ldfld int64 TestClass::Address
IL_0027: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
IL_002c: ldarg.0
IL_002d: ldfld class Offs TestClass::Offs
IL_0032: ldfld class Life Offs::Life
IL_0037: ldfld int64 Life::MaxHp
IL_003c: callvirt instance !!0 MemoryAddress::Read<int32>(int64)
IL_0041: ret
} // end of method TestClass::get_MaxHealth
See https://msdn.microsoft.com/en-us/magazine/dn802602.aspx for more information on this and other new features in C# 6.
See this post Difference between Property and Field in C# 3.0+ on the difference between a field and a property getter in C#.
Update:
Note that expression-bodied members were expanded to include properties, constructors, finalizers and indexers in C# 7.0.
What do I do wrong?
The source code of ToastDisplay is OK (mine is similar and works), but it will only receive something, if it is currently in foreground (you register receiver in onResume). But it can not receive anything if a different activity (in this case SendBroadcast activity) is shown.
Instead you probably want to startActivity ToastDisplay from the first activity?
BroadcastReceiver and Activity make sense in a different use case. In my application I need to receive notifications from a background GPS tracking service and show them in the activity (if the activity is in the foreground).
There is no need to register the receiver in the manifest. It would be even harmful in my use case - my receiver manipulates the UI of the activity and the UI would not be available during onReceive if the activity is not currently shown. Instead I register and unregister the receiver for activity in onResume and onPause as described in BroadcastReceiver documentation:
You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the tag in your AndroidManifest.xml.
This is clean and efficient:
let list = [ 'a', 'b', 'c' ]
(xs => xs[xs.length - 1])(list)
If you install a pipe operator using Babel it becomes:
list |> (xs => xs[xs.length - 1])
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
TypeError: Cannot read property 'then' of undefined when calling a Django service using AngularJS.
If you are calling a Python service, the code will look like below:
this.updateTalentSupplier=function(supplierObj){
var promise = $http({
method: 'POST',
url: bbConfig.BWS+'updateTalentSupplier/',
data:supplierObj,
withCredentials: false,
contentType:'application/json',
dataType:'json'
});
return promise; //Promise is returned
}
We are using MongoDB as the database(I know it doesn't matter. But if someone is searching with MongoDB + Python (Django) + AngularJS the result should come.
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
The constraints are in the standards:
C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators
Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.
C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.
The solution is to use fmod
, which is exactly why the operands of %
are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators:
The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod
To my knowledge, only ENV
allows that, as mentioned in "Environment replacement"
Environment variables (declared with the
ENV
statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.
They have to be environment variables in order to be redeclared in each new containers created for each line of the Dockerfile by docker build
.
In other words, those variables aren't interpreted directly in a Dockerfile, but in a container created for a Dockerfile line, hence the use of environment variable.
This day, I use both ARG
(docker 1.10+, and docker build --build-arg var=value
) and ENV
.
Using ARG
alone means your variable is visible at build time, not at runtime.
My Dockerfile usually has:
ARG var
ENV var=${var}
In your case, ARG
is enough: I use it typically for setting http_proxy variable, that docker build needs for accessing internet at build time.
Additionally,
ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))
Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).
Here is how I do it. You will need to get the namespace URL and the element name from your generated code.
new JAXBElement(new QName("http://www.novell.com/role/service","userDN"),
new String("").getClass(),testDN);
Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.
patchValue
does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue
requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.
In this scenario, we will want to use patchValue, since we are only updating user
and questioning
:
this.qService.editQue([params["id"]]).subscribe(res => {
this.question = res;
this.editqueForm.patchValue({
user: this.question.user,
questioning: this.question.questioning
});
});
EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead
const { user, questioning } = this.question;
this.editqueForm.patchValue({
user,
questioning
});
Ta-dah!