SoftReference
is designed for caches. When it is found that a WeakReference
references an otherwise unreachable object, then it will get cleared immediately. SoftReference
may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx
). SoftReference
s will be cleared before OutOfMemoryError
is thrown, unless otherwise reachable.
componentWillReceiveProps(nextProps) { // your code here}
I think that is the event you need. componentWillReceiveProps
triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.
A catch-all jQuery custom event based on an extension of it's core methods like it was proposed by different people in this thread:
(function() {
var ev = new $.Event('event.css.jquery'),
css = $.fn.css,
show = $.fn.show,
hide = $.fn.hide;
// extends css()
$.fn.css = function() {
css.apply(this, arguments);
$(this).trigger(ev);
};
// extends show()
$.fn.show = function() {
show.apply(this, arguments);
$(this).trigger(ev);
};
// extends hide()
$.fn.hide = function() {
hide.apply(this, arguments);
$(this).trigger(ev);
};
})();
An external library then, uses sth like $('selector').css('property', value)
.
As we don't want to alter the library's code but we DO want to extend it's behavior we do sth like:
$('#element').on('event.css.jquery', function(e) {
// ...more code here...
});
Example: user clicks on a panel that is built by a library. The library shows/hides elements based on user interaction. We want to add a sensor that shows that sth has been hidden/shown because of that interaction and should be called after the library's function.
Another example: jsfiddle.
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
Your pizza can have exactly three topping types:
So we order two pizzas and choose the following toppings:
Pizza Topping Topping Type
-------- ---------- -------------
1 mozzarella cheese
1 pepperoni meat
1 olives vegetable
2 mozzarella meat
2 sausage cheese
2 peppers vegetable
Wait a second, mozzarella can't be both a cheese and a meat! And sausage isn't a cheese!
We need to prevent these sorts of mistakes, to make mozzarella always be cheese. We should use a separate table for this, so we write down that fact in only one place.
Pizza Topping
-------- ----------
1 mozzarella
1 pepperoni
1 olives
2 mozzarella
2 sausage
2 peppers
Topping Topping Type
---------- -------------
mozzarella cheese
pepperoni meat
olives vegetable
sausage meat
peppers vegetable
That was the explanation that an 8 year-old might understand. Here is the more technical version.
BCNF acts differently from 3NF only when there are multiple overlapping candidate keys.
The reason is that the functional dependency X -> Y
is of course true if Y
is a subset of X
. So in any table that has only one candidate key and is in 3NF, it is already in BCNF because there is no column (either key or non-key) that is functionally dependent on anything besides that key.
Because each pizza must have exactly one of each topping type, we know that (Pizza, Topping Type) is a candidate key. We also know intuitively that a given topping cannot belong to different types simultaneously. So (Pizza, Topping) must be unique and therefore is also a candidate key. So we have two overlapping candidate keys.
I showed an anomaly where we marked mozarella as the wrong topping type. We know this is wrong, but the rule that makes it wrong is a dependency Topping -> Topping Type
which is not a valid dependency for BCNF for this table. It's a dependency on something other than a whole candidate key.
So to solve this, we take Topping Type out of the Pizzas table and make it a non-key attribute in a Toppings table.
You're declaring everything in the parent page. So the references to window
and document
are to the parent page's. If you want to do stuff to the iframe
's, use iframe || iframe.contentWindow
to access its window
, and iframe.contentDocument || iframe.contentWindow.document
to access its document
.
There's a word for what's happening, possibly "lexical scope": What is lexical scope?
The only context of a scope is this. And in your example, the owner of the method is doc
, which is the iframe
's document
. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.
This is how I would write it:
(function () {
var dom, win, doc, where, iframe;
iframe = document.createElement('iframe');
iframe.src = "javascript:false";
where = document.getElementsByTagName('script')[0];
where.parentNode.insertBefore(iframe, where);
win = iframe.contentWindow || iframe;
doc = iframe.contentDocument || iframe.contentWindow.document;
doc.open();
doc._l = (function (w, d) {
return function () {
w.vanishing_global = new Date().getTime();
var js = d.createElement("script");
js.src = 'test-vanishing-global.js?' + w.vanishing_global;
w.name = "foobar";
d.foobar = "foobar:" + Math.random();
d.foobar = "barfoo:" + Math.random();
d.body.appendChild(js);
};
})(win, doc);
doc.write('<body onload="document._l();"></body>');
doc.close();
})();
The aliasing of win
and doc
as w
and d
aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe
's stuff. If you want to access the parent's, you still use window
and document
.
I'm not sure what the implications are of adding methods to a document
(doc
in this case), but it might make more sense to set the _l
method on win
. That way, things can be run without a prefix...such as <body onload="_l();"></body>
To make vim the default editor for git on ubuntu 20:04 run the following command:
git config --global core.editor vim
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
You can export the query results to a text file (or insert statements, or even pdf) by right-clicking on Query Result row (any row) and choose Export
using Sql Developer 3.0
See SQL Developer downloads for latest versions
To build on the solutions from Ffisegydd and amaliammr, here's an example where we make CSV representation for a custom colormap:
#! /usr/bin/env python3
import matplotlib
import numpy as np
vmin = 0.1
vmax = 1000
norm = matplotlib.colors.Normalize(np.log10(vmin), np.log10(vmax))
lognum = norm(np.log10([.5, 2., 10, 40, 150,1000]))
cdict = {
'red':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 1, 1),
(lognum[3], 0.8, 0.8),
(lognum[4], .7, .7),
(lognum[5], .7, .7)
),
'green':
(
(0., .6, .6),
(lognum[0], 0.8, 0.8),
(lognum[1], 1, 1),
(lognum[2], 1, 1),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 0, 0)
),
'blue':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 0, 0),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 1, 1)
)
}
mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
norm = matplotlib.colors.LogNorm(vmin, vmax)
colors = {}
count = 0
step_size = 0.001
for value in np.arange(vmin, vmax+step_size, step_size):
count += 1
print("%d/%d %f%%" % (count, vmax*(1./step_size), 100.*count/(vmax*(1./step_size))))
rgba = mycmap(norm(value), bytes=True)
color = (rgba[0], rgba[1], rgba[2])
if color not in colors.values():
colors[value] = color
print ("value, red, green, blue")
for value in sorted(colors.keys()):
rgb = colors[value]
print("%s, %s, %s, %s" % (value, rgb[0], rgb[1], rgb[2]))
I could able to make it work only by adding GRANT OPTION
, without that always receive permission denied error
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' WITH GRANT OPTION;
Also add to your beans :
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<array>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean></bean>
For @ExceptionHandler :
enter code<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
<property name="messageConverters">
<array>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg index="0" name="defaultCharset" value="UTF-8"/>
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
<value>application/x-www-form-urlencoded;charset=UTF-8</value>
</list>
</property>
</bean>
</array>
</property>
</bean>
If you use <mvc:annotation-driven/>
it should be after beans.
From the javadoc for Set.iterator()
:
Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
And, as already stated by shuuchan, a TreeSet
is an implemention of Set
that has a guaranteed order:
The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
After trying grenade's answer you may use a temporary fix:
sudo bash -c 'echo 524288 > /proc/sys/fs/inotify/max_user_watches'
This does the same thing as kds's answer, but without persisting the changes. This is useful if the error just occurs after some uptime of your system.
Use this
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
test open the termenal or cmd. go to the [tomcat-home]\bin directory. ex: c:\tomcat8\bin write the following command: Tomcat8W //ES//Tomcat8 will open dialog, select the java tap(top tap). change the Java virtual Machine value.
My answer is too late, but it can help others.
I had the same problem, even when I used a form tag.
I solved it by declaring Meta Charset in the header of the page:
<meta charset = "UTF-8" />
_x000D_
It's better to use backtracking
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b) {
char temp;
temp = *a;
*a = *b;
*b = temp;
}
void print(char *a, int i, int n) {
int j;
if(i == n) {
printf("%s\n", a);
} else {
for(j = i; j <= n; j++) {
swap(a + i, a + j);
print(a, i + 1, n);
swap(a + i, a + j);
}
}
}
int main(void) {
char a[100];
gets(a);
print(a, 0, strlen(a) - 1);
return 0;
}
Remove obj
and just do this inside your for loop:
arr.push(i);
Also, the i < yearEnd
condition will not include the final year, so change it to i <= yearEnd
.
Regexp work on the character base, and \d
means a single digit 0
...9
and not a decimal number.
A regular expression that matches only integers with a sign could be for example
^[-+]?[0-9]+$
meaning
^
- start of string[-+]?
- an optional (this is what ?
means) minus or plus sign[0-9]+
- one or more digits (the plus means "one or more" and [0-9]
is another way to say \d
)$
- end of stringNote: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2
could otherwise end up being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.
For me, this also worked:
def search(myDict, search1):
search.a=[]
for key, value in myDict.items():
if search1 in value:
search.a.append(key)
search(myDict, 'anyName')
print(search.a)
This technique solved my problem:
In parent form:
frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;
frm.Show();
In the child form (Load event):
this.WindowState = FormWindowState.Maximized;
It works:
mysql -u root -p db_name < "C:\folder_name\db_name.sql"
C:\
is for example
In my case the problem was that the logs folder did not exist resp. the error.log file in this folder.
The For-each loop, as it is called, is a type of for loop that is used with collections to guarantee that all items in a collection are iterated over. For example
for ( Object o : objects ) {
System.out.println(o.toString());
}
Will call the toString() method on each object in the collection "objects". One nice thing about this is that you cannot get an out of bounds exception.
chart.js supports this by defaul check the link. chartjs
you can set the label in the options attribute.
options object looks like this.
options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
display: true,
position: 'left',
ticks: {
callback: function(value, index, values) {
return value + "%";
}
},
scaleLabel:{
display: true,
labelString: 'Average Personal Income',
fontColor: "#546372"
}
}
]
}
};
Instead of copy/pasting the code from the tutorial, use the code suggestion in the IDE. Start typing "extends ActionBar..." it will propose "ActionBarActivity" click enter. It worked for me!
C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]
* Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.
Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.
A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.
Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]
Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]
Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.
Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]
More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.
Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]
More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]
Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]
C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]
C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]
C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]
C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]
Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.
Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format
throughout all examples.
Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]
C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)
C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]
Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.
The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".
C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]
The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]
C++11/14/17/… References:
The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.
The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.
Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.
The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.
The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.
cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.
Note: Some information contained within these books may not be up-to-date or no longer considered best practice.
The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.
Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]
Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.
Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.
Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.
The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.
Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const
), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.
Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.
customerssalary.Average();
customerssalary.Sum();
You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.
Try this
PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))
PriceList[0:7]=[PizzaChange]*7
PriceList[7:11]=[PizzaChange+3]*4
In Python 2.x, just use the ord
and chr
functions:
>>> ord('c')
99
>>> ord('c') + 1
100
>>> chr(ord('c') + 1)
'd'
>>>
Python 3.x makes this more organized and interesting, due to its clear distinction between bytes and unicode. By default, a "string" is unicode, so the above works (ord
receives Unicode chars and chr
produces them).
But if you're interested in bytes (such as for processing some binary data stream), things are even simpler:
>>> bstr = bytes('abc', 'utf-8')
>>> bstr
b'abc'
>>> bstr[0]
97
>>> bytes([97, 98, 99])
b'abc'
>>> bytes([bstr[0] + 1, 98, 99])
b'bbc'
Swift 3, xcode 8.1
You can use small extension to place UIActivityIndicatorView in the centre of UIView and inherited UIView classes:
extension UIActivityIndicatorView {
convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
self.init(activityIndicatorStyle: activityIndicatorStyle)
center = parentView.center
self.color = color
parentView.addSubview(self)
}
}
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray, placeInTheCenterOf: view)
activityIndicator.startAnimating()
In this example UIActivityIndicatorView placed in the centre of the ViewControllers view:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, color: .gray, placeInTheCenterOf: view)
activityIndicator.startAnimating()
}
}
extension UIActivityIndicatorView {
convenience init(activityIndicatorStyle: UIActivityIndicatorViewStyle, color: UIColor, placeInTheCenterOf parentView: UIView) {
self.init(activityIndicatorStyle: activityIndicatorStyle)
center = parentView.center
self.color = color
parentView.addSubview(self)
}
}
Once I had this problem after renaming a file. I renamed the file from within Xcode, but afterwards Xcode couldn't find the function in the file. Even a clean rebuild didn't fix the problem, but closing and then re-opening the project got the build to work.
I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.
I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.
Thanks to all above though.
Using moment.js
, you can use keepOffset
parameter of toISOString
:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
public class NumberConverter {
private String[] singleDigit = {"", " one", " two", " three",
" four", " five"," six", " seven", " eight", " nine"};
private String[] tens = {" ten", " eleven", " twelve", " thirteen",
" fourteen", " fifteen"," sixteen", " seventeen", " eighteen", " nineteen"};
private String[] twoDigits = {"", "", " twenty", " thirty",
" forty", " fifty"," sixty", " seventy", " eighty", " ninety"};
public String convertToWords(String input) {
long number = Long.parseLong(input);
int size = input.length();
if (size <= 3) {
int num = (int) number;
return handle3Digits(num);
} else if (size > 3 && size <= 6) {
int thousand = (int)(number/1000);
int hundred = (int) (number % 1000);
String thousands = handle3Digits(thousand);
String hundreds = handle3Digits(hundred);
String word = "";
if (!thousands.isEmpty()) {
word = thousands +" thousand";
}
word += hundreds;
return word;
} else if (size > 6 && size <= 9) {
int million = (int) (number/ 1000000);
number = number % 1000000;
int thousand = (int)(number/1000);
int hundred = (int) (number % 1000);
String millions = handle3Digits(million);
String thousands = handle3Digits(thousand);
String hundreds = handle3Digits(hundred);
String word = "";
if (!millions.isEmpty()) {
word = millions +" million";
}
if (!thousands.isEmpty()) {
word += thousands +" thousand";
}
word += hundreds;
return word;
}
return "Not implemented yet.";
}
private String handle3Digits(int number) {
if (number <= 0)
return "";
String word = "";
if (number/100 > 0) {
int dividend = number/100;
word = singleDigit[dividend] + " hundred";
number = number % 100;
}
if (number/10 > 1) {
int dividend = number/10;
number = number % 10;
word += twoDigits[dividend];
} else if (number/10 == 1) {
number = number % 10;
word += tens[number];
return word;
} else {
number = number % 10;
}
if (number > 0) {
word += singleDigit[number];
}
return word;
}
}
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Following will give you the selected content as well as updating the clipboard.
Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.
document.querySelector('element').bind('copy', function(event) {
var selectedText = window.getSelection().toString();
selectedText = selectedText.replace(/\u200B/g, "");
clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
clipboardData.setData('text/html', selectedText);
event.preventDefault();
});
One simple query will do it:
SELECT *
FROM table
GROUP BY email
HAVING COUNT(*) = 1;
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
If you use links's onclick function to call a modal by jQuery, the "href" can't be null.
For example:
... ...
<a href="" onclick="openModal()">Open a Modal by jQuery</a>
... ...
... ...
<script type="text/javascript">
function openModal(){
$('#myModal').modal();
}
</script>
The Modal can't show. The right code is :
<a href="#" onclick="openModal()">Open a Modal by jQuery</a>
Please try with below query:
SELECT FORMAT(987654321,'#,###,##0')
Format with right decimal point :
SELECT FORMAT(987654321,'#,###,##0.###\,###')
You left off the /
(pattern delimiter) and $
(match end string).
preg_match("/^[a-zA-Z0-9]+$/", $value)
with uniq function answer:
func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
var seen: [E:Bool] = [:]
return source.filter({ (v) -> Bool in
return seen.updateValue(true, forKey: v) == nil
})
}
use:
var test = [1,2,3,4,5,6,7,8,9,9,9,9,9,9]
print(uniq(test)) //1,2,3,4,5,6,7,8,9
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils
class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64
.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1
which is printed out (and which contains 4 more lists).
I think the easiest way to do this is to use lapply
with the addition of dataframe
(assuming that each list inside each element of the main list (like the lists in $f10010_1
) has the same length):
lapply(mylist, function(x) write.table( data.frame(x), 'test.csv' , append= T, sep=',' ))
The above will convert $f10010_1
into a dataframe then do the same with every other element and append one below the other in 'test.csv'
You can also type ?write.table
on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.
Put the title in its own span.
<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");
Easy, this works in iOS8 and 9 / Swift 2 / Xcode7, just put this code inside your viewcontroller.swift. It will print the screen dimensions with every orientation change, you can put your own code instead:
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
getScreenSize()
}
var screenWidth:CGFloat=0
var screenHeight:CGFloat=0
func getScreenSize(){
screenWidth=UIScreen.mainScreen().bounds.width
screenHeight=UIScreen.mainScreen().bounds.height
print("SCREEN RESOLUTION: "+screenWidth.description+" x "+screenHeight.description)
}
I know this thread is old but I just wanted to add this answer for those who believe it's safer to Alter
than Drop
and Create
. The below will Alter
the Function
if it exists or Create
it if doesn't:
IF NOT EXISTS (SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[foo]')
AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
EXEC('CREATE FUNCTION [dbo].[foo]() RETURNS INT AS BEGIN RETURN 0 END')
GO
ALTER FUNCTION [dbo].[foo]
AS
...
Sometimes dict()
is a good choice:
a=dict(zip(['Mon','Tue','Wed','Thu','Fri'], [x for x in range(1, 6)]))
mydict=dict(zip(['mon','tue','wed','thu','fri','sat','sun'],
[random.randint(0,100) for x in range(0,7)]))
echo '\x12\x02'
will not be interpreted, and will literally write the string \x12\x02
(and append a newline) to the specified serial port. Instead use
echo -n ^R^B
which you can construct on the command line by typing CtrlVCtrlR and CtrlVCtrlB. Or it is easier to use an editor to type into a script file.
The stty
command should work, unless another program is interfering. A common culprit is gpsd
which looks for GPS devices being plugged in.
Just for the records you can also define your object in the controller like this:
this.styleDiv = {color: '', backgroundColor:'', backgroundImage : '' };
and then you can define a function to change the property of the object directly:
this.changeBackgroundImage = function (){
this.styleDiv.backgroundImage = 'url('+this.backgroundImage+')';
}
Doing it in that way you can modify dinamicaly your style.
dragonfly's answer worked for me (python 3.4.3).
import sys
del sys.modules['module_name']
Here is a lower level solution :
exec(open("MyClass.py").read(), globals())
For everyone else who has no duplicate Listen directives and no running processes on the port: check that you don't accidentally include ports.conf twice in apache2.conf (as I did due to a bad merge).
adding border-spacing: 0rem 0.5rem; creates a space for each cell (td, th) items on its bottom while leaving no space between the cells
table.app-table{
border-collapse: separate;
border-spacing: 0rem 0.5rem;
}
table.app-table thead tr.border-row the,
table.app-table tbody tr.border-row td,
table.app-table tbody tr.border-row th{
border-top: 1px solid #EAEAEA;
border-bottom: 1px solid #EAEAEA;
vertical-align: middle;
white-space: nowrap;
font-size: 0.875rem;
}
table.app-table thead tr.border-row th:first-child,
table.app-table tbody tr.border-row td:first-child{
border-left: 1px solid #EAEAEA;
}
table.app-table thead tr.border-row th:last-child,
table.app-table tbody tr.border-row td:last-child{
border-right: 1px solid #EAEAEA;
}
I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image"
android:layout_alignParentRight="true"
android:paddingRight="4dp" />
<TextView
android:id="@+id/title"
android:layout_toLeftOf="@id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="23sp"
android:maxLines="1" />
<TextView
android:id="@+id/subtitle"
android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assuming you have a custom class like this
public class CustomClass {
private long id;
private String title, subtitle, picture;
public CustomClass () {
}
public CustomClass (long id, String title, String subtitle, String picture) {
this.id = id;
this.title= title;
this.subtitle= subtitle;
this.picture= picture;
}
//add getters and setters
}
And a CustomAdapter.java
uses the xml-layout
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int resource;
private LayoutInflater inflater;
public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever
super(context, R.layout.customlistviewitem, values);
this.context = context;
this.resource = R.layout.customlistview;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = (RelativeLayout) inflater.inflate(resource, null);
CustomClass item = (CustomClass) getItem(position);
TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
ImageView imageview = (ImageView) convertView.findViewById(R.id.image);
//fill the textviews and imageview with the values
textviewTitle = item.getTtile();
textviewSubtitle = item.getSubtitle();
if (item.getAfbeelding() != null) {
int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
}
imageview.setImageDrawable(image);
return convertView;
}
}
Did you manage to do it? Feel free to ask if you want more info on something :)
EDIT: Changed the adapter to suit a List instead of just a List
There is a property className in javascript to change the name of the class of an HTML element. The existing class value will be replaced with the new one, that you have assigned in className.
<!DOCTYPE html>
<html>
<head>
<title>How to change class of an HTML element in Javascript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />
<center><button id="change-class">Change Class</button></center>
<script>
var change_class=document.getElementById("change-class");
change_class.onclick=function()
{
var icon=document.getElementById("icon");
icon.className="fa fa-gear";
}
</script>
</body>
</html>
Credit - https://jaischool.com/javascript-lang/how-to-change-class-name-of-an-html-element-in-javascript.html
The only thing that appears to work is to set flex-wrap: wrap;
on the container and them somehow make the child you want to break out after to fill the full width, so width: 100%;
should work.
If, however, you can't stretch the element to 100% (for example, if it's an <img>
), you can apply a margin to it, like width: 50px; margin-right: calc(100% - 50px)
.
Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl
Another clear solution, you can use constants to keep convention and add multiple [Authorize] attributes. Check this out:
public static class RolesConvention
{
public const string Administrator = "Administrator";
public const string Guest = "Guest";
}
Then in the controller:
[Authorize(Roles = RolesConvention.Administrator )]
[Authorize(Roles = RolesConvention.Guest)]
[Produces("application/json")]
[Route("api/[controller]")]
public class MyController : Controller
I give you two answers. npm combined with other tools is powerful but requires some work to setup. If you just want to download some libraries, you might want to use Library Manager instead (released in Visual Studio 15.8).
First add package.json in the root of you project. Add the following content:
{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"gulp": "3.9.1",
"del": "3.0.0"
},
"dependencies": {
"jquery": "3.3.1",
"jquery-validation": "1.17.0",
"jquery-validation-unobtrusive": "3.2.10",
"bootstrap": "3.3.7"
}
}
This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM. Then add a new file in the root of you project named gulpfile.js. Add the following content:
/// <binding AfterBuild='default' Clean='clean' />
/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/
var gulp = require('gulp');
var del = require('del');
var nodeRoot = './node_modules/';
var targetPath = './wwwroot/lib/';
gulp.task('clean', function () {
return del([targetPath + '/**/*']);
});
gulp.task('default', function () {
gulp.src(nodeRoot + "bootstrap/dist/js/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/js"));
gulp.src(nodeRoot + "bootstrap/dist/css/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/css"));
gulp.src(nodeRoot + "bootstrap/dist/fonts/*").pipe(gulp.dest(targetPath + "/bootstrap/dist/fonts"));
gulp.src(nodeRoot + "jquery/dist/jquery.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.js").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery/dist/jquery.min.map").pipe(gulp.dest(targetPath + "/jquery/dist"));
gulp.src(nodeRoot + "jquery-validation/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation/dist"));
gulp.src(nodeRoot + "jquery-validation-unobtrusive/dist/*.js").pipe(gulp.dest(targetPath + "/jquery-validation-unobtrusive"));
});
This file contains a JavaScript code that is executed when the project is build and cleaned. It’s will copy all necessary files to lib2 (not lib – you can easily change this). I have used the same structure as in a new project, but it’s easy to change files to a different location. If you move the files, make sure you also update _Layout.cshtml. Note that all files in the lib2-directory will be removed when the project is cleaned.
If you right click on gulpfile.js, you can select Task Runner Explorer. From here you can run gulp manually to copy or clean files.
Gulp could also be useful for other tasks like minify JavaScript and CSS-files:
https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp?view=aspnetcore-2.1
Right click on you project and select Manage client side-libraries. The file libman.json is now open. In this file you specify which library and files to use and where they should be stored locally. Really simple! The following file copies the default libraries that is used when creating a new ASP.NET Core 2.1 project:
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": [
{
"library": "[email protected]",
"files": [ "jquery.js", "jquery.min.map", "jquery.min.js" ],
"destination": "wwwroot/lib/jquery/dist/"
},
{
"library": "[email protected]",
"files": [ "additional-methods.js", "additional-methods.min.js", "jquery.validate.js", "jquery.validate.min.js" ],
"destination": "wwwroot/lib/jquery-validation/dist/"
},
{
"library": "[email protected]",
"files": [ "jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js" ],
"destination": "wwwroot/lib/jquery-validation-unobtrusive/"
},
{
"library": "[email protected]",
"files": [
"css/bootstrap.css",
"css/bootstrap.css.map",
"css/bootstrap.min.css",
"css/bootstrap.min.css.map",
"css/bootstrap-theme.css",
"css/bootstrap-theme.css.map",
"css/bootstrap-theme.min.css",
"css/bootstrap-theme.min.css.map",
"fonts/glyphicons-halflings-regular.eot",
"fonts/glyphicons-halflings-regular.svg",
"fonts/glyphicons-halflings-regular.ttf",
"fonts/glyphicons-halflings-regular.woff",
"fonts/glyphicons-halflings-regular.woff2",
"js/bootstrap.js",
"js/bootstrap.min.js",
"js/npm.js"
],
"destination": "wwwroot/lib/bootstrap/dist"
},
{
"library": "[email protected]",
"files": [ "list.js", "list.min.js" ],
"destination": "wwwroot/lib/listjs"
}
]
}
If you move the files, make sure you also update _Layout.cshtml.
As an alternative (mostly on aesthetics) to Ted Petrou's answer, I found I preferred a slightly more compact listing. Please don't consider accepting it, it's just a much-more-detailed comment on Ted's answer, plus code/data. Python/pandas is not my first/best, but I found this to read well:
df.groupby('group') \
.apply(lambda x: pd.Series({
'a_sum' : x['a'].sum(),
'a_max' : x['a'].max(),
'b_mean' : x['b'].mean(),
'c_d_prodsum' : (x['c'] * x['d']).sum()
})
)
a_sum a_max b_mean c_d_prodsum
group
0 0.530559 0.374540 0.553354 0.488525
1 1.433558 0.832443 0.460206 0.053313
I find it more reminiscent of dplyr
pipes and data.table
chained commands. Not to say they're better, just more familiar to me. (I certainly recognize the power and, for many, the preference of using more formalized def
functions for these types of operations. This is just an alternative, not necessarily better.)
I generated data in the same manner as Ted, I'll add a seed for reproducibility.
import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df
a b c d group
0 0.374540 0.950714 0.731994 0.598658 0
1 0.156019 0.155995 0.058084 0.866176 0
2 0.601115 0.708073 0.020584 0.969910 1
3 0.832443 0.212339 0.181825 0.183405 1
or you can use java 8 lambda
test.removeIf(i -> i==2);
it will simply remove all object that meet the condition
RewriteEngine On
RewriteRule ^(wordpress)($|/) - [L]
An option which doesn't require a subshell and is built in to bash
(pushd SOME_PATH && run_stuff; popd)
Demo:
$ pwd
/home/abhijit
$ pushd /tmp # directory changed
$ pwd
/tmp
$ popd
$ pwd
/home/abhijit
One possibility is using incorrect JDBC URL. make sure it is jdbc:h2:mem:testdb
The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.
You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:
In computers, these two actions are represented by two different characters - carriage return is CR
, ASCII character 13, vbCr
; line feed is LF
, ASCII character 10, vbLf
. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF
-- to start a new line, and so the CRLF
combination -- vbCrLf
-- became a traditional line ending sequence, in some computing environments.
The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF
alone (used in Unix and Macintoshes), CR
alone (apparently used in older Mac OSes) and the CRLF
combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode
, where any CRLF
pair read from the file was converted to a single CR
(and vice versa when writing).
So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine
which means someone else has decided for you which to use, and future portability issues should be reduced.
I had a similar issue today. It was caused by skype! A recent update to skype had re-enabled port 80 and 443 as alternatives to incoming connections.
H/T : http://www.codeproject.com/Questions/549157/unableplustoplusstartplusdebuggingplusonplustheplu
To disable, go to skype > options > Advanced > Connections and uncheck "Use port 80 and 443 as alternatives to incoming connections"
In response to the post starting:
If you want to use this with command line or function arguments...
with the code:
size=${#1}
There might be the case where you just want to check for a zero length argument and have no need to store a variable. I believe you can use this sort of syntax:
if [ -z "$1" ]; then
#zero length argument
else
#non-zero length
fi
See GNU and wooledge for a more complete list of Bash conditional expressions.
A more elegant way I found to achieve this behaviour is simply:
<div id="{{ 'object-' + myScopeObject.index }}"></div>
For my implementation I wanted each input element in a ng-repeat to each have a unique id to associate the label with. So for an array of objects contained inside myScopeObjects one could do this:
<div ng-repeat="object in myScopeObject">
<input id="{{object.name + 'Checkbox'}}" type="checkbox">
<label for="{{object.name + 'Checkbox'}}">{{object.name}}</label>
</div>
Being able to generate unique ids on the fly can be pretty useful when dynamically adding content like this.
Any crawler or spider will read your index.htm
or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm
or equivalent file, it will not list all the files in such folder.
If by mistake, the programmer never included an index.htm
file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/
and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.
Except, of course, if they can enter your FTP or access your site control panel.
I think there's a simpler solution: Just use the DialogInterface
argument that is passed to the onClick
method.
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
See, for example, http://www.mkyong.com/android/android-alert-dialog-example.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
Difference between == (equal) and === (identical equal)
PHP provides two comparison operators to check equality of two values. The main difference between of these two is that '=='
checks if the values of the two operands are equal or not
. On the other hand, '==='
checks the values as well as the type of operands are equal or not
.
== (Equal)
=== (Identical equal)
Example =>
<?php
$val1 = 1234;
$val2 = "1234";
var_dump($val1 == $val2);// output => bool(true)
//It checks only operands value
?>
<?php
$val1 = 1234;
$val2 = "1234";
var_dump($val1 === $val2);// output => bool(false)
//First it checks type then operands value
?>
if we type cast $val2 to (int)$val2 or (string)$val1 then it returns true
<?php
$val1 = 1234;
$val2 = "1234";
var_dump($val1 === (int)$val2);// output => bool(true)
//First it checks type then operands value
?>
OR
<?php
$val1 = 1234;
$val2 = "1234";
var_dump($val1 === (int)$val2);// output => bool(true)
//First it checks type then operands value
?>
You can configure logging in your settings.py
file.
One example:
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.
If you can't use any libraries to encode the value, http://www.urlencoder.org/ or http://www.urlencode-urldecode.com/ or ...
Just enter your value "M&M", not the full URL ;-)
The padding inside a table-divider (TD) is a padding property applied to the cell itself.
CSS
td, th {padding:0}
The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.
CSS
table, td, th {border-collapse:separate}
table {border-spacing:6px}
Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )
As stated, all objects in sharepoint contain some sort of unique identifier (often an integer based counter for list items, and GUIDs for lists).
That said, there is also a feature available at http://www.codeplex.com/features called "Unique Column Policy", designed to add an other column with a unique value. A complete writeup is available at http://scothillier.spaces.live.com/blog/cns!8F5DEA8AEA9E6FBB!293.entry
The presence of the n
option attached to the -k5
causes the global -r
option to be ignored for that field. You have to specify both n
and r
at the same level (globally or locally).
sort -t $'\t' -k5,5rn
or
sort -rn -t $'\t' -k5,5
Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component
in Parent Function Component we will have :
import React, { useState, useEffect } from "react";
then
const [childData, setChildData] = useState("");
and passing setChildData (which do a job similar to this.setState in Class Components) to Child
return( <ChildComponent passChildData={setChildData} /> )
in Child Component first we get the receiving props
function ChildComponent(props){ return (...) }
then you can pass data anyhow like using a handler function
const functionHandler = (data) => {
props.passChildData(data);
}
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.
You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.
Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.
Maybe I'm being a little pedantic on this :-P
After about seven years, here's a more elegant answer using collections.deque
:
def ngrams(words, n):
d = collections.deque(maxlen=n)
d.extend(words[:n])
words = words[n:]
for window, word in zip(itertools.cycle((d,)), words):
print(' '.join(window))
d.append(word)
words = ['I', 'am', 'become', 'death,', 'the', 'destroyer', 'of', 'worlds']
Output:
In [15]: ngrams(words, 3)
I am become
am become death,
become death, the
death, the destroyer
the destroyer of
In [16]: ngrams(words, 4)
I am become death,
am become death, the
become death, the destroyer
death, the destroyer of
In [17]: ngrams(words, 1)
I
am
become
death,
the
destroyer
of
In [18]: ngrams(words, 2)
I am
am become
become death,
death, the
the destroyer
destroyer of
Use master.dbo.fnbintohexstr(16777215)
to convert to a varchar
representation.
Google is my friend and it showed me this page:
What about :
import platform
h = platform.uname()[1]
Actually you may want to have a look to all the result in platform.uname()
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
If you really must use jQuery to solve this problem (NB: you shouldn't):
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!
For extra fun, the array return is generated by calling the function recursively based on the array's length :)
Working demo at http://jsfiddle.net/2eyQX/
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.
The right approach is
<template>
<div> <!-- The root -->
<p></p>
<p></p>
</div>
</template>
The wrong approach
<template> <!-- No root Element -->
<p></p>
<p></p>
</template>
Multi Root Components
The way around to that problem is using functional components, they are components where you have to pass no reactive data means component will not be watching for any data changes as well as not updating it self when something in parent component changes.
As this is a work around it comes with a price, functional components don't have any life cycle hooks passed to it, they are instance less as well you cannot refer to this
anymore and everything is passed with context.
Here is how you can create a simple functional component.
Vue.component('my-component', {
// you must set functional as true
functional: true,
// Props are optional
props: {
// ...
},
// To compensate for the lack of an instance,
// we are now provided a 2nd context argument.
render: function (createElement, context) {
// ...
}
})
Now that we have covered functional components in some detail lets cover how to create multi root components, for that I am gonna present you with a generic example.
<template>
<ul>
<NavBarRoutes :routes="persistentNavRoutes"/>
<NavBarRoutes v-if="loggedIn" :routes="loggedInNavRoutes" />
<NavBarRoutes v-else :routes="loggedOutNavRoutes" />
</ul>
</template>
Now if we take a look at NavBarRoutes template
<template>
<li
v-for="route in routes"
:key="route.name"
>
<router-link :to="route">
{{ route.title }}
</router-link>
</li>
</template>
We cant do some thing like this we will be violating single root component restriction
Solution Make this component functional and use render
{
functional: true,
render(h, { props }) {
return props.routes.map(route =>
<li key={route.name}>
<router-link to={route}>
{route.title}
</router-link>
</li>
)
}
Here you have it you have created a multi root component, Happy coding
Reference for more details visit: https://blog.carbonteq.com/vuejs-create-multi-root-components/
This matches everything up to ".txt" (without including it):
^.*(?=(\.txt))
There is also an easier way to access the view instead of dealing with the nib as an array.
1) Create a custom View subclass with any outlets that you want to have access to later. --MyView
2) in the UIViewController that you want to load and handle the nib, create an IBOutlet property that will hold the loaded nib's view, for instance
in MyViewController (a UIViewController subclass)
@property (nonatomic, retain) IBOutlet UIView *myViewFromNib;
(dont forget to synthesize it and release it in your .m file)
3) open your nib (we'll call it 'myViewNib.xib') in IB, set you file's Owner to MyViewController
4) now connect your file's Owner outlet myViewFromNib to the main view in the nib.
5) Now in MyViewController, write the following line:
[[NSBundle mainBundle] loadNibNamed:@"myViewNib" owner:self options:nil];
Now as soon as you do that, calling your property "self.myViewFromNib" will give you access to the view from your nib!
You can take this trick to use only qplot. Use inner variable $mapping
. You can even add colour= to your plots so this will be putted in mapping too, and then your plots combined with legend and colors automatically.
cpu_metric2 <- qplot(y=Y2,x=X1)
cpu_metric1 <- qplot(y=Y1,
x=X1,
xlab="Time", ylab="%")
combined_cpu_plot <- cpu_metric1 +
geom_line() +
geom_point(mapping=cpu_metric2$mapping)+
geom_line(mapping=cpu_metric2$mapping)
This is a pretty good introductory video: http://vimeo.com/22685608
If you are looking for more on Rails and Backbone, Thoughtbot has this pretty good book (not free): https://workshops.thoughtbot.com/backbone-js-on-rails
(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});
I tried $('#'+id).off().on(...)
, but it wouldn't work to reset the onClick attribute every time it was called to be reset.
I use .on('click',function(){...});
to stay away from having to quote block all my javascript functions.
The O.P. could now use:
$(this).removeAttr('onclick').off('click').on('click', function(){
displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this);
});
Where this came through for me is when my div was set with the onClick attribute set statically:
<div onclick = '...'>
Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});
.
Without the off('click') my onClick listeners were being appended not replaced.
It's also worth noting that ActiveX controls only work in Windows, whereas Form Controls will work on both Windows and MacOS versions of Excel.
It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.
If you want to emulate private variables for some reason, you can always use the __
prefix from PEP 8. Python mangles the names of variables like __foo
so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).
By the same convention, the _
prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo
or _bar
.
next:
select * from foo where id = (select min(id) from foo where id > 4)
previous:
select * from foo where id = (select max(id) from foo where id < 4)
random.sample()
also works on text
example:
> text = open("textfile.txt").read()
> random.sample(text, 5)
> ['f', 's', 'y', 'v', '\n']
\n is also seen as a character so that can also be returned
you could use random.sample()
to return random words from a text file if you first use the split method
example:
> words = text.split()
> random.sample(words, 5)
> ['the', 'and', 'a', 'her', 'of']
There is no reason not to use C <stdio.h>
in C++, and in fact it is often the optimal choice.
#include <stdio.h>
int
main() // (void) not necessary in C++
{
int c;
while ((c = getchar()) != EOF) {
// do something with 'c' here
}
return 0; // technically not necessary in C++ but still good style
}
I did not read all of the answers, but I did not find the answer I was looking for.
I use Python and don't want to do find/replace or 'blank operations' each time I want to compile code...
So the best solution for me is that it happens on the fly!
Here is the simple solution I found:
Go to:
Empty lists evaluate to False in boolean contexts (such as if some_list:
).
You don't actually need the bundle as the ADT can be used with just any latest Eclipse IDE.
Download latest eclipse.
Download latest ADT plugin ADT-XX.X.X.zip
. As of this answer the current version is ADT-23.0.7.zip (More versions at http://developer.android.com/tools/sdk/eclipse-adt.html)
Open Eclipse and follow the following steps:
Help
> Install New Software
> Add
> Archive
Developer Tools
, click Next
, accept any licenses and Finish
After restarting Eclipse, if you are not able to open a layout file go to step 4 but instead of selecting archive add https://dl-ssl.google.com/android/eclipse/ in the Location:
textbox. Press Ok
, update the ADT and restart Eclipse. Close and reopen the layout files and you'll be good to go.
Run the Android SDK Manager to update its components.
https://developer.android.com/studio/tools/sdk/eclipse-adt.html
img {
max-width:100%;
}
div {
width:100px;
}
with this snippet you can do it in a more efficient way
Here's a solution for people who prefer to do it all by auto layout:
In Size Inspector:
Set content compression resistance priority vertical to 1000.
Lower the priority of constraint height by click "Edit" in Constraints. Just make it less than 1000.
In Attributes Inspector:
Shows the Computer Name, Use a Button to call it
Dim strHostName As String
strHostName = System.Net.Dns.GetHostName(). MsgBox(strHostName)
Shows the User Name, Use a Button to call it
If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
Dim parts() As String = Split(My.User.Name, "\") Dim username As String = parts(1) MsgBox(username) End If
For IP Address its little complicated, But I try to explain as much as I can. First write the next code, before Form1_Load but after import section
Public Class Form1
Dim mem As String Private Sub GetIPAddress() Dim strHostName As String Dim strIPAddress As String strHostName = System.Net.Dns.GetHostName() strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() mem = strIPAddress MessageBox.Show("IP Address: " & strIPAddress) End Sub
Then in Form1_Load Section just call it
GetIPAddress()
Result: On form load it will show a msgbox along with the IP address, for put into Label1.text or some where else play with the code.
One liner which works for all Android versions:
adb shell 'cat `pm path com.example.name | cut -d':' -f2`' > app.apk
The trick is to know the content id of the Image mime part when building the html body part. It boils down to making the img tag
https://github.com/horde/horde/blob/master/kronolith/lib/Kronolith.php
Look at the function buildMimeMessage for a working example.
How about this...?
TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);
This was taken from the MSDN docs for XDocument.Load, found here...
Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"
Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.
In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.
So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.
This error message (SCRIPT5: Access is denied.) can also be encountered if the target page of a .replace method is not found (I had entered the page name incorrectly). I know because it just happened to me, which is why I went searching for some more information about the meaning of the error message.
Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.
//Create my object
var my_jsondata = new
{
Host = @"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string json_data = JsonConvert.SerializeObject(my_jsondata);
//Print the Json object
Console.WriteLine(json_data);
//Parse the json object
JObject json_object = JObject.Parse(json_data);
//Print the parsed Json object
Console.WriteLine((string)json_object["Host"]);
Console.WriteLine((string)json_object["UserName"]);
Console.WriteLine((string)json_object["Password"]);
Console.WriteLine((string)json_object["SourceDir"]);
Console.WriteLine((string)json_object["FileName"]);
Here's a simple unix2dos.bat file that preserves blank lines and exclamation points:
@echo off
setlocal DisableDelayedExpansion
for /f "tokens=1,* delims=:" %%k in ('findstr /n "^" %1') do echo.%%l
The output goes to standard out, so redirect unix2dos.bat output to a file if so desired.
It avoids the pitfalls of other previously proposed for /f batch loop solutions by:
1) Working with delayed expansion off, to avoid eating up exclamation marks.
2) Using the for /f tokenizer itself to remove the line number from the findstr /n
output lines.
(Using findstr /n is necessary to also get blank lines: They would be dropped if for /f read directly from the input file.)
But, as Jeb pointed out in a comment below, the above solution has one drawback the others don't: It drops colons at the beginning of lines.
So 2020-04-06 update just for fun, here's another 1-liner based on findstr.exe, that seems to work fine without the above drawbacks:
@echo off
setlocal DisableDelayedExpansion
for /f "tokens=* delims=0123456789" %%l in ('findstr /n "^" %1') do echo%%l
The additional tricks are:
3) Use digits 0-9 as delimiters, so that tokens=*
skips the initial line number.
4) Use the colon, inserted by findstr /n
after the line number, as the token separator after the echo command.
I'll leave it to Jeb to explain if there are corner cases where echo:something
might fail :-)
All I can say is that this last version successfully restored line endings on my huge batch library, so exceptions, if any, must be quite rare!
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
Try this:
jQuery('#main').css('opacity', '0.6');
or
jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});
if you want to support IE7, IE8 and so on.
Please use the Pandas to_numpy()
method. Below is an example--
>>> import pandas as pd
>>> df = pd.DataFrame({"A":[1, 2], "B":[3, 4], "C":[5, 6]})
>>> df
A B C
0 1 3 5
1 2 4 6
>>> s_array = df[["A", "B", "C"]].to_numpy()
>>> s_array
array([[1, 3, 5],
[2, 4, 6]])
>>> t_array = df[["B", "C"]].to_numpy()
>>> print (t_array)
[[3 5]
[4 6]]
Hope this helps. You can select any number of columns using
columns = ['col1', 'col2', 'col3']
df1 = df[columns]
Then apply to_numpy()
method.
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
You have to aggregate by anything NOT IN
the group by
clause.
So,there are two options...Add Credit_Initial and Disponible_v to the group by
OR
Change them to MAX( Credit_Initial ) as Credit_Initial, MAX( Disponible_v ) as Disponible_v
if you know the values are constant anyhow and have no other impact.
Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
Tuple<string, string> tuple = new Tuple<string, string>(
(string)values[0], (string)values[1]);
return (object)tuple;
}
}
// ...
public void OnExecute(object parameter)
{
var param = (Tuple<string, string>) parameter;
}
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
I solved the problem with the following steps:
Open "services.msc" from command / Windows RUN.
Find the service (which is greyed out).
Double click on that service and go to the "Recovery" tab.
Ensure that
and Press OK.
Now, the service will not try to restart and you can able to delete the greyed out service from services list (i.e. greyed out will be gone).
Let me add my 2¢, it's my job to get good and clean data for a hedge-fund, I've seen quite a lot of data feeds and historical data providers. This is mainly about US stock data.
To start with, if you have some money don't bother with downloading data from Yahoo, get the end of day data straight from CSI data, this is where Yahoo gets their EOD data as well AFAIK. They have an API where you can extract the data to whatever format you want. I think the yearly subscription for data is a few $100 bucks.
The main problem with downloading data from a free service is that you only get stocks that still exist, this is called Survivorship Bias and can give you wrong results if you look at many stocks, because you'll only include the ones that made it so far and not the ones that were de-listed.
For playing around with some intraday data I'd look into IQFeed, they provide several APIs to extract historical data, although they are mainly an outfit for real-time feeds. But here there are quite a few options, some brokers even provide historical data downloads via their APIs, so just pick your poison.
BUT usually all of this data is not very clean, once you really start back testing you'll see that certain stocks are missing or appear as two different symbols, or stock splits are not properly accounted for, etc. And then you realize that historical dividend data is need as well and so you start running in circles, patching data together from 100 different data sources and so on. So to start with a "discount" data feed will do, but as soon as you run more comprehensive backtests you might run into problems depending on what you do. If you just look at, let's say, the S&P 500 stocks this will not be so much a problem though and a "cheap" intraday feed will do.
What you will not find is free intraday data. I mean you might find some examples, I'm sure there's somewhere 5 years of MSFT tick data floating around but that will not get you very far.
Then, if you need the real stuff (level II order book, all ticks as they have happened at all exchanges) one "affordable", yet excellent option is Nanex. They'll actually ship you a drive with terabytes of data. If I remember right its about $3k-4K per year of data. But trust me, once you understand how hard it is to get good intraday data, you won't think this is very much money at all.
Not to discourage you but to get good data is hard, so hard in fact that many hedge-funds and banks spend hundreds of thousands of dollars a month to get data they can trust. Again, you can start somewhere and then go from there but it's good to see it a bit in context.
Edit: The answer above is from my own experience. This write-up from Caltech about available data feeds will give more insights, and especially recommends QuantQuote.
py2exe works with Python 2.7 (as well as other versions). You just need the MSVCR90.dll
<a href="http://twitter.com/me" class="twitterbird" title="Twitter link"></a>
use a class for the link itself and forget the div
.twitterbird {
margin-bottom: 10px;
width: 160px;
height:160px;
display:block;
background:transparent url('twitterbird.png') center top no-repeat;
}
.twitterbird:hover {
background-image: url('twitterbird_hover.png');
}
Alternatively you can use cmder
which lets you add aliases just like linux:
alias subl="C:\Program Files\Sublime Text 3\subl.exe" $*
Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.
Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).
function append_output(suffix, value) {
$("#output_"+suffix).append(value)
}
function kickOff() {
let start = new Promise((resolve, reject) => {
append_output("now", "start")
resolve("start")
})
let middle = new Promise((resolve, reject) => {
setTimeout(() => {
append_output("now", " middle")
resolve(" middle")
}, 1000)
})
let end = new Promise((resolve, reject) => {
append_output("now", " end")
resolve(" end")
})
Promise.all([start, middle, end]).then(results => {
results.forEach(
result => append_output("later", result))
})
}
kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
I was also missing proxy in above answer. I used get_ip_address_from_request
from django_easy_timezones.
from easy_timezones.utils import get_ip_address_from_request, is_valid_ip, is_local_ip
ip = get_ip_address_from_request(request)
try:
if is_valid_ip(ip):
geoip_record = IpRange.objects.by_ip(ip)
except IpRange.DoesNotExist:
return None
And here is method get_ip_address_from_request
, IPv4 and IPv6 ready:
def get_ip_address_from_request(request):
""" Makes the best attempt to get the client's real IP or return the loopback """
PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.')
ip_address = ''
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
if x_forwarded_for and ',' not in x_forwarded_for:
if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for):
ip_address = x_forwarded_for.strip()
else:
ips = [ip.strip() for ip in x_forwarded_for.split(',')]
for ip in ips:
if ip.startswith(PRIVATE_IPS_PREFIX):
continue
elif not is_valid_ip(ip):
continue
else:
ip_address = ip
break
if not ip_address:
x_real_ip = request.META.get('HTTP_X_REAL_IP', '')
if x_real_ip:
if not x_real_ip.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_real_ip):
ip_address = x_real_ip.strip()
if not ip_address:
remote_addr = request.META.get('REMOTE_ADDR', '')
if remote_addr:
if not remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr):
ip_address = remote_addr.strip()
if not ip_address:
ip_address = '127.0.0.1'
return ip_address
I had the same problem and the best solution I found is to first create the table defining primary key and then to use insert into statement.
CREATE TABLE mytable (
field1 INTEGER PRIMARY KEY,
field2 TEXT
);
INSERT INTO mytable
SELECT field1, field2
FROM anothertable;
For Web API 2, you can implement IHttpActionResult
. Here's mine:
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
class FileResult : IHttpActionResult
{
private readonly string _filePath;
private readonly string _contentType;
public FileResult(string filePath, string contentType = null)
{
if (filePath == null) throw new ArgumentNullException("filePath");
_filePath = filePath;
_contentType = contentType;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(_filePath))
};
var contentType = _contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(_filePath));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return Task.FromResult(response);
}
}
Then something like this in your controller:
[Route("Images/{*imagePath}")]
public IHttpActionResult GetImage(string imagePath)
{
var serverPath = Path.Combine(_rootPath, imagePath);
var fileInfo = new FileInfo(serverPath);
return !fileInfo.Exists
? (IHttpActionResult) NotFound()
: new FileResult(fileInfo.FullName);
}
And here's one way you can tell IIS to ignore requests with an extension so that the request will make it to the controller:
<!-- web.config -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
Bulk user creation with set_password
I you are creating several test users, bulk_create
is much faster, but we can't use create_user
with it.
set_password
is another way to generate the hashed passwords:
def users_iterator():
for i in range(nusers):
is_superuser = (i == 0)
user = User(
first_name='First' + str(i),
is_staff=is_superuser,
is_superuser=is_superuser,
last_name='Last' + str(i),
username='user' + str(i),
)
user.set_password('asdfqwer')
yield user
class Command(BaseCommand):
def handle(self, **options):
User.objects.bulk_create(iter(users_iterator()))
Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django
Tested in Django 1.9.
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
@FXML
ImageView image;
@Override
public void initialize(URL url, ResourceBundle rb) {
image.setImage(new Image ("/about.jpg"));
}
I'm coming late in the game but I tried all of the solutions above! couldn't get it to drop the zero's in the parameter and give me a default (it ignored the formatting or appeared blank). I was using SSRS 2005 so was struggling with its clunky / buggy issues.
My workaround was to add a column to the custom [DimDate] table in my database that I was pulling dates from. I added a column that was a string representation in the desired format of the [date] column. I then created 2 new Datasets in SSRS that pulled in the following queries for 2 defaults for my 'To' & 'From' date defaults -
'from'
SELECT Datestring
FROM dbo.dimDate
WHERE [date] = ( SELECT MAX(date)
FROM dbo.dimdate
WHERE date < DATEADD(month, -3, GETDATE()
)
'to'
SELECT Datestring
FROM dbo.dimDate
WHERE [date] = ( SELECT MAX(date)
FROM dbo.dimdate
WHERE date <= GETDATE()
)
My guess is that you don't really want to GROUP BY
some_product.
The answer to: "Is there a way to GROUP BY
a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY
a column alias.
The SELECT
clause, where column aliases are assigned, is not processed until after the GROUP BY
clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.
Inline view:
select ...
from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... ) T
group by some_product ...
CTE:
with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
from ...
group by col1, col2 ... )
select ...
from T
group by some_product ...
Adding to the solutions of others, I'd like to suggest using the plotly
package for R
, as this has worked well for me.
Below, I'm using the reformatted dataset suggested above, from xyz-tripplets to axis vectors x and y and a matrix z:
x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z
library(plotly)
plot_ly(x=x,y=y,z=z, type="surface")
The rendered surface can be rotated and scaled using the mouse. This works fairly well in RStudio.
You can also try it with the built-in volcano
dataset from R
:
plot_ly(z=volcano, type="surface")
AudioToolbox now presents the kSystemSoundID_Vibrate
as a SystemSoundID
type, so the code is:
import AudioToolbox.AudioServices
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
Instead of having to go thru the extra cast step
(Props to @Dov)
And, here's how you do it on Swift (in case you ran into the same trouble as I did)
Link against AudioToolbox.framework
(Go to your project, select your target, build phases, Link Binary with Libraries, add the library there)
Once that is completed:
import AudioToolbox.AudioServices
// Use either of these
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
The cheesy thing is that SystemSoundID
is basically a typealias
(fancy swift typedef
) for a UInt32
, and the kSystemSoundID_Vibrate
is a regular Int
. The compiler gives you an error for trying to cast from Int
to UInt32
, but the error reads as "Cannot convert to SystemSoundID", which is confusing. Why didn't apple just make it a Swift enum is beyond me.
@aponomarenko's goes into the details, my answer is just for the Swifters out there.
Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.
If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.
<form class='frmUpload'>
<input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>
<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>
<div id='imgTwoForJPG'></div>
<script>
window.picUpload = function(frmData) {
console.log("picUpload ran: " + frmData);
var allObjtProperties = '';
for (objProprty in frmData) {
console.log(objProprty + " : " + frmData[objProprty]);
allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};
document.getElementById('allImgProperties').innerHTML = allObjtProperties;
var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");
var img = new Image;
img.src = URL.createObjectURL(frmData);
console.log('img: ' + img);
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var wdthHghtRatio = picHeight/picWidth;
console.log('wdthHghtRatio: ' + wdthHghtRatio);
if (Number(picWidth) > 400) {
var newHeight = Math.round(Number(400) * wdthHghtRatio);
} else {
return false;
};
document.getElementById('cnvsForFormat').height = newHeight;
console.log('width: 400 h: ' + newHeight);
//You must change the width and height settings in order to decrease the image size, but
//it needs to be proportional to the original dimensions.
console.log('This is BEFORE the DRAW IMAGE');
ctx.drawImage(img,0,0, 400, newHeight);
console.log('THIS IS AFTER THE DRAW IMAGE!');
//Even if original image is jpeg, getting data out of the canvas will default to png if not specified
var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
//The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};
</script>
Here is a jsFiddle:
jsFiddle Pick, display, get properties, and Re-size an image file
In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.
var sqlCommand = new SqlCommand("SELECT * FROM mytable WHERE start_time >= @StartTime");
sqlCommand.Parameters.Add("@StartTime", SqlDbType.DateTime);
sqlCommand.Parameters("@StartTime").Value = MyDateObj;
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
To Answer the question:
Why can't the container component call the async API, and then dispatch the actions?
I would say for at least two reasons:
The first reason is the separation of concerns, it's not the job of the action creator
to call the api
and get data back, you have to have to pass two argument to your action creator function
, the action type
and a payload
.
The second reason is because the redux store
is waiting for a plain object with mandatory action type and optionally a payload
(but here you have to pass the payload too).
The action creator should be a plain object like below:
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
And the job of Redux-Thunk midleware
to dispache
the result of your api call
to the appropriate action
.
The array declaration should be:
Car[] garage = new Car[100];
You can also just assign directly:
garage[1] = new Car("Blue");
Use the 'And' keyword for a logical and. Like this:
If Not ((filename = testFileName) And (fileName <> "")) Then
m.put(null,null); // here key=null, value=null
m.put(null,a); // here also key=null, and value=a
Duplicate keys are not allowed in hashmap.
However,value can be duplicated.
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf
The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:
Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.
So you could create a marker as suggested by the question above:
L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick);
Then create the onClick function:
function onClick(e) {
alert(this.getLatLng());
}
Now anytime you mouseover that marker it will fire an alert of the current lat/long.
However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:
L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {
console.log(e.latlng);
});
Here is the documentation: http://leafletjs.com/reference.html#events
For Linux:
git add *
git commit -a --message "Initial Push All"
git push -u origin --all
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
Just change your bind statement from what you have to => this.delta = this.delta.bind(this);
You can use SQL Bulk Insert Statement
BULK INSERT TableName
FROM 'filePath'
WITH
(
FIELDTERMINATOR = '','',
ROWTERMINATOR = ''\n'',
ROWS_PER_BATCH = 10000,
FIRSTROW = 2,
TABLOCK
)
for more reference check
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sql%20bulk%20insert
You Can Also Bulk Insert Your data from Code as well
for that Please check below Link:
http://www.codeproject.com/Articles/439843/Handling-BULK-Data-insert-from-CSV-to-SQL-Server
Try SELECT CAST(field1 AS DECIMAL(10,2)) field1
and replace 10,2
with whatever precision you need.
I solved the problem by enabling the mod_autoindex
from Apache. It was disabled by default.
sudo a2enmod autoindex
All you will have to do is
class BatchCollection(dict):
def __init__(self, *args, **kwargs):
dict.__init__(*args, **kwargs)
OR
class BatchCollection(dict):
def __init__(self, inpt={}):
super(BatchCollection, self).__init__(inpt)
A sample usage for my personal use
### EXAMPLE
class BatchCollection(dict):
def __init__(self, inpt={}):
dict.__init__(*args, **kwargs)
def __setitem__(self, key, item):
if (isinstance(key, tuple) and len(key) == 2
and isinstance(item, collections.Iterable)):
# self.__dict__[key] = item
super(BatchCollection, self).__setitem__(key, item)
else:
raise Exception(
"Valid key should be a tuple (database_name, table_name) "
"and value should be iterable")
Note: tested only in python3
When posting via ajax, it's always a good idea to first submit normally to ensure the file that's called is always returning valid data (json) and no errors with html
tags or other
<form action="path/to/file.php" id="ajaxformx">
By adding x to id value, jquery will not process it.
Once you are sure everything is fine then remove the x
from id="ajaxform"
and the empty the action
attribute value
This is how I sorted the same error for myself just a few minutes ago :)
I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.
CSS auto-fit container between float:left & float:right divs solved my problem, thanks for your comments.
#left
{
width:200px;
float:left;
background-color:antiquewhite;
margin-left:10px;
}
#content
{
overflow:hidden;
margin-left:10px;
background-color:AppWorkspace;
}
There may be an elegant built-in function (but I haven't found it yet). You could write one:
# reorder columns
def set_column_sequence(dataframe, seq, front=True):
'''Takes a dataframe and a subsequence of its columns,
returns dataframe with seq as first columns if "front" is True,
and seq as last columns if "front" is False.
'''
cols = seq[:] # copy so we don't mutate seq
for x in dataframe.columns:
if x not in cols:
if front: #we want "seq" to be in the front
#so append current column to the end of the list
cols.append(x)
else:
#we want "seq" to be last, so insert this
#column in the front of the new column list
#"cols" we are building:
cols.insert(0, x)
return dataframe[cols]
For your example: set_column_sequence(df, ['x','y'])
would return the desired output.
If you want the seq at the end of the DataFrame instead simply pass in "front=False".
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
The following solution might be a better one to follow. the layout is in fragment_my.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="listener"
type="my_package.MyListener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/moreTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{() -> listener.onClick()}"
android:text="@string/login"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return FragmentMyBinding.inflate(
inflater,
container,
false
).apply {
lifecycleOwner = viewLifecycleOwner
listener = this@MyFragment
}.root
}
override fun onClick() {
TODO("Not yet implemented")
}
}
interface MyListener{
fun onClick()
}
Try this
div#ImageContainer { width: 600px; }
#ImageContainer img{ max-width: 600px}
You need run visudo
and in the editor that it opens write:
igor ALL=(ALL) ALL
That line grants all permissions to user igor
.
If you want permit to run only some commands, you need to list them in the line:
igor ALL=(ALL) /bin/kill, /bin/ps
For me, the object definitely existed and was uploaded correctly, however, its s3 url still threw the same error:
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
I found out that the reason was because my filename contained a #
symbol, and I guess certain characters or symbols will also cause this error.
Removing this character and generating the new s3 url resolved my issue.
This is my benchmark results
test 4,267,740 ops/sec ±1.32% (60 runs sampled)
exec 3,649,719 ops/sec ±2.51% (60 runs sampled)
match 3,623,125 ops/sec ±1.85% (62 runs sampled)
indexOf 6,230,325 ops/sec ±0.95% (62 runs sampled)
test method is faster than the match method, but the fastest method is the indexOf
The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry
With the library you only need to do this:
Blurry.with(context)
.radius(10)
.sampling(8)
.color(Color.argb(66, 255, 255, 0))
.async()
.onto(rootView);
app.use(function(req, res, next) {
var allowedOrigins = [
"http://localhost:4200"
];
var origin = req.headers.origin;
console.log(origin)
console.log(allowedOrigins.indexOf(origin) > -1)
// Website you wish to allow to
if (allowedOrigins.indexOf(origin) > -1) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type,Authorization"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
Add this code in your index.js or server.js file and change the allowed origin array according to your requirement.
PUT ing
PUT /binders/{id}/docs
Create or update, and relate a single document to a binder
e.g.:
PUT /binders/1/docs HTTP/1.1
{
"docNumber" : 1
}
PATCH ing
PATCH /docs
Create docs if they do not exist and relate them to binders
e.g.:
PATCH /docs HTTP/1.1
[
{ "op" : "add", "path" : "/binder/1/docs", "value" : { "doc_number" : 1 } },
{ "op" : "add", "path" : "/binder/8/docs", "value" : { "doc_number" : 8 } },
{ "op" : "add", "path" : "/binder/3/docs", "value" : { "doc_number" : 6 } }
]
I'll include additional insights later, but in the meantime if you want to, have a look at RFC 5789, RFC 6902 and William Durand's Please. Don't Patch Like an Idiot blog entry.
Use the getTime
method to get the time in total milliseconds since 1970-01-01, and subtract those:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
You can use jstat, like :
jstat -gc pid
Full docs here : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html
Have a look on this example
.switch {
width: 50px;
height: 17px;
position: relative;
display: inline-block;
}
.switch input {
display: none;
}
.switch .slider {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
cursor: pointer;
background-color: #e7ecf1;
border-radius: 30px !important;
border: 0;
padding: 0;
display: block;
margin: 12px 10px;
min-height: 11px;
}
.switch .slider:before {
position: absolute;
background-color: #aaa;
height: 15px;
width: 15px;
content: "";
left: 0px;
bottom: -2px;
border-radius: 50%;
transition: ease-in-out .5s;
}
.switch .slider:after {
content: "";
color: white;
display: block;
position: absolute;
transform: translate(-50%,-50%);
top: 50%;
left: 70%;
transition: all .5s;
font-size: 10px;
font-family: Verdana,sans-serif;
}
.switch input:checked + .slider:after {
transition: all .5s;
left: 30%;
content: "";
}
.switch input:checked + .slider {
background-color: #d3d6d9;
}
.switch input:checked + .slider:before {
transform: translateX(15px);
background-color: #26a2ac;
}
_x000D_
<label class="switch">
<input type="checkbox" />
<div class="slider"></div>
</label>
_x000D_
If you print(type(Num.getone))
you will get <class 'function'>
.
It is just a plain function, and be called as usual (with no arguments):
Num.getone() # returns 1 as expected
but if you print print(type(myObj.getone))
you will get <class 'method'>
.
So when you call getone()
from an instance of the class, Python automatically "transforms" the function defined in a class into a method.
An instance method requires the first argument to be the instance object. You can think myObj.getone()
as syntactic sugar for
Num.getone(myObj) # this explains the Error 'getone()' takes no arguments (1 given).
For example:
class Num:
def __init__(self,num):
self.n = num
def getid(self):
return id(self)
myObj=Num(3)
Now if you
print(id(myObj) == myObj.getid())
# returns True
As you can see self
and myObj
are the same object
Another option is using reduce()
and new Map()
to group the array. Use Spread syntax
to convert set object into an array.
var myArray = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}]_x000D_
_x000D_
var result = [...myArray.reduce((c, {group,color}) => {_x000D_
if (!c.has(group)) c.set(group, {group,color: []});_x000D_
c.get(group).color.push(color);_x000D_
return c;_x000D_
}, new Map()).values()];_x000D_
_x000D_
console.log(result);
_x000D_
Can't you just add a reference to System.Web
and then you can use Server.MapPath
?
Edit: Nowadays I'd recommend using the HostingEnvironment.MapPath
Method:
It's a static method in System.Web
assembly that Maps a virtual path to a physical path on the server. It doesn't require a reference to HttpContext
.
In case anyone encountering the same issue, please uninstall scipy and install scipy==1.1.0
$ pip uninstall scipy
$ pip install scipy==1.1.0
Even though that this question was already answered I feel that there are missing examples in the answer that was answered.
Therefore I'll bring here what I wrote in a blog post "Android Log Levels"
Verbose
Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.
Debug
Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.
Info
For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.
Warning
When there is a potentially harmful situation.
This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.
Error
Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.
WTF (What a Terrible Failure)
Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.
You can view GitLab's version at: https://your.domain.name/help
Or via terminal: gitlab-rake gitlab:env:info
Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.
fill_parent
(deprecated and renamed MATCH_PARENT
in API Level 8 and higher)
Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dockstyle of a Windows Form Control to Fill
.
Setting a top level layout or control to fill_parent will force it to take up the whole screen.
wrap_content
Setting a View's size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It's roughly the equivalent of setting a Windows Form Control's Autosize
property to True.
Online Documentation
There's some details in the Android code documentation here.
The Simple Difference is: console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.
process.stdout.write() methods don't append new line character. useful for printing patterns.
I think this should work :
$("textarea#ExampleMessage").val(result.exampleMessage);
i made my own utils. it is handy. :)
package samples.utils;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.ui.context.Theme;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.support.RequestContextUtils;
/**
* SpringMVC????
*
* @author ??([email protected])
*
*/
public final class WebContextHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(WebContextHolder.class);
private static WebContextHolder INSTANCE = new WebContextHolder();
public WebContextHolder get() {
return INSTANCE;
}
private WebContextHolder() {
super();
}
// --------------------------------------------------------------------------------------------------------------
public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attributes.getRequest();
}
public HttpSession getSession() {
return getSession(true);
}
public HttpSession getSession(boolean create) {
return getRequest().getSession(create);
}
public String getSessionId() {
return getSession().getId();
}
public ServletContext getServletContext() {
return getSession().getServletContext(); // servlet2.3
}
public Locale getLocale() {
return RequestContextUtils.getLocale(getRequest());
}
public Theme getTheme() {
return RequestContextUtils.getTheme(getRequest());
}
public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
}
public ApplicationEventPublisher getApplicationEventPublisher() {
return (ApplicationEventPublisher) getApplicationContext();
}
public LocaleResolver getLocaleResolver() {
return RequestContextUtils.getLocaleResolver(getRequest());
}
public ThemeResolver getThemeResolver() {
return RequestContextUtils.getThemeResolver(getRequest());
}
public ResourceLoader getResourceLoader() {
return (ResourceLoader) getApplicationContext();
}
public ResourcePatternResolver getResourcePatternResolver() {
return (ResourcePatternResolver) getApplicationContext();
}
public MessageSource getMessageSource() {
return (MessageSource) getApplicationContext();
}
public ConversionService getConversionService() {
return getBeanFromApplicationContext(ConversionService.class);
}
public DataSource getDataSource() {
return getBeanFromApplicationContext(DataSource.class);
}
public Collection<String> getActiveProfiles() {
return Arrays.asList(getApplicationContext().getEnvironment().getActiveProfiles());
}
public ClassLoader getBeanClassLoader() {
return ClassUtils.getDefaultClassLoader();
}
private <T> T getBeanFromApplicationContext(Class<T> requiredType) {
try {
return getApplicationContext().getBean(requiredType);
} catch (NoUniqueBeanDefinitionException e) {
LOGGER.error(e.getMessage(), e);
throw e;
} catch (NoSuchBeanDefinitionException e) {
LOGGER.warn(e.getMessage());
return null;
}
}
}
If you're really, absolutely positively sure that the NSURL is a file url, i.e. [url isFileURL]
is guaranteed to return true in your case, then you can simply use:
[UIImage imageWithContentsOfFile:url.path]
My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the best program in the world! ");
while (true) {
System.out.print("Enter a query: ");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("q")) {
System.out.println("The program is ending now ....");
break;
} else {
System.out.println("The program is running...");
}
}
}
}
Open Your .htaccess file and enter the following code in
Options -Indexes
Make sure you hit the ENTER key (or RETURN key if you use a Mac) after entering the "Options -Indexes" words so that the file ends with a blank line.
Without using regex
, you can just do:
def get_num(x):
return int(''.join(ele for ele in x if ele.isdigit()))
Result:
>>> get_num(x)
120
>>> get_num(y)
90
>>> get_num(banana)
200
>>> get_num(orange)
300
EDIT :
Answering the follow up question.
If we know that the only period in a given string is the decimal point, extracting a float is quite easy:
def get_num(x):
return float(''.join(ele for ele in x if ele.isdigit() or ele == '.'))
Result:
>>> get_num('dfgd 45.678fjfjf')
45.678
I found I had to be logged in as a domain user.
It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.
Logged in as domain user (but admin on machine) and it accepted the credentials.
Simply do it
sudo apt install php-mysqli
It works perfectly and it is version independent
The requests.Session()
solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token
is required as a hidden field and add it to the payload with the username and password:
import requests
from bs4 import BeautifulSoup
payload = {
'email': '[email protected]',
'password': 'passw0rd'
}
with requests.Session() as sess:
res = sess.get(server_name + '/signin')
signin = BeautifulSoup(res._content, 'html.parser')
payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
res = sess.post(server_name + '/auth/login', data=payload)
In the source header you can declare:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
....
It is described in the PEP 0263:
Then you can use UTF-8 in strings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)
This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).
In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.
There is a way to filter Safari 5+ from Chrome:
@media screen and (-webkit-min-device-pixel-ratio:0) {
/* Safari and Chrome */
.myClass {
color:red;
}
/* Safari only override */
::i-block-chrome,.myClass {
color:blue;
}
}
Here is the simplest solution based on [https://en.wikipedia.org/wiki/Coefficient_of_determination]
# 1. 'Actual' and 'Predicted' data
df <- data.frame(
y_actual = c(1:5),
y_predicted = c(0.8, 2.4, 2, 3, 4.8))
# 2. R2 Score components
# 2.1. Average of actual data
avr_y_actual <- mean(df$y_actual)
# 2.2. Total sum of squares
ss_total <- sum((df$y_actual - avr_y_actual)^2)
# 2.3. Regression sum of squares
ss_regression <- sum((df$y_predicted - avr_y_actual)^2)
# 2.4. Residual sum of squares
ss_residuals <- sum((df$y_actual - df$y_predicted)^2)
# 3. R2 Score
r2 <- 1 - ss_residuals / ss_total
In C++-11 you can do:
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
// access by value, the type of i is int
std::cout << i << ' ';
}
std::cout << '\n';
See here for variations: https://en.cppreference.com/w/cpp/language/range-for
Right click and open SVN Repo-browser:
Right click on Trunk (working copy) and choose Copy to...:
Input the respective branch's name/path:
Click OK, type the respective log message, and click OK.
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_