for frequency distribution of a variable with excessive values you can collapse down the values in classes,
Here I excessive values for employrate
variable, and there's no meaning of it's frequency distribution with direct values_count(normalize=True)
country employrate alcconsumption
0 Afghanistan 55.700001 .03
1 Albania 11.000000 7.29
2 Algeria 11.000000 .69
3 Andorra nan 10.17
4 Angola 75.699997 5.57
.. ... ... ...
208 Vietnam 71.000000 3.91
209 West Bank and Gaza 32.000000
210 Yemen, Rep. 39.000000 .2
211 Zambia 61.000000 3.56
212 Zimbabwe 66.800003 4.96
[213 rows x 3 columns]
frequency distribution with values_count(normalize=True)
with no classification,length of result here is 139 (seems meaningless as a frequency distribution):
print(gm["employrate"].value_counts(sort=False,normalize=True))
50.500000 0.005618
61.500000 0.016854
46.000000 0.011236
64.500000 0.005618
63.500000 0.005618
58.599998 0.005618
63.799999 0.011236
63.200001 0.005618
65.599998 0.005618
68.300003 0.005618
Name: employrate, Length: 139, dtype: float64
putting classification we put all values with a certain range ie.
0-10 as 1, 11-20 as 2 21-30 as 3, and so forth.
gm["employrate"]=gm["employrate"].str.strip().dropna()
gm["employrate"]=pd.to_numeric(gm["employrate"])
gm['employrate'] = np.where(
(gm['employrate'] <=10) & (gm['employrate'] > 0) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=20) & (gm['employrate'] > 10) , 1, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=30) & (gm['employrate'] > 20) , 2, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=40) & (gm['employrate'] > 30) , 3, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=50) & (gm['employrate'] > 40) , 4, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=60) & (gm['employrate'] > 50) , 5, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=70) & (gm['employrate'] > 60) , 6, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=80) & (gm['employrate'] > 70) , 7, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=90) & (gm['employrate'] > 80) , 8, gm['employrate']
)
gm['employrate'] = np.where(
(gm['employrate'] <=100) & (gm['employrate'] > 90) , 9, gm['employrate']
)
print(gm["employrate"].value_counts(sort=False,normalize=True))
after classification we have a clear frequency distribution.
here we can easily see, that 37.64%
of countries have employ rate between 51-60%
and 11.79%
of countries have employ rate between 71-80%
5.000000 0.376404
7.000000 0.117978
4.000000 0.179775
6.000000 0.264045
8.000000 0.033708
3.000000 0.028090
Name: employrate, dtype: float64
I know it's been a looong time since the question was made, but I found an easy solution and thought someone could use it (sorry about the poor english). Here it goes:
CSS
.main, .sidebar {
float: none;
padding: 20px;
vertical-align: top;
}
.container {
display: table;
}
.main {
width: 400px;
background-color: LightSlateGrey;
display: table-cell;
}
.sidebar {
width: 200px;
display: table-cell;
background-color: Tomato;
}
HTML
<div class="container clearfix">
<div class="sidebar">
simple text here
</div>
<div class="main">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue, tortor in mattis mattis, arcu erat pharetra orci, at vestibulum lorem ante a felis. Integer sit amet est ac elit vulputate lobortis. Vestibulum in ipsum nulla. Aenean erat elit, lacinia sit amet adipiscing quis, aliquet at erat. Vivamus massa sem, cursus vel semper non, dictum vitae mi. Donec sed bibendum ante.
</div>
</div>
Simple example. Note that you can turn into responsiveness.
To cancel an animation you simply need to set the property that is currently being animated, outside of the UIView animation. That will stop the animation wherever it is, and the UIView will jump to the setting you just defined.
You need to use the command echo $PATH
to display the PATH variable or you can just execute set
or env
to display all of your environment variables.
By typing $PATH
you tried to run your PATH variable contents as a command name.
Bash displayed the contents of your path any way. Based on your output the following directories will be searched in the following order:
/usr/local/share/npm/bin
/Library/Frameworks/Python.framework/Versions/2.7/bin
/usr/local/bin
/usr/local/sbin
~/bin
/Library/Frameworks/Python.framework/Versions/Current/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/opt/X11/bin
/usr/local/git/bin
To me this list appears to be complete.
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
Use
if (Build.VERSION.SDK_INT >= 19) {
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
It should solve the error.
Create a text file with a .reg
extension and the following contents:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
Or download it from the following source:
https://tls1test.salesforce.com/s/NET40-Enable-TLS-1_2.reg
Double-click to install...
Everything is possible (or almost) with css, just use:
display: none; //to hide
display: table-cell //to show
Attempting to provide a concise update, based on Enzero's answer.
Install the Bootstrap.Datepicker package.
PM> install-package Bootstrap.Datepicker
...
Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
//...,
"~/Scripts/bootstrap-datepicker.js",
"~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
...,
"~/Content/bootstrap-datepicker3.css"));
In the related view, in the scripts' section, enable and customize datepicker.
@section scripts{
<script type="text/javascript">
//...
$('.datepicker').datepicker({
format: 'dd/mm/yyyy', //choose the date format you prefer
language: "YOUR-LOCALE-CODE-HERE",
orientation: 'left bottom'
});
</script>
Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:
@Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
if the module userdir is enabled and your site is in a userdir (~/public_html) you must check /etc/apache2/mods-enabled/php5.conf. The following part makes it work (on Ubuntu 14.10 utopic):
# Running PHP scripts in user directories is disabled by default
#
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
# <IfModule mod_userdir.c>
# <Directory /home/*/public_html>
# php_admin_flag engine Off
# </Directory>
# </IfModule>
Please note that this is quite a hard problem, as stated by the accepted answer. I guess it didn't deter the folks at geonames.org though. They have a file a country info file, which doesn't fit whole into this answer - limit is at 30000 chars apparently. There are regexes for about 150 countries.
I extracted the bits relevant to this question here :
AD ^(?:AD)*(\d{3})$
AM ^(\d{6})$
AR ^([A-Z]\d{4}[A-Z]{3})$
AT ^(\d{4})$
AU ^(\d{4})$
AX ^(?:FI)*(\d{5})$
AZ ^(?:AZ)*(\d{4})$
BA ^(\d{5})$
BB ^(?:BB)*(\d{5})$
BD ^(\d{4})$
BE ^(\d{4})$
BG ^(\d{4})$
BH ^(\d{3}\d?)$
BM ^([A-Z]{2}\d{2})$
BN ^([A-Z]{2}\d{4})$
BR ^(\d{8})$
BY ^(\d{6})$
CA ^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]) ?(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$
CH ^(\d{4})$
CL ^(\d{7})$
CN ^(\d{6})$
CR ^(\d{4})$
CU ^(?:CP)*(\d{5})$
CV ^(\d{4})$
CX ^(\d{4})$
CY ^(\d{4})$
CZ ^(\d{5})$
DE ^(\d{5})$
DK ^(\d{4})$
DO ^(\d{5})$
DZ ^(\d{5})$
EC ^([a-zA-Z]\d{4}[a-zA-Z])$
EE ^(\d{5})$
EG ^(\d{5})$
ES ^(\d{5})$
ET ^(\d{4})$
FI ^(?:FI)*(\d{5})$
FM ^(\d{5})$
FO ^(?:FO)*(\d{3})$
FR ^(\d{5})$
GB ^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2})|([A-Z]{2}\d{2}[A-Z]{2})|([A-Z]{2}\d{3}[A-Z]{2})|([A-Z]\d[A-Z]\d[A-Z]{2})|([A-Z]{2}\d[A-Z]\d[A-Z]{2})|(GIR0AA))$
GE ^(\d{4})$
GF ^((97|98)3\d{2})$
GG ^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2})|([A-Z]{2}\d{2}[A-Z]{2})|([A-Z]{2}\d{3}[A-Z]{2})|([A-Z]\d[A-Z]\d[A-Z]{2})|([A-Z]{2}\d[A-Z]\d[A-Z]{2})|(GIR0AA))$
GL ^(\d{4})$
GP ^((97|98)\d{3})$
GR ^(\d{5})$
GT ^(\d{5})$
GU ^(969\d{2})$
GW ^(\d{4})$
HN ^([A-Z]{2}\d{4})$
HR ^(?:HR)*(\d{5})$
HT ^(?:HT)*(\d{4})$
HU ^(\d{4})$
ID ^(\d{5})$
IL ^(\d{5})$
IM ^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2})|([A-Z]{2}\d{2}[A-Z]{2})|([A-Z]{2}\d{3}[A-Z]{2})|([A-Z]\d[A-Z]\d[A-Z]{2})|([A-Z]{2}\d[A-Z]\d[A-Z]{2})|(GIR0AA))$
IN ^(\d{6})$
IQ ^(\d{5})$
IR ^(\d{10})$
IS ^(\d{3})$
IT ^(\d{5})$
JE ^(([A-Z]\d{2}[A-Z]{2})|([A-Z]\d{3}[A-Z]{2})|([A-Z]{2}\d{2}[A-Z]{2})|([A-Z]{2}\d{3}[A-Z]{2})|([A-Z]\d[A-Z]\d[A-Z]{2})|([A-Z]{2}\d[A-Z]\d[A-Z]{2})|(GIR0AA))$
JO ^(\d{5})$
JP ^(\d{7})$
KE ^(\d{5})$
KG ^(\d{6})$
KH ^(\d{5})$
KP ^(\d{6})$
KR ^(?:SEOUL)*(\d{6})$
KW ^(\d{5})$
KZ ^(\d{6})$
LA ^(\d{5})$
LB ^(\d{4}(\d{4})?)$
LI ^(\d{4})$
LK ^(\d{5})$
LR ^(\d{4})$
LS ^(\d{3})$
LT ^(?:LT)*(\d{5})$
LU ^(\d{4})$
LV ^(?:LV)*(\d{4})$
MA ^(\d{5})$
MC ^(\d{5})$
MD ^(?:MD)*(\d{4})$
ME ^(\d{5})$
MG ^(\d{3})$
MK ^(\d{4})$
MM ^(\d{5})$
MN ^(\d{6})$
MQ ^(\d{5})$
MT ^([A-Z]{3}\d{2}\d?)$
MV ^(\d{5})$
MX ^(\d{5})$
MY ^(\d{5})$
MZ ^(\d{4})$
NC ^(\d{5})$
NE ^(\d{4})$
NF ^(\d{4})$
NG ^(\d{6})$
NI ^(\d{7})$
NL ^(\d{4}[A-Z]{2})$
NO ^(\d{4})$
NP ^(\d{5})$
NZ ^(\d{4})$
OM ^(\d{3})$
PF ^((97|98)7\d{2})$
PG ^(\d{3})$
PH ^(\d{4})$
PK ^(\d{5})$
PL ^(\d{5})$
PM ^(97500)$
PR ^(\d{9})$
PT ^(\d{7})$
PW ^(96940)$
PY ^(\d{4})$
RE ^((97|98)(4|7|8)\d{2})$
RO ^(\d{6})$
RS ^(\d{6})$
RU ^(\d{6})$
SA ^(\d{5})$
SD ^(\d{5})$
SE ^(?:SE)*(\d{5})$
SG ^(\d{6})$
SH ^(STHL1ZZ)$
SI ^(?:SI)*(\d{4})$
SK ^(\d{5})$
SM ^(4789\d)$
SN ^(\d{5})$
SO ^([A-Z]{2}\d{5})$
SV ^(?:CP)*(\d{4})$
SZ ^([A-Z]\d{3})$
TC ^(TKCA 1ZZ)$
TH ^(\d{5})$
TJ ^(\d{6})$
TM ^(\d{6})$
TN ^(\d{4})$
TR ^(\d{5})$
TW ^(\d{5})$
UA ^(\d{5})$
US ^\d{5}(-\d{4})?$
UY ^(\d{5})$
UZ ^(\d{6})$
VA ^(\d{5})$
VE ^(\d{4})$
VI ^\d{5}(-\d{4})?$
VN ^(\d{6})$
WF ^(986\d{2})$
YT ^(\d{5})$
ZA ^(\d{4})$
ZM ^(\d{5})$
CS ^(\d{5})$
Hopefully I didn't make any mistake, my regex-fu is pretty weak.
To install the updates, just download the installer from the Nodejs.org site and run it again. The new version of Node.js and NPM will replace the older versions.
This method is cross-platform, works for multiple monitors/screens (targets the active screen), and requires no other libraries than Tk. The root window will appear centered without any unwanted "flashing" or animations:
import tkinter as tk
def get_geometry(frame):
geometry = frame.winfo_geometry()
match = re.match(r'^(\d+)x(\d+)\+(\d+)\+(\d+)$', geometry)
return [int(val) for val in match.group(*range(1, 5))]
def center_window(root):
"""Must be called after application is fully initialized
so that the root window is the true final size."""
# Avoid unwanted "flashing" by making window transparent until fully ready
root.attributes('-alpha', 0)
# Get dimensions of active screen/monitor using fullscreen trick; withdraw
# window before making it fullscreen to preserve previous dimensions
root.withdraw()
root.attributes('-fullscreen', True)
root.update_idletasks()
(screen_width, screen_height, *_) = get_geometry(root)
root.attributes('-fullscreen', False)
# Restore and get "natural" window dimensions
root.deiconify()
root.update_idletasks()
(window_width, window_height, *_) = get_geometry(root)
# Compute and set proper window center
pos_x = round(screen_width / 2 - window_width / 2)
pos_y = round(screen_height / 2 - window_height / 2)
root.geometry(f'+{pos_x}+{pos_y}')
root.update_idletasks()
root.attributes('-alpha', 1)
# Usage:
root = tk.Tk()
center_window(root)
Note that at every point where window geometry is modified, update_idletasks()
must be called to force the operation to occur synchronously/immediately. It uses Python 3 functionality but can easily be adapted to Python 2.x if necessary.
I was building a simple tipCalculator and there was a lot of answers here that seem to overcomplicate the issue. So I found summarizing the issue to be the best way to truly answer this question
if you want to create a rounded decimal number, first you call toFixed(# of decimal places you want to keep)
and then wrap that in a Number()
so end result:
let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip) // 57.29 instead of 57.288
The file is just a file, you need to create an image like so:
var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
var objectUrl = _URL.createObjectURL(file);
img.onload = function () {
alert(this.width + " " + this.height);
_URL.revokeObjectURL(objectUrl);
};
img.src = objectUrl;
}
});
Demo: http://jsfiddle.net/4N6D9/1/
I take it you realize this is only supported in a few browsers. Mostly firefox and chrome, could be opera as well by now.
P.S. The URL.createObjectURL()
method has been removed from the MediaStream
interface. This method has been deprecated in 2013 and superseded by assigning streams to HTMLMediaElement.srcObject
. The old method was removed because it is less safe, requiring a call to URL.revokeOjbectURL()
to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.
For more information, please refer here.
The accepted answer has to be really altered otherwise not working. The getDecimalFormatSymbols makes a defensive copy. Thus,
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));
The new line is this one: formatter.setDecimalFormatSymbols(symbols);
git checkout -b NEW_BRANCH_NAME COMMIT_ID
This will create a new branch called 'NEW_BRANCH_NAME' and check it out.
("check out" means "to switch to the branch")
git branch NEW_BRANCH_NAME COMMIT_ID
This just creates the new branch without checking it out.
in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:
git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Since Jackson 2.0 you can use JsonInclude
@JsonInclude(Include.NON_NULL)
public class Shop {
//...
}
Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.
e.g. I may have a Vehicle
class. A Car
would derive from a Vehicle
, as would a Motorbike
. I can ask each Vehicle
for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars
and Motorbikes
.
In my code I can often just deal with Vehicles
via common methods go()
, stop()
etc. When I add a new Vehicle type later (e.g. Scooter
) the majority of my code would remain oblivious to this fact, and the implementation of Scooter
alone worries about Scooter
particularities.
I would suggest Smoothie Charts.
It's very simple to use, easily and widely configurable, and does a great job of streaming real time data.
There's a builder that lets you explore the options and generate code.
Disclaimer: I am a contributor to the library.
I solved a similar problem I had with scrollbar this way:
First disable vertical scrollbar by setting it's:
overflow-y: hidden;
Then make a div with fixed position with a height equal to the screen height and make it's width thin to look like scrollbar. This div should be vertically scroll-able. Now inside this div make another div with the height of your document (with all it's contents). Now all you need to do is to add an onScroll function to the container div and scroll body as the div scrolls. Here's the code:
HTML:
<div onscroll="OnScroll(this);" style="width:18px; height:100%; overflow-y: auto; position: fixed; top: 0; right: 0;">
<div id="ScrollDiv" style="width:28px; height:100%; overflow-y: auto;">
</div>
</div>
Then in your page load event add this:
JS:
$( document ).ready(function() {
var body = document.body;
var html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
document.getElementById('ScrollDiv').style.height = height + 'px';
});
function OnScroll(Div) {
document.body.scrollTop = Div.scrollTop;
}
Now scrolling the div works just like scrolling the body while body has no scrollbar.
This issue is caused by the pipeline mode in your Application Pool setting that your web site is set to.
Short
Simple way (bad practice) Add the following to your web.config. See http://www.iis.net/ConfigReference/system.webServer/validation
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Long If possible, your best bet is to change your application to support the integrated pipelines. There are a number of changes between IIS6 and IIS7.x that will cause this error. You can find details about these changes here http://learn.iis.net/page.aspx/381/aspnet-20-breaking-changes-on-iis-70/.
If you're unable to do that, you'll need to change the App pool which may be more difficult to do depending on your availability to the web server.
Check http://technet.microsoft.com/en-us/library/cc731755(WS.10).aspx for details on changing the App Pool
If you need to create an App Pool with Classic pipelines, take a look at http://technet.microsoft.com/en-us/library/cc731784(WS.10).aspx
If you don't have access to the server to make this change, you'll need to do this through your hosting server and contact them for help.
Feel free to ask questions.
You can use both the $_SERVER['REQUEST_TIME']
variable or the time()
function. Both of these return a Unix timestamp.
Most of the time these two solutions will yield the exact same Unix Timestamp. The difference between these is that $_SERVER['REQUEST_TIME']
returns the time stamp of the most recent server request and time()
returns the current time. This may create minor differences in accuracy depending on your application, but for most cases both of these solutions should suffice.
Based on your example code above, you are going to want to format this information once you obtain the Unix Timestamp. Unformatted Unix time looks like: 1232659628
So in order to get something that will work, you can use the date()
function to format it.
A good reference for ways to use the date()
function is located in the PHP Manual.
As an example, the following code returns a date that looks like this: 01/22/2009 04:35:00 pm
:
echo date("m/d/Y h:i:s a", time());
Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.
For example, consider the Enumerable.Select
extension method.
This method takes a Func<T, TResult>
instead of any concrete function. This allows it to be used in any context where the above pattern applies.
So for example, say I have a List<Person>
and I want just the name of every person in the list. I can do this:
var names = people.Select(p => p.Name);
Or say I want the age of every person:
var ages = people.Select(p => p.Age);
Right away, you can see how I was able to leverage the same code representing a pattern (with Select
) with two different functions (p => p.Name
and p => p.Age
).
The alternative would be to write a different version of Select
every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:
// Presumably, the code inside these two methods would look almost identical;
// the only difference would be the part that actually selects a value
// based on a Person.
var names = GetPersonNames(people);
var ages = GetPersonAges(people);
With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.
Exit
[construct], and intelisense will tell you which one(s) are valid in a particular place.
If you're more used to using ax
objects to do your plotting, you might find the ax.xaxis.label.set_size()
easier to remember, or at least easier to find using tab in an ipython terminal. It seems to need a redraw operation after to see the effect. For example:
import matplotlib.pyplot as plt
# set up a plot with dummy data
fig, ax = plt.subplots()
x = [0, 1, 2]
y = [0, 3, 9]
ax.plot(x,y)
# title and labels, setting initial sizes
fig.suptitle('test title', fontsize=12)
ax.set_xlabel('xlabel', fontsize=10)
ax.set_ylabel('ylabel', fontsize='medium') # relative to plt.rcParams['font.size']
# setting label sizes after creation
ax.xaxis.label.set_size(20)
plt.draw()
I don't know of a similar way to set the suptitle size after it's created.
For people using a mac. When you're using different host names say test.local and test2.local. Try changing test.local to test.dev. I found out that Mac OS X lion controls the .local tld. So when you change it to something else it's faster.
And of course use above suggestions like turning off the ipv6 reference in your hosts file:
#::1 localhost
and setting this in the hosts file: 127.0.0.1 localhost
so it points to ipv4.
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
Another way to do this is described below.
First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation
. Then set maximum iterations to 1000.
After doing this, use the following formula.
=If(D55="","",IF(C55="",NOW(),C55))
Once anything is typed into cell D55
(for this example) then C55
populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.
This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.
fix json values, it's add \ before u{xxx} to all +" "
$item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
$matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
$matches[2] = preg_replace('/(")/', '"', $matches[2]);
$matches[2] = json_decode('"' . $matches[2] . '"');
return '"' . $matches[1] . '":"' . $matches[2] . '",';
}, $item);
Some awk
version.
awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'
When pattern found, set c=5
If c
is true, print and decrease number of c
I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :
I used unsignedBigInteger('user_id') to define the foreign referenced key.
Schema::create('generals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('general_name');
$table->string('status');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('general_id');
$table->foreign('general_id')->references('id')->on('generals');
$table->string('category_name');
$table->string('status');
$table->timestamps();
});
I hope this helps out.
use
Objective-C
[headingButton setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];
Swift
headingButton.setTitleColor(.black, for: .normal)
This works in MySQL all versions and Amazon RDS Aurora:
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
or
Setting the index column to NULL and then doing the INSERT.
But not in MariaDB, I tested version 10.
That feature is called a common table expression http://msdn.microsoft.com/en-us/library/ms190766.aspx
You won't be able to do the exact thing in mySQL, the easiest thing would to probably make a view that mirrors that CTE and just select from the view. You can do it with subqueries, but that will perform really poorly. If you run into any CTEs that do recursion, I don't know how you'd be able to recreate that without using stored procedures.
EDIT: As I said in my comment, that example you posted has no need for a CTE, so you must have simplified it for the question since it can be just written as
SELECT article.*, userinfo.*, category.* FROM question
INNER JOIN userinfo ON userinfo.user_userid=article.article_ownerid
INNER JOIN category ON article.article_categoryid=category.catid
WHERE article.article_isdeleted = 0
ORDER BY article_date DESC Limit 1, 3
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
dpi -
px - pixel
pt - points
in - inch - with respect to physical screen size(1 inch = 2.54 cm).
mm- milimeter - with respect to physical screen size.
sp - scale-independent pixel.
dip -
In standard, dp and sp are used. sp for font size and dp for everything else.
Formula for conversion of units:
px = dp * ( dpi / 160 );
Density Bucket -> Screen Display => Physical Size => Pixel Size
ldpi -> 120 dpi => 0.5 x 0.5 in => 0.5 in * 120 dpi = 60x60 px
mdpi -> 160 dpi => 0.5 x 0.5 in => 0.5 in * 160 dpi = 80x80 px
hdpi -> 240 dpi => 0.5 x 0.5 in => 0.5 in * 240 dpi = 120x120 px
xhdpi -> 320 dpi => 0.5 x 0.5 in => 0.5 in * 320 dpi = 160x160 px
xxhdpi -> 480 dpi => 0.5 x 0.5 in => 0.5 in * 480 dpi = 240x240 px
xxxhdpi -> 640 dpi => 0.5 x 0.5 in => 0.5 in * 640 dpi = 320x320 px
Rename multiple file extensions:
You want to change ringtone1.mp3
, ringtone2.mp3
to ringtone1.wav
, ringtone2.wav
Here is how to do that: I am in d drive on command prompt (CMD) so I use:
d:\>ren *.* *.wav
This is just an example of file extensions, you can use any type of file extension like WAV, MP3, JPG, GIF, bmp, PDF, DOC, DOCX, TXT this depends on what your operating system.
And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Klaus solution has less overhead, on the other hand this one may be more readable
myDict = {'age': ['12'], 'address': ['34 Main Street, 212 First Avenue'],
'firstName': ['Alan', 'Mary-Ann'], 'lastName': ['Stone', 'Lee']}
def search(myDict, lookup):
for key, value in myDict.items():
for v in value:
if lookup in v:
return key
search(myDict, 'Mary')
You can use iPushPull to push live data direct from an Excel session to the web where you can display it in an IFRAME (or using a WordPress plugin, if applicable). The data in the frame will update whenever the data on the sheet updates.
The iPush(...) in-cell function pushes data from Excel to the web.
This support page describes how to embed your Excel data in your website.
Disclaimer - I work for iPushPull.
This should fix it...
Scanner in=new Scanner(System.in);
int rounds = 0;
while (rounds < 1 || rounds > 3) {
System.out.print("How many rounds? ");
if (in.hasNextInt()) {
rounds = in.nextInt();
} else {
System.out.println("Invalid input. Please try again.");
in.next(); // -->important
System.out.println();
}
// Clear buffer
}
System.out.print(rounds+" rounds.");
When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)
hope it helps
If your compiler supports C++11 standard, there is a constructor inheritance using using
(pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
I got this issue when I accidently tried to update the object instead of save!
I had
if (IsNewSchema(model))
unitOfWork.SchemaRepository.Update(schema);
else
unitOfWork.SchemaRepository.Insert(schema);
when I should of had
if (IsNewSchema(model))
unitOfWork.SchemaRepository.Insert(schema);
else
unitOfWork.SchemaRepository.Update(schema);
That's because your dat1
and dat2
variables are just strings.
You should parse them to get a Date
object, for that format I always use the following function:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
I use this function because the Date.parse(string)
(or new Date(string)
) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.
Use the Make shell
builtin like in MY_VAR=$(shell echo whatever)
me@Zack:~$make
MY_VAR IS whatever
me@Zack:~$ cat Makefile
MY_VAR := $(shell echo whatever)
all:
@echo MY_VAR IS $(MY_VAR)
You could use CAST or CONVERT:
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
The formula for this is very simple, so try this expression,
int num = (int) rand() % (max - min) + min;
//Where rand() returns a random number between 0.0 and 1.0
I did not intend to steal @Jake and @Cornelius's answer, so i tried editing it. but it was rejected.
Anyways, the only improvement I have to point out is about avoiding extra blank column in excel after paste. Adding one line dataGridView1.RowHeadersVisible = false;
hides so called "Row Header" which appears on the left most part of DataGridView, and so it is not selected and copied to clipboard when you do dataGridView1.SelectAll();
private void copyAlltoClipboard()
{
//to remove the first blank column from datagridview
dataGridView1.RowHeadersVisible = false;
dataGridView1.SelectAll();
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
private void button3_Click_1(object sender, EventArgs e)
{
copyAlltoClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
You can append a queryString to your src and change it only when you will release an updated version:
<script src="test.js?v=1"></script>
In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)
Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()
ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
For SourceTextsCellNumber = 0 To UBound(SourceTexts)
TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
Next SourceTextsCellNumber
CreateTextArrayFromSourceTexts = TargetTextArray
End Function
Example:
Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")
Result:
TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"
Enjoy!
Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.
You can just show / hide a gif, but you can also embed that to ajaxSetup, so it's called on every ajax request.
$.ajaxSetup({
beforeSend:function(){
// show gif here, eg:
$("#loading").show();
},
complete:function(){
// hide gif here, eg:
$("#loading").hide();
}
});
One note is that if you want to do an specific ajax request without having the loading spinner, you can do it like this:
$.ajax({
global: false,
// stuff
});
That way the previous $.ajaxSetup we did will not affect the request with global: false
.
More details available at: http://api.jquery.com/jQuery.ajaxSetup
This is a full, single class implementation based on the above excellent answer from Dave Jarvis. The class automatically chooses between the two different supplied algorithms, for maximum efficiency. (This answer is for people who would just like to quickly copy and paste.)
package somepackage
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie;
import org.ahocorasick.trie.Trie.TrieBuilder;
import org.apache.commons.lang3.StringUtils;
/**
* ReplaceStrings, This class is used to replace multiple strings in a section of text, with high
* time efficiency. The chosen algorithms were adapted from: https://stackoverflow.com/a/40836618
*/
public final class ReplaceStrings {
/**
* replace, This replaces multiple strings in a section of text, according to the supplied
* search and replace definitions. For maximum efficiency, this will automatically choose
* between two possible replacement algorithms.
*
* Performance note: If it is known in advance that the source text is long, then this method
* signature has a very small additional performance advantage over the other method signature.
* (Although either method signature will still choose the best algorithm.)
*/
public static String replace(
final String sourceText, final Map<String, String> searchReplaceDefinitions) {
final boolean useLongAlgorithm
= (sourceText.length() > 1000 || searchReplaceDefinitions.size() > 25);
if (useLongAlgorithm) {
// No parameter adaptations are needed for the long algorithm.
return replaceUsing_AhoCorasickAlgorithm(sourceText, searchReplaceDefinitions);
} else {
// Create search and replace arrays, which are needed by the short algorithm.
final ArrayList<String> searchList = new ArrayList<>();
final ArrayList<String> replaceList = new ArrayList<>();
final Set<Map.Entry<String, String>> allEntries = searchReplaceDefinitions.entrySet();
for (Map.Entry<String, String> entry : allEntries) {
searchList.add(entry.getKey());
replaceList.add(entry.getValue());
}
return replaceUsing_StringUtilsAlgorithm(sourceText, searchList, replaceList);
}
}
/**
* replace, This replaces multiple strings in a section of text, according to the supplied
* search strings and replacement strings. For maximum efficiency, this will automatically
* choose between two possible replacement algorithms.
*
* Performance note: If it is known in advance that the source text is short, then this method
* signature has a very small additional performance advantage over the other method signature.
* (Although either method signature will still choose the best algorithm.)
*/
public static String replace(final String sourceText,
final ArrayList<String> searchList, final ArrayList<String> replacementList) {
if (searchList.size() != replacementList.size()) {
throw new RuntimeException("ReplaceStrings.replace(), "
+ "The search list and the replacement list must be the same size.");
}
final boolean useLongAlgorithm = (sourceText.length() > 1000 || searchList.size() > 25);
if (useLongAlgorithm) {
// Create a definitions map, which is needed by the long algorithm.
HashMap<String, String> definitions = new HashMap<>();
final int searchListLength = searchList.size();
for (int index = 0; index < searchListLength; ++index) {
definitions.put(searchList.get(index), replacementList.get(index));
}
return replaceUsing_AhoCorasickAlgorithm(sourceText, definitions);
} else {
// No parameter adaptations are needed for the short algorithm.
return replaceUsing_StringUtilsAlgorithm(sourceText, searchList, replacementList);
}
}
/**
* replaceUsing_StringUtilsAlgorithm, This is a string replacement algorithm that is most
* efficient for sourceText under 1000 characters, and less than 25 search strings.
*/
private static String replaceUsing_StringUtilsAlgorithm(final String sourceText,
final ArrayList<String> searchList, final ArrayList<String> replacementList) {
final String[] searchArray = searchList.toArray(new String[]{});
final String[] replacementArray = replacementList.toArray(new String[]{});
return StringUtils.replaceEach(sourceText, searchArray, replacementArray);
}
/**
* replaceUsing_AhoCorasickAlgorithm, This is a string replacement algorithm that is most
* efficient for sourceText over 1000 characters, or large lists of search strings.
*/
private static String replaceUsing_AhoCorasickAlgorithm(final String sourceText,
final Map<String, String> searchReplaceDefinitions) {
// Create a buffer sufficiently large that re-allocations are minimized.
final StringBuilder sb = new StringBuilder(sourceText.length() << 1);
final TrieBuilder builder = Trie.builder();
builder.onlyWholeWords();
builder.ignoreOverlaps();
for (final String key : searchReplaceDefinitions.keySet()) {
builder.addKeyword(key);
}
final Trie trie = builder.build();
final Collection<Emit> emits = trie.parseText(sourceText);
int prevIndex = 0;
for (final Emit emit : emits) {
final int matchIndex = emit.getStart();
sb.append(sourceText.substring(prevIndex, matchIndex));
sb.append(searchReplaceDefinitions.get(emit.getKeyword()));
prevIndex = emit.getEnd() + 1;
}
// Add the remainder of the string (contains no more matches).
sb.append(sourceText.substring(prevIndex));
return sb.toString();
}
/**
* main, This contains some test and example code.
*/
public static void main(String[] args) {
String shortSource = "The quick brown fox jumped over something. ";
StringBuilder longSourceBuilder = new StringBuilder();
for (int i = 0; i < 50; ++i) {
longSourceBuilder.append(shortSource);
}
String longSource = longSourceBuilder.toString();
HashMap<String, String> searchReplaceMap = new HashMap<>();
ArrayList<String> searchList = new ArrayList<>();
ArrayList<String> replaceList = new ArrayList<>();
searchReplaceMap.put("fox", "grasshopper");
searchReplaceMap.put("something", "the mountain");
searchList.add("fox");
replaceList.add("grasshopper");
searchList.add("something");
replaceList.add("the mountain");
String shortResultUsingArrays = replace(shortSource, searchList, replaceList);
String shortResultUsingMap = replace(shortSource, searchReplaceMap);
String longResultUsingArrays = replace(longSource, searchList, replaceList);
String longResultUsingMap = replace(longSource, searchReplaceMap);
System.out.println(shortResultUsingArrays);
System.out.println("----------------------------------------------");
System.out.println(shortResultUsingMap);
System.out.println("----------------------------------------------");
System.out.println(longResultUsingArrays);
System.out.println("----------------------------------------------");
System.out.println(longResultUsingMap);
System.out.println("----------------------------------------------");
}
}
(Add these to your pom file if needed.)
<!-- Apache Commons utilities. Super commonly used utilities.
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
<!-- ahocorasick, An algorithm used for efficient searching and
replacing of multiple strings.
https://mvnrepository.com/artifact/org.ahocorasick/ahocorasick -->
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>0.4.0</version>
</dependency>
Yep.
// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart). Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Dino.Tools.WebMonitor
{
public class FakeChartForm1 : Form
{
private System.ComponentModel.IContainer components = null;
System.Windows.Forms.DataVisualization.Charting.Chart chart1;
public FakeChartForm1 ()
{
InitializeComponent();
}
private double f(int i)
{
var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
return f1;
}
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
this.chart1.Series.Add(series1);
for (int i=0; i < 100; i++)
{
series1.Points.AddXY(i, f(i));
}
chart1.Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(0, 50);
this.chart1.Name = "chart1";
// this.chart1.Size = new System.Drawing.Size(284, 212);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.chart1);
this.Name = "Form1";
this.Text = "FakeChart";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FakeChartForm1());
}
}
}
UI:
It sounds like you are talking about aggregation. Each instance of your player
class can contain zero or more instances of Airplane
, which, in turn, can contain zero or more instances of Flight
. You can implement this in Python using the built-in list
type to save you naming variables with numbers.
class Flight(object):
def __init__(self, duration):
self.duration = duration
class Airplane(object):
def __init__(self):
self.flights = []
def add_flight(self, duration):
self.flights.append(Flight(duration))
class Player(object):
def __init__ (self, stock = 0, bank = 200000, fuel = 0, total_pax = 0):
self.stock = stock
self.bank = bank
self.fuel = fuel
self.total_pax = total_pax
self.airplanes = []
def add_planes(self):
self.airplanes.append(Airplane())
if __name__ == '__main__':
player = Player()
player.add_planes()
player.airplanes[0].add_flight(5)
You may consider FluentFTP, previously known as System.Net.FtpClient.
It is released under The MIT License and available on NuGet (FluentFTP).
if still not working for you then just close all of your command prompts and then again open and run mongo, mongoimport, mongodb from anywhere it ll work because after setting the path variable command prompt should be restarted.
There is a substring function in XSLT. Example here.
Pidfile contains pid of a process. It is a convention allowing long running processes to be more self-aware. Server process can inspect it to stop itself, or have heuristic that its other instance is already running. Pidfiles can also be used to conventiently kill risk manually, e.g. pkill -F <some.pid>
Always remember when we compare two strings. the comparison happens on chacracter basis. so '2' > '12' is true because the comparison will happen as '2' > '1' and in alphabetical way '2' is always greater than '1' as unicode. SO it will comeout true. I hope this helps.
Cleaning up : Since the post section of a Pipeline is guaranteed to run at the end of a Pipeline’s execution, we can add some notification or other steps to perform finalization, notification, or other end-of-Pipeline tasks.
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
cleanup {
echo 'One way or another, I have finished'
deleteDir() /* clean up our workspace */
}
}
}
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object
and are what you are using, and invoke their base class through super()
, e.g.
class X(object):
def __init__(self, x):
pass
def doit(self, bar):
pass
class Y(X):
def __init__(self):
super(Y, self).__init__(123)
def doit(self, foo):
return super(Y, self).doit(foo)
Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.
For completeness sake, old-style classes call base methods explicitly using the base class, i.e.
def doit(self, foo):
return X.doit(self, foo)
But since you shouldn't be using old-style anymore, I wouldn't care about this too much.
Python 3 only knows about new-style classes (no matter if you derive from object
or not).
Sometimes it takes longer to figure out the regex than to just write it out in python:
import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
s = s.replace(char, ' ')
If you need other characters you can change it to use a white-list or extend your black-list.
Sample white-list:
whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
if char in whitelist:
new_s += char
else:
new_s += ' '
Sample white-list using a generator-expression:
whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)
Classic example "Index in Books"
Consider a "Book" of 1000 pages, divided by 10 Chapters, each section with 100 pages.
Simple, huh?
Now, imagine you want to find a particular Chapter that contains a word "Alchemist". Without an index page, you have no other option than scanning through the entire book/Chapters. i.e: 1000 pages.
This analogy is known as "Full Table Scan" in database world.
But with an index page, you know where to go! And more, to lookup any particular Chapter that matters, you just need to look over the index page, again and again, every time. After finding the matching index you can efficiently jump to that chapter by skipping the rest.
But then, in addition to actual 1000 pages, you will need another ~10 pages to show the indices, so totally 1010 pages.
Thus, the index is a separate section that stores values of indexed column + pointer to the indexed row in a sorted order for efficient look-ups.
Things are simple in schools, isn't it? :P
Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )
eg.
SELECT SQL_NO_CACHE * FROM TABLE
This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
vehicle[] car = new vehicle[N];
An example usage:
>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world
The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.
This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray
:
>>> s = bytearray(1000000) # a million zeroed bytes
>>> t = buffer(s, 1) # slice cuts off the first byte
>>> s[1] = 5 # set the second element in s
>>> t[0] # which is now also the first element in t!
'\x05'
This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.
Note that buffer
has been replaced by the better named memoryview
in Python 3, though you can use either in Python 2.7.
Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.
If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.
<label class="radio control-label">Some label</label>
OR for 'radio inline'
<label class="radio-inline control-label">Some label</label>
Just a note: You might have set up your service differently using the forms interface to add a service installer and project installer. In that case replace where it says serviceInstaller.ServiceName with "name from designer".ServiceName.
You also don't need the private members in this case.
Thanks for the help.
Here's one sample: http://jsfiddle.net/CUUfb/1/
To avoid the compilation error I used
let name1:string = person.name || '';
And then validate the empty string.
Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.
The object where Oracle stores the name of the identifiers (e.g. the table names of the user are stored in the table named as USER_TABLES and the column names of the user are stored in the table named as USER_TAB_COLUMNS), have the NAME columns (e.g. TABLE_NAME in USER_TABLES) of size Varchar2(30)...and it's uniform through all system tables of objects or identifiers --
DBA_ALL_TABLES ALL_ALL_TABLES USER_ALL_TABLES
DBA_PARTIAL_DROP_TABS ALL_PARTIAL_DROP_TABS USER_PARTIAL_DROP_TABS
DBA_PART_TABLES ALL_PART_TABLES USER_PART_TABLES
DBA_TABLES ALL_TABLES USER_TABLES
DBA_TABLESPACES USER_TABLESPACES TAB
DBA_TAB_COLUMNS ALL_TAB_COLUMNS USER_TAB_COLUMNS
DBA_TAB_COLS ALL_TAB_COLS USER_TAB_COLS
DBA_TAB_COMMENTS ALL_TAB_COMMENTS USER_TAB_COMMENTS
DBA_TAB_HISTOGRAMS ALL_TAB_HISTOGRAMS USER_TAB_HISTOGRAMS
DBA_TAB_MODIFICATIONS ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS
DBA_TAB_PARTITIONS ALL_TAB_PARTITIONS USER_TAB_PARTITIONS
encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
And,
I suggest you to learn about system configuration.
How to Show All Categories on System Configuration Field?
Here I solved with a good example. It working. You can check and learn the flow of code.
There are other too many examples also that you should learn.
If value
is a string
in that format and you'd like to convert it into a DateTime
object, you can use DateTime.ParseExact
static method:
DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);
Example:
string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(myDate.ToShortDateString());
Result:
2012-12-01
Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
Why are you using WMI? Can't you use the standard .NET functionality?
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
What I liked in the IDE was that I was able to write a few variables like:
private int id;
private string name;
private string version;
private string description;
private string status;
private string symbol;
Notice, that the variable names start with small letters, and then select the whole block, and press Ctrl+R, Ctrl+E, Apply. The properties are generated with the capital letter:
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
etc.
if you want a procdure to copy a stream to other the one that nick posted is fine but it is missing the position reset, it should be
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
input.Position = TempPos;// or you make Position = 0 to set it at the start
}
but if it is in runtime not using a procedure you shpuld use memory stream
Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
input.Position = TempPos;// or you make Position = 0 to set it at the start
I found this an easy way of cleaning in a shape between the desired row and column. I am not sure if this is what you are looking for. Hope it helps.
Sub sbClearCellsOnlyData()
Range("A1:C10").ClearContents
End Sub
Working with Bjarne Stroustrup Programming Principles and Practice Using C++ "FLTK" example i got the same error but after like 1 hour i got an idea, i tracked one of the libs already seen in Project Properties -> Linker -> Input -> Additional Dependencies, in my case i tracked the kernel32.lib to see where was located and saw there were many kernel32.lib's in different folders. So i started copy the FLTK libs in those folders and the last one i tried worked. Visual Studio 2013 Express found the fltkd.lib and the code worked.
In my case the correct route was C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86
I don't know how to set that route inside Visual Studio.
Not sure if that Windows kits folder was created when i installed Microsoft Windows SDK for Windows 7 and .NET Framework 4 (ISO) http://www.microsoft.com/en-us/download/details.aspx?id=8442
Hope that helps you people.
You're almost correct, just misplaced a few quotes. Wrapping the whole thing in regular quotes will literally give you the string #demo + {this.state.id}
- you need to indicate which are variables and which are string literals. Since anything inside {}
is an inline JSX expression, you can do:
href={"#demo" + this.state.id}
This will use the string literal #demo
and concatenate it to the value of this.state.id
. This can then be applied to all strings. Consider this:
var text = "world";
And this:
{"Hello " + text + " Andrew"}
This will yield:
Hello world Andrew
You can also use ES6 string interpolation/template literals with ` (backticks) and ${expr}
(interpolated expression), which is closer to what you seem to be trying to do:
href={`#demo${this.state.id}`}
This will basically substitute the value of this.state.id
, concatenating it to #demo
. It is equivalent to doing: "#demo" + this.state.id
.
I solved this in my env, without modify hadoop-env.sh
You'd be better using /bin/bash
as default shell not /bin/sh
Check these before:
echo $JAVA_HOME
)echo $SHELL
in every node, check if print /bin/bash
if not, vi /etc/passwd
, add /bin/bash
at tail of your username
ref
ctrl + shift + A => open pop window to select options, select to spaces to convert all tabs as space, or to tab to convert all spaces as tab.
I found a way that seems to work better for me:
ssh-keygen -y -f <private key file>
That command will output the public key for the given private key, so then just compare the output to each *.pub file.
Update:
Since git rm .
deletes all files in this and child directories in the working checkout as well as in the index, you need to undo each of these changes:
git reset HEAD . # This undoes the index changes
git checkout . # This checks out files in this and child directories from the HEAD
This should do what you want. It does not affect parent folders of your checked-out code or index.
Old answer that wasn't:
reset HEAD
will do the trick, and will not erase any uncommitted changes you have made to your files.
after that you need to repeat any git add
commands you had queued up.
Try this:
<SCRIPT LANGUAGE="JavaScript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline("HI");
s.writeline("Bye");
s.writeline("-----------------------------");
s.Close();
}
</SCRIPT>
</head>
<body>
<p>To sign up for the Excel workshop please fill out the form below:
</p>
<form onSubmit="WriteToFile(this)">
Type your first name:
<input type="text" name="FirstName" size="20">
<br>Type your last name:
<input type="text" name="LastName" size="20">
<br>
<input type="submit" value="submit">
</form>
This will work only on IE
You are assigning to a function call:
invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount
which is illegal in Python. The question is, what do you want to do? What does invest()
do? I suppose it returns a value, namely what you're trying to use as subsequent_amount
, right?
If so, then something like this should work:
amount = invest(amount,top_company(5,year,year+1),year)
Debugger for mysql was good but its not free. This is what i use now:
DELIMITER GO$
DROP PROCEDURE IF EXISTS resetLog
GO$
Create Procedure resetLog()
BEGIN
create table if not exists log (ts timestamp default current_timestamp, msg varchar(2048)) engine = myisam;
truncate table log;
END;
GO$
DROP PROCEDURE IF EXISTS doLog
GO$
Create Procedure doLog(in logMsg nvarchar(2048))
BEGIN
insert into log (msg) values(logMsg);
END;
GO$
Usage in stored procedure:
call dolog(concat_ws(': ','@simple_term_taxonomy_id', @simple_term_taxonomy_id));
usage of stored procedure:
call resetLog ();
call stored_proc();
select * from log;
It's for validation purposes.
Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.
Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/
I do this
$u = $_SERVER['HTTP_USER_AGENT'];
$isIE7 = (bool)preg_match('/msie 7./i', $u );
$isIE8 = (bool)preg_match('/msie 8./i', $u );
$isIE9 = (bool)preg_match('/msie 9./i', $u );
$isIE10 = (bool)preg_match('/msie 10./i', $u );
if ($isIE9) {
//do ie9 stuff
}
I had the same error when initializing Spring on startup, using some different library versions, but everything worked when I got my versions in this order in the classpath (the other libraries in the cp were not important):
Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.
There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request
in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:
import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text)
some_elements = soup.find_all("div", class_="myCssClass")
Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.
When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:
from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)
I would advice to start your own solution. You'll understand Scrapy's benefits doing so.
ps: take a look at scrapely: https://github.com/scrapy/scrapely
pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia
Here's how I do it. You could do it the same way, or use this code for ideas.
let s = "www.stackoverflow.com"
s.substringWithRange(0..<s.lastIndexOf("."))
Here are the extensions I use:
import Foundation
extension String {
var length: Int {
get {
return countElements(self)
}
}
func indexOf(target: String) -> Int {
var range = self.rangeOfString(target)
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func indexOf(target: String, startIndex: Int) -> Int {
var startRange = advance(self.startIndex, startIndex)
var range = self.rangeOfString(target, options: NSStringCompareOptions.LiteralSearch, range: Range<String.Index>(start: startRange, end: self.endIndex))
if let range = range {
return distance(self.startIndex, range.startIndex)
} else {
return -1
}
}
func lastIndexOf(target: String) -> Int {
var index = -1
var stepIndex = self.indexOf(target)
while stepIndex > -1 {
index = stepIndex
if stepIndex + target.length < self.length {
stepIndex = indexOf(target, startIndex: stepIndex + target.length)
} else {
stepIndex = -1
}
}
return index
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
}
Credit albertbori / Common Swift String Extensions
Generally I am a strong proponent of extensions, especially for needs like string manipulation, searching, and slicing.
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
==
shouldn't be used to compare objects in your if
. For NSString
use isEqualToString:
to compare them.
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
Anyone looking for running jupyter as sudo, when jupyter installed with virtualenv (without sudo) - this worked for me:
First verify this is a PATH issue:
Check if the path returned by which jupyter
is covered by the sudo user:
sudo env | grep ^PATH
(As opposed to the current user: env | grep ^PATH
)
If its not covered - add a soft link from it to one of the covered paths. For ex:
sudo ln -s /home/user/venv/bin/jupyter /usr/local/bin
Now you sould be able to run:
sudo jupyter notebook
you can use app:layout_constraintVertical_weight
it same as layout_weight
in linearlayout
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/button5"
app:layout_constraintVertical_weight="1"/>
<Button
android:id="@+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintLeft_toRightOf="@+id/button4"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintVertical_weight="1"/>
</android.support.constraint.ConstraintLayout>
NOTE: app:layout_constraintVertical_weight
(app:layout_constraintHorizontal_weight
) will work with android:layout_width="0dp"
(android:layout_height="0dp"
Here's a directive that will add target="_blank"
to all <a>
tags with an href
attribute. That means they will all open in a new window. Remember that directives are used in Angular for any dom manipulation/behavior. Live demo (click).
app.directive('href', function() {
return {
compile: function(element) {
element.attr('target', '_blank');
}
};
});
Here's the same concept made less invasive (so it won't affect all links) and more adaptable. You can use it on a parent element to have it affect all children links. Live demo (click).
app.directive('targetBlank', function() {
return {
compile: function(element) {
var elems = (element.prop("tagName") === 'A') ? element : element.find('a');
elems.attr("target", "_blank");
}
};
});
It seems like you would just use "target="_blank"
on your <a>
tag. Here are two ways to go:
<a href="//facebook.com" target="_blank">Facebook</a>
<button ng-click="foo()">Facebook</button>
JavaScript:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $window) {
$scope.foo = function() {
$window.open('//facebook.com');
};
});
Here are the docs for $window
: http://docs.angularjs.org/api/ng.$window
You could just use window
, but it is better to use dependency injection, passing in angular's $window
for testing purposes.
puttygen
supports exporting your private key to an OpenSSH compatible format. You can then use OpenSSH tools to recreate the public key.
Conversions->Export OpenSSH
and export your private key~/.ssh/id_dsa
(or id_rsa
).Create the RFC 4716 version of the public key using ssh-keygen
ssh-keygen -e -f ~/.ssh/id_dsa > ~/.ssh/id_dsa_com.pub
Convert the RFC 4716 version of the public key to the OpenSSH format:
ssh-keygen -i -f ~/.ssh/id_dsa_com.pub > ~/.ssh/id_dsa.pub
Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.
If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.
The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.
You can set the figure size if you explicitly create the figure with
plt.figure(figsize=(3,4))
You need to set figure size before calling plt.plot()
To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff
Use dictionary views:
if x in d.viewvalues():
dosomething()..
When you're going to work with such time series in Python, pandas
is indispensable. And here's the good news: it comes with a historical data downloader for Yahoo: pandas.io.data.DataReader
.
from pandas.io.data import DataReader
from datetime import datetime
ibm = DataReader('IBM', 'yahoo', datetime(2000, 1, 1), datetime(2012, 1, 1))
print(ibm['Adj Close'])
Here's an example from the pandas
documentation.
Update for pandas >= 0.19:
The pandas.io.data
module has been removed from pandas>=0.19
onwards. Instead, you should use the separate pandas-datareader
package. Install with:
pip install pandas-datareader
And then you can do this in Python:
import pandas_datareader as pdr
from datetime import datetime
ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1))
print(ibm['Adj Close'])
As stated by others, the filename bootstrap-theme.css is very confusing. I would have chosen something like bootstrap-3d.css or bootstrap-fancy.css which would be more descriptive of what it actually does. What the world sees as a "Bootstrap Theme" is a thing you can get from BootSwatch which is a totally different beast.
With that said, the effects are quite nice - gradients and shadows and such. Unfortunately this file will wreak havoc on BootSwatch Themes, so I decided to dig into what it would take to make it play nice with them.
Bootstrap-theme.css is generated from the theme.less file in the Bootstrap source. The affected elements are (as of Bootstrap v3.2.0):
The theme.less file depends on:
@import "variables.less";
@import "mixins.less";
The code uses colors defined in variables.less in several places, for example:
// Give the progress background some depth
.progress {
#gradient > .vertical(@start-color: darken(@progress-bg, 4%); @end-color: @progress-bg)
}
This why bootstrap-theme.css totally messes up BootSwatch Themes. The good news is that BootSwatch Themes are also created from variables.less files, so you can simply build a bootstrap-theme.css for your BootSwatch Theme.
The right way to do it is to update the Theme build process, but here here is the quick and dirty way. Replace the variables.less file in the Bootstrap source with the one from your Bootswatch Theme and build it and voila you have a bootstrap-theme.css file for your Bootswatch Theme.
Building Bootstrap may sound daunting, but it is actually very simple:
Done. See, that was easy, wasn't it?
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
What about a simple while loop?
while times > 0:
do_something()
times -= 1
You already have the variable; why not use it?
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
The fastest and imho easiest solution that works in any environment is:
<?php
namespace \My\Awesome\Namespace;
class Foo {
private $shortName;
public function fastShortName() {
if ($this->shortName === null) {
$this->shortName = explode("\\", static::class);
$this->shortName = end($this->shortName);
}
return $this->shortName;
}
public function shortName() {
return basename(strtr(static::class, "\\", "/"));
}
}
echo (new Foo())->shortName(); // "Foo"
?>
var string = string.split(",");
Edit: see the end examples for ES6 updated examples.
This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.
While they still work fine, other answers are missing something very important.
Is there not a simple way to pass a child's props to its parent using events, in React.js?
The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?
Child: it really does not have to be more complicated than that.
var Child = React.createClass({
render: function () {
return <button onClick={this.props.onClick}>{this.props.text}</button>;
},
});
Parent with single child: using the value it passes to the child
var Parent = React.createClass({
getInitialState: function() {
return {childText: "Click me! (parent prop)"};
},
render: function () {
return (
<Child onClick={this.handleChildClick} text={this.state.childText}/>
);
},
handleChildClick: function(event) {
// You can access the prop you pass to the children
// because you already have it!
// Here you have it in state but it could also be
// in props, coming from another parent.
alert("The Child button text is: " + this.state.childText);
// You can also access the target of the click here
// if you want to do some magic stuff
alert("The Child HTML is: " + event.target.outerHTML);
}
});
Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.
var Parent = React.createClass({
getInitialState: function() {
return {childrenData: [
{childText: "Click me 1!", childNumber: 1},
{childText: "Click me 2!", childNumber: 2}
]};
},
render: function () {
var children = this.state.childrenData.map(function(childData,childIndex) {
return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
}.bind(this));
return <div>{children}</div>;
},
handleChildClick: function(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
});
It is also possible to use this.handleChildClick.bind(null,childIndex)
and then use this.state.childrenData[childIndex]
Note we are binding with a null
context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.
This is for me a bad idea in term of coupling and encapsulation:
var Parent = React.createClass({
handleClick: function(childComponent) {
// using childComponent.props
// using childComponent.refs.button
// or anything else using childComponent
},
render: function() {
<Child onClick={this.handleClick} />
}
});
Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.
Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:
<Child ref="theChild" .../>
And access the DOM node in the parent with
React.findDOMNode(this.refs.theChild)
For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.
The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.
To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:
They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.
The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.
If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.
About using anything else
Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...)
or childComponent.forceUpdate()
, or assigning it new variables, inside the parent, making the whole app much harder to reason about.
Edit: ES6 examples
As many people now use ES6, here are the same examples for ES6 syntax
The child can be very simple:
const Child = ({
onClick,
text
}) => (
<button onClick={onClick}>
{text}
</button>
)
The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:
class Parent1 extends React.Component {
handleChildClick(childData,event) {
alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
alert("The Child HTML is: " + event.target.outerHTML);
}
render() {
return (
<div>
{this.props.childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => this.handleChildClick(child,e)}
/>
))}
</div>
);
}
}
But it can also be simplified if it does not need to manage state:
const Parent2 = ({childrenData}) => (
<div>
{childrenData.map(child => (
<Child
key={child.childNumber}
text={child.childText}
onClick={e => {
alert("The Child button data is: " + child.childText + " - " + child.childNumber);
alert("The Child HTML is: " + e.target.outerHTML);
}}
/>
))}
</div>
)
PERF WARNING (apply to ES5/ES6): if you are using PureComponent
or shouldComponentUpdate
, the above implementations will not be optimized by default because using onClick={e => doSomething()}
, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this
in class constructor) so that PureComponent
optimization can kick in, or you can implement your own shouldComponentUpdate
and ignore the callback in the props comparison check.
You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:
// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}
// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)
// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)
In this case you could optimize the Child component by using:
const OptimizedChild = onlyUpdateForKeys(['text'])(Child)
Good question. I've just started a large project at work and part of previous projects was to introduce modularity to our code-base.
I've heard bad things about maven. In fact, it's all I've ever heard about it. I looked at introducing it to solve the dependency nightmare we're currently experiencing. The problem I've seen with Maven is that it is quite rigid in its structure, i.e. you need to conform to its project layout for it to work for you.
I know what most people will say - you don't have to conform to the structure. Indeed that's true but you won't know this until you're over the initial learning curve at which point you've invested too much time to go and throw it all away.
Ant is used a lot these days, and I love it. Taking that into account I stumbled across a little known dependency manager called Apache Ivy. Ivy integrates into Ant very well and it's quick and easy to get basic JAR retrieval setup and working. Another benefit of Ivy is that it's very powerful yet quite transparent; you can transfer builds using mechanisms such as scp or ssh quite easily; 'chain' dependency retrieval over filesystems or remote repositories (Maven repo compatibility is one of its popular features).
That all said, I found it very frustrating to use in the end - the documentation is aplenty, but it's written in bad English which can add to frustration when debugging or attempting to work out what's gone wrong.
I'm going to revisit Apache Ivy at some point during this project and I hope to get it working properly. One thing it did do was allow us as a team to work out what libraries we're dependent on and get a documented list.
Ultimately I think it all comes down to how you work as an individual/team and what you need to resolve your dependency issues.
You might find the following resources relating to Ivy useful:
In Netbeans you can right click on the project and run it, but in IntelliJ IDEA you have to select the index.jsp file or the welcome file to run the project.
this is because Netbeans generate the following tag in web.xml and IntelliJ do not.
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
I took @Dmitriusan's answer and made it into an alias:
alias docker-run-prev-container='prev_container_id="$(docker ps -aq | head -n1)" && docker commit "$prev_container_id" "prev_container/$prev_container_id" && docker run -it --entrypoint=bash "prev_container/$prev_container_id"'
Add this into your ~/.bashrc
aliases file, and you'll have a nifty new docker-run-prev-container
alias which'll drop you into a shell in the previous container.
Helpful for debugging failed docker build
s.
This would be a good place to use a closure:
(function() {
var toggled = false;
$(".list-toggle").click(function() {
toggled = !toggled;
$(".list-sort").attr("colspan", toggled ? 6 : null);
});
})();
The toggled
variable will only exist inside of the scope defined, and can be used to store the state of the toggle from one click event to the next.
Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td>
that have $
inside. Example:
using nth-child in tables tr td
html
<tr>
<td> </td>
<td data-rel='$'>$</td>
<td> </td>
</tr>
css
table tr td[data-rel='$'] {
background-color: #333;
color: white;
}
Please try these example.
table tr td[data-content='$'] {_x000D_
background-color: #333;_x000D_
color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<td>A</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>B</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>C</td>_x000D_
<td data-content='$'>$</td>_x000D_
<td>D</td>_x000D_
</tr>_x000D_
</table>
_x000D_
UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.
I've solved changing from Release Configuration to Debug Configuration.
Nice article explaining the basics (does not cover line breaks, however).
A Whole Bunch of Amazing Stuff Pseudo Elements Can Do
If you need to have two inline elements where one breaks into the next line within another element, you can accomplish this by adding a pseudo-element :after with content:'\A' and white-space: pre
HTML
<h3>
<span class="label">This is the main label</span>
<span class="secondary-label">secondary label</span>
</h3>
CSS
.label:after {
content: '\A';
white-space: pre;
}
The right way to install grunt is by running this command:
npm install grunt -g
(Prepend "sudo" to the command above if you get a EACCESS error message)
-g will make npm install the package globally, so you will be able to use it whenever you want in your current machine.
Try Following custome class for prevant copy and paste in Edittext
public class SegoeUiEditText extends AppCompatEditText {
private final Context context;
@Override
public boolean isSuggestionsEnabled() {
return false;
}
public SegoeUiEditText(Context context) {
super(context);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public SegoeUiEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
private void setFonts(Context context) {
this.setTypeface(Typeface.createFromAsset(context.getAssets(), "Fonts/Helvetica-Normal.ttf"));
}
private void init() {
setTextIsSelectable(false);
this.setCustomSelectionActionModeCallback(new ActionModeCallbackInterceptor());
this.setLongClickable(false);
}
@Override
public int getSelectionStart() {
for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
if (element.getMethodName().equals("canPaste")) {
return -1;
}
}
return super.getSelectionStart();
}
/**
* Prevents the action bar (top horizontal bar with cut, copy, paste, etc.) from appearing
* by intercepting the callback that would cause it to be created, and returning false.
*/
private class ActionModeCallbackInterceptor implements ActionMode.Callback, android.view.ActionMode.Callback {
private final String TAG = SegoeUiEditText.class.getSimpleName();
public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; }
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; }
public void onDestroyActionMode(ActionMode mode) {}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
menu.clear();
return false;
}
@Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
}
}
}
I was having the same problem, it has a very simple solution.
Steps for executing the 'Lex' program:
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
<context:property-placeholder ... />
is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/>
simply factories a java.util.Properties instance that you can inject.
In Spring 3.1 (not 3.0...) you can do something like this:
@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration {
@Autowired Environment environment;
@Bean public javax.sql.DataSource dataSource( ){
String user = this.environment.getProperty("ds.user");
...
}
}
In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:
@Value("${ds.user}") private String user;
If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:
@Configuration
public class MySpring3Configuration {
@Bean
public static PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer ppc = ...
ppc.setLocations(...);
return ppc;
}
@Bean
public class DataSource dataSource(
@Value("${ds.user}") String user,
@Value("${ds.pw}") String pw,
...) {
DataSource ds = ...
ds.setUser(user);
ds.setPassword(pw);
...
return ds;
}
}
Note that the PPC is defined using a static
bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor
- it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.
Try this example
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html
I just ran into this problem and stumbled across a different situation. Although it's probably just a unicorn, I thought I'd lay it out.
I had one session that was smaller, and I noticed that the font sizes were different: the smaller session had the smaller fonts. Apparently, I had changed window font sizes for some reason.
So in OS X, I just did Cmd-+
on the smaller sized session, and it snapped back into place.
Update:
This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.
Original post
This is Microsoft's recommended way to handle WCF client calls:
For more detail see: Expected Exceptions
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
catch (TimeoutException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
catch (CommunicationException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
Additional information
So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:
c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client
Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.
This gives you:
Code below:
SELECT obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
I could have sworn there used to be a convenient fields
property on a form but … Must have been my imagination.
I just do this (for <form name="my_form"></form>
) because I usually don't want fieldsets themselves:
let fields = Array.from(document.forms.my_form.querySelectorAll('input, select, textarea'));
do url_raw.cast_to_raw()
support in oracle 6
No need to do that mess.
use python-lambda
https://github.com/nficano/python-lambda
with single command pylambda deploy
it will automatically deploy your function
Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.
One that I've found works for the site I test is this one:
waitForCondition | selenium.browserbot.getUserWindow().$.active==0 | 20000
Klendathu
Typescript needs to know that you're working with an HTMLElement for type safety, else you'll see lots of Property 'type' does not exist on type 'Element'
type of errors.
document.addEventListener("mousewheel", function(event){
let numberInput = (<HTMLInputElement>document.activeElement);
if (numberInput.type === "number") {
numberInput.blur();
}
});
In order to complete BlueM's accepted answer, you can desactivate it here:
Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off
With all due respect to the great answers provided already, there are times that I simply want a thread-safe IList. Nothing advanced or fancy. Performance is important in many cases but at times that just isn't a concern. Yes, there are always going to be challenges without methods like "TryGetValue" etc, but most cases I just want something that I can enumerate without needing to worry about putting locks around everything. And yes, somebody can probably find some "bug" in my implementation that might lead to a deadlock or something (I suppose) but lets be honest: When it comes to multi-threading, if you don't write your code correctly, it is going deadlock anyway. With that in mind I decided to make a simple ConcurrentList implementation that provides these basic needs.
And for what its worth: I did a basic test of adding 10,000,000 items to regular List and ConcurrentList and the results were:
List finished in: 7793 milliseconds. Concurrent finished in: 8064 milliseconds.
public class ConcurrentList<T> : IList<T>, IDisposable
{
#region Fields
private readonly List<T> _list;
private readonly ReaderWriterLockSlim _lock;
#endregion
#region Constructors
public ConcurrentList()
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>();
}
public ConcurrentList(int capacity)
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>(capacity);
}
public ConcurrentList(IEnumerable<T> items)
{
this._lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
this._list = new List<T>(items);
}
#endregion
#region Methods
public void Add(T item)
{
try
{
this._lock.EnterWriteLock();
this._list.Add(item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public void Insert(int index, T item)
{
try
{
this._lock.EnterWriteLock();
this._list.Insert(index, item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public bool Remove(T item)
{
try
{
this._lock.EnterWriteLock();
return this._list.Remove(item);
}
finally
{
this._lock.ExitWriteLock();
}
}
public void RemoveAt(int index)
{
try
{
this._lock.EnterWriteLock();
this._list.RemoveAt(index);
}
finally
{
this._lock.ExitWriteLock();
}
}
public int IndexOf(T item)
{
try
{
this._lock.EnterReadLock();
return this._list.IndexOf(item);
}
finally
{
this._lock.ExitReadLock();
}
}
public void Clear()
{
try
{
this._lock.EnterWriteLock();
this._list.Clear();
}
finally
{
this._lock.ExitWriteLock();
}
}
public bool Contains(T item)
{
try
{
this._lock.EnterReadLock();
return this._list.Contains(item);
}
finally
{
this._lock.ExitReadLock();
}
}
public void CopyTo(T[] array, int arrayIndex)
{
try
{
this._lock.EnterReadLock();
this._list.CopyTo(array, arrayIndex);
}
finally
{
this._lock.ExitReadLock();
}
}
public IEnumerator<T> GetEnumerator()
{
return new ConcurrentEnumerator<T>(this._list, this._lock);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new ConcurrentEnumerator<T>(this._list, this._lock);
}
~ConcurrentList()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
GC.SuppressFinalize(this);
this._lock.Dispose();
}
#endregion
#region Properties
public T this[int index]
{
get
{
try
{
this._lock.EnterReadLock();
return this._list[index];
}
finally
{
this._lock.ExitReadLock();
}
}
set
{
try
{
this._lock.EnterWriteLock();
this._list[index] = value;
}
finally
{
this._lock.ExitWriteLock();
}
}
}
public int Count
{
get
{
try
{
this._lock.EnterReadLock();
return this._list.Count;
}
finally
{
this._lock.ExitReadLock();
}
}
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
}
public class ConcurrentEnumerator<T> : IEnumerator<T>
{
#region Fields
private readonly IEnumerator<T> _inner;
private readonly ReaderWriterLockSlim _lock;
#endregion
#region Constructor
public ConcurrentEnumerator(IEnumerable<T> inner, ReaderWriterLockSlim @lock)
{
this._lock = @lock;
this._lock.EnterReadLock();
this._inner = inner.GetEnumerator();
}
#endregion
#region Methods
public bool MoveNext()
{
return _inner.MoveNext();
}
public void Reset()
{
_inner.Reset();
}
public void Dispose()
{
this._lock.ExitReadLock();
}
#endregion
#region Properties
public T Current
{
get { return _inner.Current; }
}
object IEnumerator.Current
{
get { return _inner.Current; }
}
#endregion
}
I simplify the code a little bit.
from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))
if( char.toUpperCase() != char.toLowerCase() )
Will return true only in case of letter
As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.
if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
Following the Jenkins wiki, you'll have to:
chown -R jenkins:jenkins $JENKINS_HOME
JENKINS_HOME is by default located in ~/.jenkins
on a Linux installation, yet to exactly find where it is located, go on the http://your_jenkins_url/configure page and check the value of the first parameter: Home directory
; this is the JENKINS_HOME.
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
Previous answer is not good for negative numbers. Use a short type instead of int
short iValue = -1400;
string sResult = iValue.ToString("X2");
Console.WriteLine("Value={0} Result={1}", iValue, sResult);
Now result is FA88
You can use the following function to replace Character
or String
at a particular position of a String. To replace all the following match cases use String.prototype.replaceAllMatches()
function.
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
var retStr = this, repeatedIndex = 0;
for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
if (repeatedIndex == 0 && x == 0) {
repeatedIndex = retStr.indexOf(matchkey);
} else { // matchIndex > 0
repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
}
if (x == matchIndex) {
retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
matchkey = null; // To break the loop.
}
}
return retStr;
};
Test:
var str = "yash yas $dfdas.**";
console.log('Index Matched replace : ', str.replaceMatch('as', '*', 2) );
console.log('Index Matched replace : ', str.replaceMatch('y', '~', 1) );
Output:
Index Matched replace : yash yas $dfd*.**
Index Matched replace : yash ~as $dfdas.**
You can store images in MySQL as blobs. However, this is problematic for a couple of reasons:
Instead, consider updating your table to add an image_path field. For example:
ALTER TABLE `your_table`
ADD COLUMN `image_path` varchar(1024)
Then store your images on disk, and update the table with the image path. When you need to use the images, retrieve them from disk using the path specified.
An advantageous side-effect of this approach is that the images do not necessarily be stored on disk; you could just as easily store a URL instead of an image path, and retrieve images from any internet-connected location.
Following @Vishnuvardhan Janapati 's answer, here is another way to save and reload model with custom layer/metric/loss under TensorFlow 2.0.0
import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras.utils.generic_utils import get_custom_objects
# custom loss (for example)
def custom_loss(y_true,y_pred):
return tf.reduce_mean(y_true - y_pred)
get_custom_objects().update({'custom_loss': custom_loss})
# custom loss (for example)
class CustomLayer(Layer):
def __init__(self, ...):
...
# define custom layer and all necessary custom operations inside custom layer
get_custom_objects().update({'CustomLayer': CustomLayer})
In this way, once you have executed such codes, and saved your model with tf.keras.models.save_model
or model.save
or ModelCheckpoint
callback, you can re-load your model without the need of precise custom objects, as simple as
new_model = tf.keras.models.load_model("./model.h5"})
This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?
d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()
Have you tried using Html.fromHtml(source)?
I think that class is pretty liberal with respect to source quality (it uses TagSoup internally, which was designed with real-life, bad HTML in mind). It doesn't support all HTML tags though, but it does come with a handler you can implement to react on tags it doesn't understand.
If you only want to perform some specific operations by your second SP and do not require values back from the SP then simply do:
Exec secondSPName @anyparams
Else, if you need values returned by your second SP inside your first one, then create a temporary table variable with equal numbers of columns and with same definition of column return by second SP. Then you can get these values in first SP as:
Insert into @tep_table
Exec secondSPName @anyparams
Update:
To pass parameter to second sp, do this:
Declare @id ID_Column_datatype
Set @id=(Select id from table_1 Where yourconditions)
Exec secondSPName @id
Update 2:
Suppose your second sp returns Id
and Name
where type of id
is int
and name
is of varchar(64)
type.
now, if you want to select these values in first sp then create a temporary table
variable and insert values into it:
Declare @tep_table table
(
Id int,
Name varchar(64)
)
Insert into @tep_table
Exec secondSP
Select * From @tep_table
This will return you the values returned by second SP.
Hope, this clear all your doubts.
You declare the variable as extern
in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace
.
The value you are setting in the timeout
attribute is the one of the correct ways to set the session timeout value.
The timeout
attribute specifies the number of minutes a session can be idle before it is abandoned. The default value for this attribute is 20.
By assigning a value of 1 to this attribute, you've set the session to be abandoned in 1 minute after its idle.
To test this, create a simple aspx page, and write this code in the Page_Load event,
Response.Write(Session.SessionID);
Open a browser and go to this page. A session id will be printed. Wait for a minute to pass, then hit refresh. The session id will change.
Now, if my guess is correct, you want to make your users log out as soon as the session times out. For doing this, you can rig up a login page which will verify the user credentials, and create a session variable like this -
Session["UserId"] = 1;
Now, you will have to perform a check on every page for this variable like this -
if(Session["UserId"] == null)
Response.Redirect("login.aspx");
This is a bare-bones example of how this will work.
But, for making your production quality secure apps, use Roles & Membership classes provided by ASP.NET. They provide Forms-based authentication which is much more reliabletha the normal Session-based authentication you are trying to use.
The following kills all the processes created by this user:
kill -9 -1
Based on Ray Nicholus's answer :
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
using this will also work :
inputElement.onchange = function(event) {
var fileList = event.target.files;
//TODO do something with fileList.
}
+=
adds another value with the variable's value and assigns the new value to the variable.
>>> x = 3
>>> x += 2
>>> print x
5
-=
, *=
, /=
does similar for subtraction, multiplication and division.
Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
function findKey(object, value) {
for (let key in object)
if (object[key] === value) return key;
return "key is not found";
}
const object = { id_1: "apple", id_2: "pear", id_3: "peach" };
console.log(findKey(object, "pear"));
//expected output: id_2
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.
If you want to use a format that allows you to keep the number like your entry this format works for me:
"# \\%"
The disapproval of tail
here based on speed alone doesn't really seem to emphasize that part of the slower speed comes from the fact that tail is safer to work with, if you don't for sure that the length of x will exceed n
, the number of elements you want to subset out:
x <- 1:10
tail(x, 20)
# [1] 1 2 3 4 5 6 7 8 9 10
x[length(x) - (0:19)]
#Error in x[length(x) - (0:19)] :
# only 0's may be mixed with negative subscripts
Tail will simply return the max number of elements instead of generating an error, so you don't need to do any error checking yourself. A great reason to use it. Safer cleaner code, if extra microseconds/milliseconds don't matter much to you in its use.
"List" is an object getting from backend and using iterator to display in table
"minAmount" , "MaxAmount" is an object variable "mrr" is an just temporary var to get value and iterate mrr to get data.
<table class="table table-hover">
<tbody>
<tr th:each="mrr,iterStat : ${list}">
<td th:text="${mrr.id}"></td>
<td th:text="${mrr.minAmount}"></td>
<td th:text="${mrr.maxAmount}"></td>
</tr>
</tbody>
</table>
I tried -Xmx32255M
is accepted by vmargs for compressed oops.
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
As a general way to handle error in a loop like your sample code, I would rather use:
on error resume next
for each...
'do something that might raise an error, then
if err.number <> 0 then
...
end if
next ....
You may run your node.js application on multiple cores by using the cluster module on combination with os module which may be used to detect how many CPUs you have.
For example let's imagine that you have a server
module that runs simple http server on the backend and you want to run it for several CPUs:
// Dependencies._x000D_
const server = require('./lib/server'); // This is our custom server module._x000D_
const cluster = require('cluster');_x000D_
const os = require('os');_x000D_
_x000D_
// If we're on the master thread start the forks._x000D_
if (cluster.isMaster) {_x000D_
// Fork the process._x000D_
for (let i = 0; i < os.cpus().length; i++) {_x000D_
cluster.fork();_x000D_
}_x000D_
} else {_x000D_
// If we're not on the master thread start the server._x000D_
server.init();_x000D_
}
_x000D_
Assuming you have a form like this:
<form id="myForm" action="foo.php" method="post">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
You can attach a onsubmit
-event with jQuery like this:
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
If you return false
the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.
Vincent Povirk's answer won't work completely;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
replace
include fastcgi_params;
with
include fastcgi.conf;
and remove fastcgi_param SCRIPT_FILENAME ... in nginx.conf
The problem can be PHP configuration:
Please check the setting max_input_vars in the php.ini file.
Try to increase the value of this setting to 5000 as example.
max_input_vars = 5000
Then restart your web-server and try.
Replace following
curl_setopt ($setuploginurl, CURLOPT_SSLVERSION, 'CURL_SSLVERSION_TLSv1_2');
With
curl_setopt ($ch, CURLOPT_SSLVERSION, 6);
Should work flawlessly.
You can use the split() function, which returns a list, to separate them.
letters = 'QH QD JC KD JS'
letters_list = letters.split()
Printing letters_list would now format it like this:
['QH', 'QD', 'JC', 'KD', 'JS']
Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:
print(letters_list[2])
This would print the third element of your list, which is 'JC'
If you are assigning the results to a column or variable, give it the DATE type, and the conversion is implicit.
DECLARE @Date DATE = GETDATE()
SELECT @Date --> 2017-05-03
I discovered the joy of anaconda: https://www.continuum.io/downloads
C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1)
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl
voila, a virtual environment is created.
Four little additions to the accepted solution:
Complete solution that seems to work for most browsers:
CSS
html.noscroll {
position: fixed;
overflow-y: scroll;
width: 100%;
}
Disable scroll
if ($(document).height() > $(window).height()) {
var scrollTop = ($('html').scrollTop()) ? $('html').scrollTop() : $('body').scrollTop(); // Works for Chrome, Firefox, IE...
$('html').addClass('noscroll').css('top',-scrollTop);
}
Enable scroll
var scrollTop = parseInt($('html').css('top'));
$('html').removeClass('noscroll');
$('html,body').scrollTop(-scrollTop);
Thanks to Fabrizio and Dejan for putting me on the right track and to Brodingo for the solution to the double scroll bar
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
java.util.UUID
: toString() method
Generally speaking, the cli/php.ini
file is used when the PHP binary is called from the command-line.
You can check that running php --ini
from the command-line.
fpm/php.ini
will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo()
from a php page served by your webserver.
cgi/php.ini
, in your situation, will most likely not be used.
Using two distinct php.ini
files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.
Typically, in the php.ini
file that's used by the web-server, you'll specify a rather short max_execution_time
: web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini
file that will be used is the one in cli/
. For those scripts, you'll specify a much longer max_execution_time
in cli/php.ini
than you did in fpm/php.ini
.
max_execution_time
is a common example ; you could do the same with several other configuration directives, of course.
You can use not only now()
, also current_timestamp()
and localtimestamp()
.
The main reason of incorrect display timestamp is inserting NOW() with single quotes! It didn't work for me in MySQL Workbench because of this IDE add single quotes for mysql functions and i didn't recognize it at once )
Don't use functions with single quotes like in MySQL Workbench. It doesn't work.
I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
Another way to do this:
git push origin --delete <branch_name>
)If removing empty lines means lines including any spaces, use:
grep '\S' FILE
For example:
$ printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$ cat -v FILE
line1
line2
line3
line4
$ grep '\S' FILE
line1
line2
line3
line4
$ grep . FILE
line1
line2
line3
line4
See also:
This worked perfectly for me
background-repeat: no-repeat;
background-size: 100% 100%;
String methodName =Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("methodName = " + methodName);
For anyone using Windows 10, there's a request in Feedback Hub to get Microsoft to fix this issue. If you'd like to add a +1 to have it fixed, here's a link: https://aka.ms/Cryalp.
The link only works on Windows 10 as it needs to open Feedback Hub to get to the suggestion. The link was generated using the "Share" feature in Feedback Hub and aka.ms is an internal link shortening service used by Microsoft.
I think a suitable replacement for when you have three to five screens of equal importance is the BottomNavigationActivity,this can be used to switch fragments.
You will notice a wizard exists for this in Android Studio, take care however as Android Studio has a tendency to produce overly complex boiler plate code.
A tutorial can be found here: https://android.jlelse.eu/ultimate-guide-to-bottom-navigation-on-android-75e4efb8105f
Another quality tutorial can be found at Android Hive here: https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/
Try wrapping your FileWriter
in a BufferedWriter
:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
One interesting difference that seems worth noting is that while FirstOrDefault and Take(1) generate the same SQL (according to LINQPad, anyway), FirstOrDefault returns a value--the default--when there are no matching rows and Take(1) returns no results... at least in LINQPad.
Use geom_text
, with aes
label. You can play with hjust, vjust
to adjust text position.
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +
geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)
In WPF an image is typically loaded from a Stream or an Uri.
BitmapImage supports both and an Uri can even be passed as constructor argument:
var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);
If the image file is located in a local folder, you would have to use a file://
Uri. You could create such a Uri from a path like this:
var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);
If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:
var uri = new Uri("pack://application:,,,/Bilder/sas.png");
In this case the Visual Studio Build Action for sas.png
would have to be Resource
.
Once you have created a BitmapImage
and also have an Image control like in this XAML
<Image Name="image1" />
you would simply assign the BitmapImage to the Source
property of that Image control:
image1.Source = bitmap;
Use $elemMatch to find the array of particular object
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
It Seems your AVD Manager is missing from root SDK directory please follow the Steps
Now try to run it.
This issue arises when the host key is expired or changed. you can remove the keys that host is using and try to ssh again, so that you are adding new key that is known to both client and server.
You can check the keys associated with your hosts with cat /.ssh/known_hosts
. Now, You can remove the hosts keys manually or using the ssh-keygen option. You can do either of the following option.
Manual removal of keys
vim /.ssh/known_hosts
delete the key that is associated with your host.
Remove key using ssh-keygen
ssh-keygen -R your_host_or_host_ip
This will remove your key associated with the host.
Now, you can ssh to your host as usual and you will be asked if you want to continue to this host. Once your enter yes, this host will be added to your/.ssh/known_hosts with updated key. By now, you should be your host.
Also, consider GForge.
Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:
sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh
Select SQL Management Studio from the dropdown in Download SQL Server 2012 Express.
mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.
If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.