Swift 5 - Xcode version 12.1 (12A7403)
|Step One|
Add the following to your AppDelegate.swift file
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let colorView = UIView()
colorView.backgroundColor = UIColor.lightGray
UITableViewCell.appearance().selectedBackgroundView = colorView
return true
}
|Step Two|
Make sure your cell's Content View background is set to "Clear Color" (and not "Default") in the Attributes Inspector. This is done to not conflict with your App Delegate setting.
del my_dict[key]
is slightly faster than my_dict.pop(key)
for removing a key from a dictionary when the key exists
>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"
>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786
But when the key doesn't exist if key in my_dict: del my_dict[key]
is slightly faster than my_dict.pop(key, None)
. Both are at least three times faster than del
in a try
/except
statement:
>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
... del d['missing key']
... except KeyError:
... pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133
Edit: This method would not work for comparing binary files!
In .NET 4.0, the File
class has the following two new methods:
public static IEnumerable<string> ReadLines(string path)
public static IEnumerable<string> ReadLines(string path, Encoding encoding)
Which means you could use:
bool same = File.ReadLines(path1).SequenceEqual(File.ReadLines(path2));
You'd see https://docs.python.org/3/howto/descriptor.html#properties
class Property(object):
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("can't delete attribute")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.
I like to use the following to get a nicely sorted listing of the current dir:
> dir . /s /b sortorder:N
One of your best option to debug Django code is via wdb: https://github.com/Kozea/wdb
wdb works with python 2 (2.6, 2.7), python 3 (3.2, 3.3, 3.4, 3.5) and pypy. Even better, it is possible to debug a python 2 program with a wdb server running on python 3 and vice-versa or debug a program running on a computer with a debugging server running on another computer inside a web page on a third computer! Even betterer, it is now possible to pause a currently running python process/thread using code injection from the web interface. (This requires gdb and ptrace enabled) In other words it's a very enhanced version of pdb directly in your browser with nice features.
Install and run the server, and in your code add:
import wdb
wdb.set_trace()
According to the author, main differences with respect to pdb
are:
For those who don’t know the project, wdb is a python debugger like pdb, but with a slick web front-end and a lot of additional features, such as:
- Source syntax highlighting
- Visual breakpoints
- Interactive code completion using jedi
- Persistent breakpoints
- Deep objects inspection using mouse Multithreading / Multiprocessing support
- Remote debugging
- Watch expressions
- In debugger code edition
- Popular web servers integration to break on error
- In exception breaking during trace (not post-mortem) in contrary to the werkzeug debugger for instance
- Breaking in currently running programs through code injection (on supported systems)
It has a great browser-based user interface. A joy to use! :)
There is a parse_dates
parameter for read_csv
which allows you to define the names of the columns you want treated as dates or datetimes:
date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files
First you need to "uncompress" userdata.img
with simg2img
, then you can mount it via the loop device.
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* @param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(String response) {
//Your response here
}
}
That should be your {install path}\data e.g. C:\apps\wamp\bin\mysql\mysql5.5.8\data\{databasename}
You could use a list comprehension or a generator expression instead:
', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
I spent an hour trying to get djsnowsill's answer to work with a database using Mixed Case tables and columns, then finally stumbled upon the solution thanks to a comment from Manuel Darveau, but I thought I could make it a bit clearer for everyone:
CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
EXECUTE format('SELECT setval(pg_get_serial_sequence(''%1$I'', %2$L),
(SELECT COALESCE(MAX(%2$I)+1,1) FROM %1$I), false)',tablename,columnname);
END;
$body$ LANGUAGE 'plpgsql';
SELECT format('%s_%s_seq',table_name,column_name), reset_sequence(table_name,column_name)
FROM information_schema.columns WHERE column_default like 'nextval%';
This has the benefit of:
To explain, the problem was that pg_get_serial_sequence
takes strings to work out what you're referring to, so if you do:
"TableName" --it thinks it's a table or column
'TableName' --it thinks it's a string, but makes it lower case
'"TableName"' --it works!
This is achieved using ''%1$I''
in the format string, ''
makes an apostrophe 1$
means first arg, and I
means in quotes
You can get the window height quite easily in pure CSS, using the units "vh", each corresponding to 1% of the window height. On the example below, let's begin to centralize block.foo by adding a margin-top half the size of the screen.
.foo{
margin-top: 50vh;
}
But that only works for 'window' size. With a dab of javascript, you could make it more versatile.
$(':root').css("--windowHeight", $( window ).height() );
That code will create a CSS variable named "--windowHeight" that carries the height of the window. To use it, just add the rule:
.foo{
margin-top: calc( var(--windowHeight) / 2 );
}
And why is it more versatile than simply using "vh" units? Because you can get the height of any element. Now if you want to centralize a block.foo in any container.bar, you could:
$(':root').css("--containerHeight", $( .bar ).height() );
$(':root').css("--blockHeight", $( .foo ).height() );
.foo{
margin-top: calc( var(--containerHeight) / 2 - var(--blockHeight) / 2);
}
And finally, for it to respond to changes on the window size, you could use (in this example, the container is 50% the window height):
$( window ).resize(function() {
$(':root').css("--containerHeight", $( .bar ).height()*0.5 );
});
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadImage').val();
if(imgVal=='')
{
alert("empty input file");
}
return false;
});
});
</script>
<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
Or you could try:
Combining a variety of elements from the answers here with normalize provides good coverage. Keep the order of operations to incrementally clean the url.
function clean_url(s) {
return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
.toLowerCase()
.replace(/\s+/g, '-') //spaces to dashes
.replace(/&/g, '-and-') //ampersand to and
.replace(/[^\w\-]+/g, '') //remove non-words
.replace(/\-\-+/g, '-') //collapse multiple dashes
.replace(/^-+/, '') //trim starting dash
.replace(/-+$/, ''); //trim ending dash
}
normlize('NFD')
breaks accented characters into their components, which are basic letters plus diacritics (the accent part). replace(/[\u0300-\u036f]/g, "")
purges all the diacritics, leaving the basic letters by themselves. The rest is explained with inline comments.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0)
and substring(0, 1)
will throw a StringIndexOutOfBoundsException
. startsWith
does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
Heads up, you should be using the main thread for this action.
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
if granted {
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
This worked for me.
I created a folder then changed into the folder using CD option from command prompt.
Then executed the jar from there.
d:\LS\afterchange>jar xvf ..\mywar.war
Codes below is my approach under anaconda python 2.7 plus a package name "pydot-ng" to making a PDF file with decision rules. I hope it is helpful.
from sklearn import tree
clf = tree.DecisionTreeClassifier(max_leaf_nodes=n)
clf_ = clf.fit(X, data_y)
feature_names = X.columns
class_name = clf_.classes_.astype(int).astype(str)
def output_pdf(clf_, name):
from sklearn import tree
from sklearn.externals.six import StringIO
import pydot_ng as pydot
dot_data = StringIO()
tree.export_graphviz(clf_, out_file=dot_data,
feature_names=feature_names,
class_names=class_name,
filled=True, rounded=True,
special_characters=True,
node_ids=1,)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("%s.pdf"%name)
output_pdf(clf_, name='filename%s'%n)
I am not sure I understood your question, but if you write:
mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0
This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0
Additionally if someone have a use case where he needs group names before executing search on Regex object he can use:
var regex = new Regex(pattern); // initialized somewhere
// ...
var groupNames = regex.GetGroupNames();
Actually if you want to use this with multi-dimensional arrays you would want to use some recursion.
static public function array_to_object(array $array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
$array[$key] = self::array_to_object($value);
}
}
return (object)$array;
}
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
I know this topic is old, but there are no correct answers.
rotation transform rotates the element from its center, so, a wider element will rotate this way:
Applying overflow: hidden
hides the longest dimension as you can see here:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
}_x000D_
.imagetest{_x000D_
overflow: hidden_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" width=100%/>_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
So, what I do is some calculations, in my example the picture is 455px width and 111px height and we have to add some margins based on these dimensions:
in CSS:
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);
Result:
img{_x000D_
border: 1px solid #000;_x000D_
transform: rotate(270deg);_x000D_
-ms-transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg);_x000D_
-webkit-transform: rotate(270deg);_x000D_
-o-transform: rotate(270deg);_x000D_
/* 455 * 111 */_x000D_
margin: calc((455px - 111px)/2) calc((111px - 455px)/2);_x000D_
}
_x000D_
<article>_x000D_
<section class="photo">_x000D_
<div></div>_x000D_
<div class="imagetest">_x000D_
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSqVNRUwpfOwZ5n4kvVXea2VHd6QZGACVVaBOl5aJ2EGSG-WAIF" />_x000D_
</div>_x000D_
</section>_x000D_
</article>
_x000D_
I hope it helps someone!
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
One way to achieve this is to wrap the API call into a promise and then use await
to wait for the result.
// let's say this is the API function with two callbacks,
// one for success and the other for error
function apiFunction(query, successCallback, errorCallback) {
if (query == "bad query") {
errorCallback("problem with the query");
}
successCallback("Your query was <" + query + ">");
}
// myFunction wraps the above API call into a Promise
// and handles the callbacks with resolve and reject
function apiFunctionWrapper(query) {
return new Promise((resolve, reject) => {
apiFunction(query,(successResponse) => {
resolve(successResponse);
}, (errorResponse) => {
reject(errorResponse);
});
});
}
// now you can use await to get the result from the wrapped api function
// and you can use standard try-catch to handle the errors
async function businessLogic() {
try {
const result = await apiFunctionWrapper("query all users");
console.log(result);
// the next line will fail
const result2 = await apiFunctionWrapper("bad query");
} catch(error) {
console.error("ERROR:" + error);
}
}
// call the main function
businessLogic();
Output:
Your query was <query all users>
ERROR:problem with the query
You can set one of the columns as an index in case it is an "id" for example. In this case the index column will be replaced by one of the columns you have chosen.
df.set_index('id', inplace=True)
Regarding Bruce Adams answer:
Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.
For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.
A makefile segment to explain it:
install:
cp program $DESTDIR$PREFIX/bin/program
Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:
prog.pseudo.in:
open("@prefix@/share/prog.db")
...
prog:
sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
compile prog.pseudo
install:
cp prog $DESTDIR$PREFIX/bin/prog
cp prog.db $DESTDIR$PREFIX/share/prog.db
If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.
Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).
Another way to do it....
$year = '2014';
$month = '02';
$day = '26';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $year . '-' . $month . '-' . $day . '00:00:00');
$day = date('w', $date->getTimestamp());
// 0=Sunday 6=Saturday
if($day!=0){
$newdate = $date->getTimestamp() - $day * 86400; //86400 seconds in a day
// Look for DST change
if($old = date('I', $date->getTimestamp()) != $new = date('I', $newdate)){
if($old == 0){
$newdate -= 3600; //3600 seconds in an hour
} else {
$newdate += 3600;
}
}
$date->setTimestamp($newdate);
}
echo $date->format('D Y-m-d H:i:s');
The following is what I came up with. It's similer to Riccardo C.'s, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.head = None
self.curr = None
self.tail = None
def __iter__(self):
return self
def next(self):
if self.head and not self.curr:
self.curr = self.head
return self.curr
elif self.curr.next:
self.curr = self.curr.next
return self.curr
else:
raise StopIteration
def append(self, data):
n = Node(data)
if not self.head:
self.head = n
self.tail = n
else:
self.tail.next = n
self.tail = self.tail.next
# Add 5 nodes
ll = LinkedList()
for i in range(1, 6):
ll.append(i)
# print out the list
for n in ll:
print n
"""
Example output:
$ python linked_list.py
1
2
3
4
5
"""
Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...
If you use Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
result.class.name.split('::').last
Is the opaque overlay for aesthetic purposes?
If so, you can use:
#overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 50;
background: #000;
pointer-events: none;
opacity: 0.8;
color: #fff;
}
'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.
datamap = eval(input('Provide some data here: '))
means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval
.
ast.literal_eval
raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
Use ast.literal_eval
whenever you need eval
. You shouldn't usually evaluate literal Python statements.
My library Time4J offers a pattern-based solution (similar to Apache DurationFormatUtils
, but more flexible):
Duration<ClockUnit> duration =
Duration.of(-573421, ClockUnit.SECONDS) // input in seconds only
.with(Duration.STD_CLOCK_PERIOD); // performs normalization to h:mm:ss-structure
String fs = Duration.formatter(ClockUnit.class, "+##h:mm:ss").format(duration);
System.out.println(fs); // output => -159:17:01
This code demonstrates the capabilities to handle hour overflow and sign handling, see also the API of duration-formatter based on pattern.
To make Mostafa's answer complete, this is definietly the simplest and most efficient way to do it:
function getDatesFromRange($start_date, $end_date, $date_format = 'Y-m-d')
{
$dates_array = array();
for ($x = strtotime($start_date); $x <= strtotime($end_date); $x += 86400) {
array_push($dates_array, date($date_format, $x));
}
return $dates_array;
}
// see the dates in the array
print_r( getDatesFromRange('2017-02-09', '2017-02-19') );
You can even change the default output date format if you add a third parameter when you call the function, otherwise it will use the default format that's been set as 'Y-m-d'.
I hope it helps :)
A great real-world example of where lazy loading comes in handy is with ORM's (Object Relation Mappers) such as Entity Framework and NHibernate.
Say you have an entity Customer which has properties for Name, PhoneNumber, and Orders. Name and PhoneNumber are regular strings but Orders is a navigation property that returns a list of every order the customer ever made.
You often might want to go through all your customer's and get their name and phone number to call them. This is a very quick and simple task, but imagine if each time you created a customer it automatically went and did a complex join to return thousands of orders. The worst part is that you aren't even going to use the orders so it is a complete waste of resources!
This is the perfect place for lazy loading because if the Order property is lazy it will not go fetch all the customer's order unless you actually need them. You can enumerate the Customer objects getting only their Name and Phone Number while the Order property is patiently sleeping, ready for when you need it.
It seems the answer to your question is no, however one hack you can use is to assign a dummy column to separate each new table. This works especially well if you're looping through a result set for a list of columns in a scripting language such as Python or PHP.
SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1
JOIN table2 ON table2.table1id = table1.id
JOIN table3 ON table3.table1id = table1.id
I realize this doesn't answer your question exactly, but if you're a coder this is a great way to separate tables with duplicate column names. Hope this helps somebody.
In my case I have update compile SDK and build SDK version to 30 and added
requestLegacyPermission=true
in android manifest file, as I was accessing the storage for reading and writing. later when I edited the compile SDK and build SDK version and get back to version 26 then I forgot to remove
requestLegacyPermission=true
in Manifest file.
Reason:
requestLegacyPermission was introduced in Android 10 so that's the reason Manifest was not recognizing this as I updated Compile SDK and Build SDK to 26.
Hello from the future.
For clarity, I just wanted to add (as this was pretty high up in google) - we can now use
<button type="submit">Upload Stuff</button>
And to reset a form
<button type="reset" value="Reset">Reset</button>
Check out button types
We can also attach buttons to submit forms like this:
<button type="submit" form="myform" value="Submit">Submit</button>
Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas so try this code. :
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work. Comenten si les sirvio :)
I wanted to add support for a language that isn't officially supported by iOS (not listed in Language section under system settings). By following the Apple's Internationalization Tutorial and few hints here by Brian Webster and geon, I came up with this piece of code (put it in main.m):
int main(int argc, char * argv[]) {
@autoreleasepool {
// Grab regional settings locale, for Slovenian this is either sl_SI or en_SI
NSLocale *locale = [NSLocale currentLocale];
NSString *ll = [locale localeIdentifier]; // sl_SI
// Grab the first part of language identifier
NSArray *comp = [ll componentsSeparatedByString:@"_"];
NSString *ll1 = @"en";
if (comp.count > 0) {
ll1 = comp[0]; // sl, en, ...
}
// Check if we already saved language (user can manually change it inside app for example)
if (![[NSUserDefaults standardUserDefaults] objectForKey:@"SelectedLanguage"]) {
// Slovenian (Slovenia), Slovenia
if ([ll isEqualToString:@"sl_SI"] || [ll isEqualToString:@"en_SI"]) {
ll1 = @"sl-SI"; // This is the part of localized path for Slovenian language that Xcode generates
}
// Add more unsupported languages here...
[[NSUserDefaults standardUserDefaults] setObject:ll1 forKey:@"SelectedLanguage"]; // Save language
}
else {
// Restore language as we have previously saved it
ll1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"SelectedLanguage"];
}
// Overwrite NSLocalizedString and StoryBoard language preference
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:ll1, @"en", @"fr", nil] forKey:@"AppleLanguages"];
// Make sure settings are stored to disk
[[NSUserDefaults standardUserDefaults] synchronize];
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
This works well for both Storyboard and NSLocalizedString code. The code assumes that user will have an option to manually change language inside app later on.
Of course, don't forget to add proper Storyboard translations and Localizable.strings translations (see link to Apple page above for how to do that).
I'd like to point out the Vaex package.
Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).
Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.
Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.
Most of my points are related to Invariant's answer, so I would suggest to go through it first.
UPDATE
JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.
Old answer with JavaFXPorts
Some bad news first:
Now, some good news:
If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.
Most of the documentation on how to get started can be found here and some of the samples can be found here.
You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).
In the "Abbreviation" field, enter the string that should activate the template (e.g. @a
), and in the "Template Text" area enter the string to complete (e.g. @author - My Name
). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).
I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.
To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding
-Duser.name=Your name
to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.
Restart IntelliJ
I encountered the same credential prompting issue, and did a quick search and nothing on the internet would fix it. It took some time to find the problem, a silly one.
In IIS -> Advance Setting -> Physical Path Credential (is empty)
As soon as i added a machine ID (domain/user) that has access to the VM/server, the password prompting would stop.
Hope this helps
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Just to save some of you time...
On my Galaxy S v.2.3.3 Shared Preferences are not stored in:/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
but are now located in: /dbdata/databases/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
I believe they changed this in 2.3
public String getRealPathFromURI(Uri uri) {
String result;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor == null) {
result = uri.getPath();
cursor.close();
return result;
}
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
return result;
}
Then using to get file from URI :
File finalFile = newFile(getRealPathFromURI(uri));
--HOPE CAN HELP YOU----
By using below method you can convert java.math.BigDecimal to String.
BigDecimal bigDecimal = new BigDecimal("10.0001");
String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
System.out.println("bigDecimal value in String: "+bigDecimalString);
Output:
bigDecimal value in String: 10.0001
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
I'd probably use all.equal
and which
to get the information you want. It's not recommended to use all.equal
in an if...else
block for some reason, so we wrap it in isTRUE()
. See ?all.equal
for more:
foo <- function(A,B){
if (!isTRUE(all.equal(A,B))){
mismatches <- paste(which(A != B), collapse = ",")
stop("error the A and B does not match at the following columns: ", mismatches )
} else {
message("Yahtzee!")
}
}
And in use:
> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) :
error the A and B does not match at the following columns: 2,4
you can populate the data you want with a simple callback function,
let's say we have a list named lst
that we want to populate,
we have a function that pupulates pupulates list,
const lst = [];
const populateData = (data) => {lst.push(data)}
now we can pass the callback function to the function which is making the axios call and we can pupulate the list when we get data from response.
now we make our function that makes the request and pass populateData
as a callback function.
function axiosTest (populateData) {
axios.get(url)
.then(function(response){
populateData(response.data);
})
.catch(function(error){
console.log(error);
});
}
I couldn't find a rationale by the original developers this quickly, but I can give you an educated guess based on a few years of Git experience.
No, not every branch is something you want to push to the outside world. It might represent a private experiment.
Moreover, where should git push
send all the branches? Git can work with multiple remotes and you may want to have different sets of branches on each. E.g. a central project GitHub repo may have release branches; a GitHub fork may have topic branches for review; and a local Git server may have branches containing local configuration. If git push
would push all branches to the remote that the current branch tracks, this kind of scheme would be easy to screw up.
Mathematica nowoadays also offers access to both current and historical stock prices, see http://reference.wolfram.com/mathematica/ref/FinancialData.html , if you happen to have a copy of it.
The problem with your desired output is that it is not valid json document,; it's a stream of json documents!
That's okay, if its what you need, but that means that for each document you want in your output, you'll have to call json.dumps
.
Since the newline you want separating your documents is not contained in those documents, you're on the hook for supplying it yourself. So we just need to pull the loop out of the call to json.dump and interpose newlines for each document written.
import csv
import json
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
json.dump(row, jsonfile)
jsonfile.write('\n')
table {_x000D_
_x000D_
display: block;_x000D_
}_x000D_
_x000D_
thead, tbody {_x000D_
display: block;_x000D_
}_x000D_
tbody {_x000D_
position: absolute;_x000D_
height: 150px;_x000D_
overflow-y: scroll;_x000D_
}_x000D_
td, th {_x000D_
min-width: 100px !important;_x000D_
height: 25px !important;_x000D_
overflow:hidden !important;_x000D_
text-overflow: ellipsis !important;_x000D_
max-width: 100px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container" style="position:fixed;height:180px;overflow-x:scroll;overflow-y:hidden">_x000D_
_x000D_
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Col1</th>_x000D_
<th>Col2</th>_x000D_
<th>Username</th>_x000D_
<th>Password</th>_x000D_
<th>First Name</th>_x000D_
<th>Last Name</th>_x000D_
<th>Col16</th>_x000D_
<th>Col7</th>_x000D_
<th>Col8</th>_x000D_
<th>Col9</th>_x000D_
<th>Col10</th>_x000D_
<th>Col11</th>_x000D_
<th>Col12</th>_x000D_
<th>Col13</th>_x000D_
<th>Col14</th>_x000D_
<th>Col15</th>_x000D_
<th>Col16</th>_x000D_
<th>Col17</th>_x000D_
<th>Col18</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
</tbody>_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
<td>Long Value</td>_x000D_
<td>Title</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
_x000D_
_x000D_
</div>`enter code here`
_x000D_
I believe what you are looking for is functional approach
const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
elem === 'a' is the condition, replace it with your own.
if(mytime.after(fromtime) && mytime.before(totime))
//mytime is in between
It might be useful to note (for *nix platforms): some types of global git configuration/information are stored in /usr/share/git-core/
, such as git autocompletion scripts and the following (default) hooks:
Each of these can contain their own set of commands to execute, at the time described by their respective filenames.
This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.
SELECT *,
(CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
FROM table_name
ORDER BY IsNum, LEN(column_name), column_name;
For the GET parameters there are two alternatives:
First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s¶m2=%2$s",
num1,
num2);
StringRequest myReq = new StringRequest(Method.GET,
uri,
createMyReqSuccessListener(),
createMyReqErrorListener());
queue.add(myReq);
where num1 and num2 are String variables that contain your values.
Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder
and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8"));
to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.
For the POST parameters probably sometimes will be easier than the accepted answer to do it like:
StringRequest myReq = new StringRequest(Method.POST,
"http://somesite.com/some_endpoint.php",
createMyReqSuccessListener(),
createMyReqErrorListener()) {
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("param1", num1);
params.put("param2", num2);
return params;
};
};
queue.add(myReq);
e.g. to just override the getParams()
method.
You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.
A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.
A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).
The manual explains it as follows:
A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.
A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.
The manual explains how indexes are used in general: here.
In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.
Untested, but I believe the MSSQL equivalent is:
CREATE TABLE tmp (
id int NOT NULL PRIMARY KEY IDENTITY,
uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
name varchar(255) NOT NULL,
tag int NOT NULL DEFAULT 0,
description varchar(255),
);
CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);
Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).
You're right, see 3.1.3. Unicode Strings.
It's been the syntax since Python 2.0.
Python 3 made them redundant, as the default string type is Unicode. Versions 3.0 through 3.2 removed them, but they were re-added in 3.3+ for compatibility with Python 2 to aide the 2 to 3 transition.
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
Just cd
to your working folder and then start the IPython notebook server
. This way you can be mobile.
In my case I was getting the grey background and it turned out to be inclusion of a zoom value in the map options. Yup, makes no sense.
The best solution I could find at present time to open a window maximized is (Internet Explorer 11, Chrome 49, Firefox 45):
var popup = window.open("your_url", "popup", "fullscreen");
if (popup.outerWidth < screen.availWidth || popup.outerHeight < screen.availHeight)
{
popup.moveTo(0,0);
popup.resizeTo(screen.availWidth, screen.availHeight);
}
see https://jsfiddle.net/8xwocrp6/7/
Note 1: It does not work on Edge (13.1058686). Not sure whether it's a bug or if it's as designed (I've filled a bug report, we'll see what they have to say about it). Here is a workaround:
if (navigator.userAgent.match(/Edge\/\d+/g))
{
return window.open("your_url", "popup", "width=" + screen.width + ",height=" + screen.height);
}
Note 2: moveTo
or resizeTo
will not work (Access denied) if the window you are opening is on another domain.
You will need to set the permissions every time you plug the converter in. I use PuTTY to connect. In order to do so, I have created a little Bash script to sort out the permissions and launch PuTTY:
#!/bin/bash
sudo chmod 666 /dev/ttyUSB0
putty
P.S. I would never recommend that permissions are set to 777.
This is a very old question, but my answer may help someone.
Below is the working code
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class EncryptionDecryptionUtil {
public static String encrypt(final String secret, final String data) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.ENCRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while encrypting data", e);
}
}
public static String decrypt(final String secret,
final String encryptedString) {
byte[] decodedKey = Base64.getDecoder().decode(secret);
try {
Cipher cipher = Cipher.getInstance("AES");
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
cipher.init(Cipher.DECRYPT_MODE, originalKey);
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
return new String(cipherText);
} catch (Exception e) {
throw new RuntimeException(
"Error occured while decrypting data", e);
}
}
public static void main(String[] args) {
String data = "This is not easy as you think";
String key = "---------------------------------";
String encrypted = encrypt(key, data);
System.out.println(encrypted);
System.out.println(decrypt(key, encrypted));
}
}
For Generating Key you can use below class
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SecretKeyGenerator {
public static void main(String[] args) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
int keyBitSize = 256;
keyGenerator.init(keyBitSize, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
}
}
The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html
private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return ComparisonChain.start().
compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
compare(str1,str2).
result();
}
};
Collections.sort(list, stringAlphabeticalComparator);
The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:
"AA","Aa","aa","Development","development"
Same way you'd hide anything: visibility: hidden;
Most of the other methods listed here are Rails specific. If you want do do this with pure Ruby, the following is the most concise way I've come up with (thanks to @ulysse-bn for the suggested improvement)
x="this_should_be_camel_case"
x.gsub(/(?:_|^)(\w)/){$1.upcase}
#=> "ThisShouldBeCamelCase"
There are essentially three different ways how to express something like if-then-else in Prolog. To compare them consider char_class/2
. For a
and b
the class should be ab
and other
for all other terms. One could write this clumsily like so:
char_class(a, ab).
char_class(b, ab).
char_class(X, other) :-
dif(X, a),
dif(X, b).
?- char_class(Ch, Class).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
To write things more compactly, an if-then-else construct is needed. Prolog has a built-in one:
?- ( ( Ch = a ; Ch = b ) -> Class = ab ; Class = other ).
Ch = a, Class = ab.
While this answer is sound, it is incomplete. Just the first answer from ( Ch = a ; Ch = b )
is given. The other answers are chopped away. Not very relational, indeed.
A better construct, often called a "soft cut" (don't believe the name, a cut is a cut is a cut), gives slightly better results (this is in YAP):
?- ( ( Ch = a ; Ch = b ) *-> Class = ab ; Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
Alternatively, SICStus has if/3
with very similar semantics:
?- if( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab.
So the last answer is still suppressed. Now enter library(reif)
for SICStus, YAP, and SWI. Install it and say:
?- use_module(library(reif)).
?- if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
Ch = a, Class = ab
; Ch = b, Class = ab
; Class = other,
dif(Ch, a), dif(Ch, b).
Note that all the if_/3
is compiled away to a wildly nested if-then-else for
char_class(Ch, Class) :-
if_( ( Ch = a ; Ch = b ), Class = ab , Class = other ).
which expands in YAP 6.3.4 to:
char_class(A,B) :-
( A\=a
->
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
;
( A==a
->
B=ab
)
;
A=a,
B=ab
;
dif(A,a),
( A\=b
->
B=other
;
( A==b
->
B=ab
)
;
A=b,
B=ab
;
dif(A,b),
B=other
)
).
It reads Hello World
(cat
), replaces all (g
) occurrences of %
by $
and (over)writes it to /etc/init.d/dropbox
as root.
It should be legal to put a semicolon directly before the WITH keyword.
Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.
Here is how I do it in 2018. Who knows, maybe an R newbie will see it one day and fall in love with ggplot2
.
library(ggplot2)
ggplot(data = iris, aes(Petal.Length, Petal.Width, color = Species)) +
geom_point() +
scale_color_manual(values = c("setosa" = "red", "versicolor" = "blue", "virginica" = "yellow"))
export
is a built-in command of the bash
shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.
I stumbled upon a situation where I have a small component I want to reuse, and added some code in a reusable view itself(it's really not much more than a button that opens a PopoverController
).
While this works fine in the iPad (the UIPopoverController
presents itself, therefor needs no reference to a UIViewController
), getting the same code to work means suddenly referencing your presentViewController
from your UIViewController
. Kinda inconsistent right?
Like mentioned before, it's not the best approach to have logic in your UIView. But it felt really useless to wrap the few lines of code needed in a separate controller.
Either way, here's a swift solution, which adds a new property to any UIView:
extension UIView {
var viewController: UIViewController? {
var responder: UIResponder? = self
while responder != nil {
if let responder = responder as? UIViewController {
return responder
}
responder = responder?.nextResponder()
}
return nil
}
}
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
After facing a similar issue, below is what I did :
To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");
.
Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*"
instead of any specific URL to allow any URL.
public class RestApplication
extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public MessageApplication()
{
singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
CorsFilter corsFilter = new CorsFilter();
// To allow all origins for CORS add following, otherwise add only specific urls.
// corsFilter.getAllowedOrigins().add("*");
System.out.println("To only allow restrcited urls ");
corsFilter.getAllowedOrigins().add("http://localhost:4200");
singletons = new LinkedHashSet<Object>();
singletons.add(corsFilter);
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<!-- Auto scan rest service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.app.RestApplication</param-value>
</init-param>
And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.
You can use the Environment class's static NewLine property to get the proper newline:
$errorMsg = "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),$keyPath,$value,$key,$policyValue,([Environment]::NewLine),$localValue
Add-Content -Path $logpath $errorMsg
Here is a sample implementation:
import java.util.*;
public class MyBSTree<K,V> implements MyTree<K,V>{
private BSTNode<K,V> _root;
private int _size;
private Comparator<K> _comparator;
private int mod = 0;
public MyBSTree(Comparator<K> comparator){
_comparator = comparator;
}
public Node<K,V> root(){
return _root;
}
public int size(){
return _size;
}
public boolean containsKey(K key){
if(_root == null){
return false;
}
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return true;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
return false;
}
private int compare(K k1, K k2){
if(_comparator != null){
return _comparator.compare(k1,k2);
}
else {
Comparable<K> comparable = (Comparable<K>)k1;
return comparable.compareTo(k2);
}
}
public V get(K key){
Node<K,V> node = node(key);
return node != null ? node.value() : null;
}
private BSTNode<K,V> node(K key){
if(_root != null){
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return node;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
}
return null;
}
public void add(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
if(_root == null){
_root = new BSTNode<K, V>(key, value);
}
BSTNode<K,V> prev = null, curr = _root;
boolean lastChildLeft = false;
while(curr != null){
int comparison = compare(key, curr.key());
prev = curr;
if(comparison == 0){
curr._value = value;
return;
}else if(comparison < 0){
curr = curr._left;
lastChildLeft = true;
}
else{
curr = curr._right;
lastChildLeft = false;
}
}
mod++;
if(lastChildLeft){
prev._left = new BSTNode<K, V>(key, value);
}else {
prev._right = new BSTNode<K, V>(key, value);
}
}
private void removeNode(BSTNode<K,V> curr){
if(curr.left() == null && curr.right() == null){
if(curr == _root){
_root = null;
}else{
if(curr.isLeft()) curr._parent._left = null;
else curr._parent._right = null;
}
}
else if(curr._left == null && curr._right != null){
curr._key = curr._right._key;
curr._value = curr._right._value;
curr._left = curr._right._left;
curr._right = curr._right._right;
}
else if(curr._left != null && curr._right == null){
curr._key = curr._left._key;
curr._value = curr._left._value;
curr._right = curr._left._right;
curr._left = curr._left._left;
}
else { // both left & right exist
BSTNode<K,V> x = curr._left;
// find right-most node of left sub-tree
while (x._right != null){
x = x._right;
}
// move that to current
curr._key = x._key;
curr._value = x._value;
// delete duplicate data
removeNode(x);
}
}
public V remove(K key){
BSTNode<K,V> curr = _root;
V val = null;
while(curr != null){
int comparison = compare(key, curr.key());
if(comparison == 0){
val = curr._value;
removeNode(curr);
mod++;
break;
}else if(comparison < 0){
curr = curr._left;
}
else{
curr = curr._right;
}
}
return val;
}
public Iterator<MyTree.Node<K,V>> iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<Node<K,V>>{
int _startMod;
Stack<BSTNode<K,V>> _stack;
public MyIterator(){
_startMod = MyBSTree.this.mod;
_stack = new Stack<BSTNode<K, V>>();
BSTNode<K,V> node = MyBSTree.this._root;
while (node != null){
_stack.push(node);
node = node._left;
}
}
public void remove(){
throw new UnsupportedOperationException();
}
public boolean hasNext(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
return !_stack.empty();
}
public Node<K,V> next(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
if(!hasNext()){
throw new NoSuchElementException();
}
BSTNode<K,V> node = _stack.pop();
BSTNode<K,V> x = node._right;
while (x != null){
_stack.push(x);
x = x._left;
}
return node;
}
}
@Override
public String toString(){
if(_root == null) return "[]";
return _root.toString();
}
private static class BSTNode<K,V> implements Node<K,V>{
K _key;
V _value;
BSTNode<K,V> _left, _right, _parent;
public BSTNode(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
_key = key;
_value = value;
}
public K key(){
return _key;
}
public V value(){
return _value;
}
public Node<K,V> left(){
return _left;
}
public Node<K,V> right(){
return _right;
}
public Node<K,V> parent(){
return _parent;
}
boolean isLeft(){
if(_parent == null) return false;
return _parent._left == this;
}
boolean isRight(){
if(_parent == null) return false;
return _parent._right == this;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
try{
BSTNode<K,V> node = (BSTNode<K,V>)o;
return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
}catch (ClassCastException ex){
return false;
}
}
@Override
public int hashCode(){
int hashCode = _key.hashCode();
if(_value != null){
hashCode ^= _value.hashCode();
}
return hashCode;
}
@Override
public String toString(){
String leftStr = _left != null ? _left.toString() : "";
String rightStr = _right != null ? _right.toString() : "";
return "["+leftStr+" "+_key+" "+rightStr+"]";
}
}
}
conda
doesn't support this directly because it installs from binaries, whereas git install would be from source. conda build
does support recipes that are built from git. On the other hand, if all you want to do is keep up-to-date with the latest and greatest of a package, using pip inside of Anaconda is just fine, or alternately, use setup.py develop
against a git clone.
try this:
create procedure dept_count( @dept_name varchar(20), @d_count INTEGER out)
AS
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
In Windows, you also normally need to run command line as administrator.
As standard-user:
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
Get https://mcr.microsoft.com/v2/: dial tcp: lookup mcr.microsoft.com on [::1]:53: read udp [::1]:45540->[::1]:53: read:
>>>connection refused
But as an administrator.
docker build -t myimage -f Dockerfile .
Sending build context to Docker daemon 106.8MB
Step 1/1 : FROM mcr.microsoft.com/dotnet/core/runtime:3.0
3.0: Pulling from dotnet/core/runtime
68ced04f60ab: Pull complete e936bd534ffb: Pull complete caf64655bcbb: Pull complete d1927dbcbcab: Pull complete Digest: sha256:e0c67764f530a9cad29a09816614c0129af8fe3bd550eeb4e44cdaddf8f5aa40
Status: Downloaded newer image for mcr.microsoft.com/dotnet/core/runtime:3.0
---> f059cd71a22a
Successfully built f059cd71a22a
Successfully tagged myimage:latest
To remove the first character you would use:
var myOriginalString = ",'first string','more','even more'";
var myString = myOriginalString.substring(1);
I'm not sure this will be the result you're looking for though because you will still need to split it to create an array with it. Maybe something like:
var myString = myOriginalString.substring(1);
var myArray = myString.split(',');
Keep in mind, the ' character will be a part of each string in the split here.
I also hit this error…
The installation msi will try to create a new task in the Windows Task scheduler to remind you to give customer feedback. This install step executes regardless of whether you do or do not click the check box to participate in customer feedback. In many corporate environments (including mine) creating new windows tasks is denied to all but domain administrators. As a result, running as a local admin is not sufficient and the entire installation fails when adding the task returns “access denied”. This shows up in the install log as a 1603.
The only workaround we could find was to manually pull all the files out of the msi, remove the “add schedule task” from the install script, and then create a new msi. After that one line change, it worked fine.
Below changes worked for me
I change distribution URL, located in gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-all.zip
And
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
kotlin version 1.2.71
It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.
However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")
So as long as the method is present in xInterface
, and your class implements xInterface
, you won't be able to make the method static.
If you can't change the interface (or don't want to), there are several things you can do:
xInterface
), and a static method. The instance method will consist of a single line that delegates to the static method.If you are not using annotation based Servlet then please remove annotation @WebServlet("/YourServletName") from the starting of the servlet. This annotation confuses the mapping with web.xml, after removing this annotation Tomcat server will work properly.
I know its kind of too late and proly every one got the answer. But little bit more to add to this: when GenerateType is set, persist() on an object is expected to get an id generated.
If there is a value set to the Id by user already, hibernate treats it as saved record and so it is treated as detached.
if the id is null - in this situation a null pointer exception is raised when the type is AUTO or IDENTITY etc unless the id is generated from a table or a sequece etc.
design: this happens when the table has a bean property as primary key. GenerateType must be set only when an id is autogenerated. remove this and the insert should work with the user specified id. (it is a bad design to have a property mapped to primary key field)
As the transcript for SciPy told you, SciPy isn't really supposed to work on Win64:
Warning: Windows 64 bits support is experimental, and only available for
testing. You are advised not to use it for production.
So I would suggest to install the 32-bit version of Python, and stop attempting to build SciPy yourself. If you still want to try anyway, you first need to compile BLAS and LAPACK, as PiotrLegnica says. See the transcript for the places where it was looking for compiled versions of these libraries.
Although I take the risk of not being popular I say they are not useful nowadays.
I think they were well intended and useful in the past when for example DELETE told the server to delete the resource found at supplied URL and PUT (with its sibling PATCH) told the server to do update in an idempotent manner.
Things evolved and URLs became virtual (see url rewriting for example) making resources lose their initial meaning of real folder/subforder/file and so, CRUD action verbs covered by HTTP protocol methods (GET, POST, PUT/PATCH, DELETE) lost track.
Let's take an example:
On the left side is not written the HTTP method, essentially it doesn't matter (POST and GET are enough) and on the right side appropriate HTTP methods are used.
Right side looks elegant, clean and professional. Imagine now you have to maintain a code that's been using the elegant API and you have to search where deletion call is done. You'll search for "api/entity" and among results you'll have to see which one is doing DELETE. Or even worse, you have a junior programmer which by mistake switched PUT with DELETE and as URL is the same shit happened.
In my opinion putting the action verb in the URL has advantages over using the appropriate HTTP method for that action even if it's not so elegant. If you want to see where delete call is made you just have to search for "api/entity/delete" and you'll find it straight away.
Building an API without the whole HTTP array of methods makes it easier to be consumed and maintained afterwards
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
You don't need to use JsonConverterAttribute
, keep your model clean, also use CustomCreationConverter
, the code is simpler:
public class SampleConverter : CustomCreationConverter<ISample>
{
public override ISample Create(Type objectType)
{
return new Sample();
}
}
Then:
var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());
Documentation: Deserialize with CustomCreationConverter
Hello please note like real work.
Children can not have two mother
So in java, subclass can not have two parent class.
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
Using the code from the thread above, you would be able to use:
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest())
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
}
return View(model);
}
You can run the mount command without parameter in order to get partition information before constructing your mount command. Here is an example of the mount command without parameter outputed from my HTC Hero.
$ mount
mount
rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock3 /system yaffs2 rw 0 0
/dev/block/mtdblock5 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock4 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:1 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=
1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,s
hortname=mixed,utf8,errors=remount-ro 0 0
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH
in the shell or include_path
in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
Use a iterator to loop through list and then delete the required object.
Iterator itr = a.iterator();
while(itr.hasNext()){
if(itr.next().equals("acbd"))
itr.remove();
}
Use the -j
option:
-j Store just the name of a saved file (junk the path), and do not
store directory names. By default, zip will store the full path
(relative to the current path).
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
Not sure as to why it doesn't render it on your navigation's browser, but I normally use an snippet like this when trying to display a header with an image and a centered text, hope it helps!
https://output.jsbin.com/jeqorahupo
<hgroup style="display:block; text-align:center; vertical-align:middle; margin:inherit auto; padding:inherit auto; max-height:inherit">
<header style="background:url('http://lorempixel.com/30/30/') center center no-repeat; background-size:auto; display:inner-block; vertical-align:middle; position:relative; position:absolute; top:inherit; left:inherit; display: -webkit-box; display: -webkit-flex;display: -moz-box;display: -ms-flexbox;display: flex;-webkit-flex-align: center;-ms-flex-align: center;-webkit-align-items: center;align-items: center;">
<image src="http://lorempixel.com/60/60/" title="Img title" style="opacity:0.35"></img>
http://lipsum.org</header>
</hgroup>
You need to delete your old db folder and recreate new one. It will resolve your issue.
With New-Item you can add the Force parameter
New-Item -Force -ItemType directory -Path foo
Or the ErrorAction parameter
New-Item -ErrorAction Ignore -ItemType directory -Path foo
window load will wait for all resources to be loaded.
document ready waits for the document to be initialized.
unload well, waits till the document is being unloaded.
the order is: document ready, window load, ... ... ... ... window unload.
always use document ready unless you need to wait for your images to load.
shorthand for document ready:
$(function(){
// yay!
});
let args = {"data":htmlData,"filename":exampleName}
To create a HTMl file and download
window.downloadHTML = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.html';
data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
console.log(data);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}
To create and download a CSV
window.downloadCSV = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
This worked for me while searching for value less than or equal than now:
db.collectionName.find({ "dt": { "$lte" : new Date() + "" } });
Prototype makes it dead simple
new Ajax.Request( '/myurl', {
method: 'get',
parameters: { 'param1': 'value1'},
onSuccess: function(response){
alert(response.responseText);
},
onFailure: function(){
alert('ERROR');
}
});
I see many answers suggesting itertools.tee, but that's ignoring one crucial warning in the docs for it:
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use
list()
instead oftee()
.
Basically, tee
is designed for those situation where two (or more) clones of one iterator, while "getting out of sync" with each other, don't do so by much -- rather, they say in the same "vicinity" (a few items behind or ahead of each other). Not suitable for the OP's problem of "redo from the start".
L = list(DictReader(...))
on the other hand is perfectly suitable, as long as the list of dicts can fit comfortably in memory. A new "iterator from the start" (very lightweight and low-overhead) can be made at any time with iter(L)
, and used in part or in whole without affecting new or existing ones; other access patterns are also easily available.
As several answers rightly remarked, in the specific case of csv
you can also .seek(0)
the underlying file object (a rather special case). I'm not sure that's documented and guaranteed, though it does currently work; it would probably be worth considering only for truly huge csv files, in which the list
I recommmend as the general approach would have too large a memory footprint.
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
#write data
ser.write("AT+CSQ")
print("write data: AT+CSQ")
time.sleep(0.5) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
Add a file .jslintrc (or .jshintrc in the case of jshint) at the root of your project with the following content:
{
"node": true
}
Try to restart eclipse, that works sometimes. I guess there is some kind of cache there.
In theory, memcpy
might have a slight, imperceptible, infinitesimal, performance advantage, only because it doesn't have the same requirements as std::copy
. From the man page of memcpy
:
To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).
In other words, memcpy
can ignore the possibility of overlapping data. (Passing overlapping arrays to memcpy
is undefined behavior.) So memcpy
doesn't need to explicitly check for this condition, whereas std::copy
can be used as long as the OutputIterator
parameter is not in the source range. Note this is not the same as saying that the source range and destination range can't overlap.
So since std::copy
has somewhat different requirements, in theory it should be slightly (with an extreme emphasis on slightly) slower, since it probably will check for overlapping C-arrays, or else delegate the copying of C-arrays to memmove
, which needs to perform the check. But in practice, you (and most profilers) probably won't even detect any difference.
Of course, if you're not working with PODs, you can't use memcpy
anyway.
If you are using 19c then just follow the following steps
If you are using cmake, you can use:
add_compile_options(-pthread)
Or
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")
android:minHeight android:maxHeight is important for that.
<SeekBar
android:id="@+id/pb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="2dp"
android:minHeight="2dp"
android:progressDrawable="@drawable/seekbar_bg"
android:thumb="@drawable/seekbar_thumb"
android:max="100"
android:progress="50"/>
seekbar_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="3dp" />
<solid android:color="#ECF0F1" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="3dp" />
<solid android:color="#C6CACE" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="3dp" />
<solid android:color="#16BC5C" />
</shape>
</clip>
</item>
</layer-list>
seekbar_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#16BC5C" />
<stroke
android:width="1dp"
android:color="#16BC5C" />
<size
android:height="20dp"
android:width="20dp" />
</shape>
If there is no size limit, the quickest way is to take the length of the file, and generate the length of the file+1 number of random digits (or just "11111..." s). Advantage: you don't even need to read the file, and you can minimize memory use nearly to zero. Disadvantage: You will print billions of digits.
However, if the only factor was minimizing memory usage, and nothing else is important, this would be the optimal solution. It might even get you a "worst abuse of the rules" award.
Get each bit of byte and convert to string. Say byte has 8 bits, and we can get them one by one via bit move. For example, we move the second bit of the byte 6 bits to right, the second bit at last of bit of 8 bits, then and(&) with 0x0001 to clean the front bits.
public static String getByteBinaryString(byte b) {
StringBuilder sb = new StringBuilder();
for (int i = 7; i >= 0; --i) {
sb.append(b >>> i & 1);
}
return sb.toString();
}
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
In VS2019, the project property page, TypeScript Build tab has a setting (dropdown) for "Module System". When I changed that from "ES2015" to CommonJS, then VS2019 IDE stopped complaining that it could find neither axios nor redux-thunk (TS2307).
tsconfig.json:
{
"compilerOptions": {
"allowJs": true,
"baseUrl": "src",
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"lib": [
"es6",
"dom",
"es2015.promise"
],
"module": "esnext",
"moduleResolution": "node",
"noImplicitAny": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"outDir": "build/dist",
"rootDir": "src",
"sourceMap": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"target": "es5",
"skipLibCheck": true,
"strict": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"exclude": [
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts",
"node_modules",
"obj",
"**/*.spec.ts"
],
"include": [
"src",
"src/**/*.ts",
"@types/**/*.d.ts",
"node_modules/axios",
"node_modules/redux-thunk"
]
}
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
One other easy way of doing it would be as follows (if you have a simple NetBeans project and not using maven for example).
This is the default working setup https://www.youtube.com/watch?v=XiD7JTCBdpI
Use Connection Method: standard TCP/IP over ssh
Then ssh hostname: 127.0.0.1:2222
SSH Username: vagrant password vagrant
MySQL Hostname: localhost
Username: homestead password:secret
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
Solution for your example code using PowerMockito.whenNew
FooTest.java
package foo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
//Both @PrepareForTest and @RunWith are needed for `whenNew` to work
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest {
// Class Under Test
Foo cut;
@Mock
Bar barMock;
@Before
public void setUp() throws Exception {
cut = new Foo();
}
@After
public void tearDown() {
cut = null;
}
@Test
public void testFoo() throws Exception {
// Setup
PowerMockito.whenNew(Bar.class).withNoArguments()
.thenReturn(this.barMock);
// Test
cut.foo();
// Validations
Mockito.verify(this.barMock, Mockito.times(1)).someMethod();
}
}
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element)
on its parent, which is to just call element.remove()
. In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.
The .remove()
method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.
If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode
, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode
and are actually defined in the browser, and add .remove
to them.
Here's the shim I came up with, which I've confirmed works in IE 8.
(function () {
var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
remove = function () {
// The check here seems pointless, since we're not adding this
// method to the prototypes of any any elements that CAN be the
// root of the DOM. However, it's required by spec (see point 1 of
// https://dom.spec.whatwg.org/#dom-childnode-remove) and would
// theoretically make a difference if somebody .apply()ed this
// method to the DOM's root node, so let's roll with it.
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
};
for (var i=0; i<typesToPatch.length; i++) {
var type = typesToPatch[i];
if (window[type] && !window[type].prototype.remove) {
window[type].prototype.remove = remove;
}
}
})();
This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.
Once you've included them shim, you'll be able to remove a DOM element element
from the DOM by simply calling
element.remove();
I prefer to solve this in the classic way, creating a new array of my desired data type:
List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.
If you are using II7 (and I guess you do) do the following.
Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool
Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.
We will import the CSV file into the destination table in the simplest form. I placed my sample CSV file on the C: drive and now we will create a table which we will import data from the CSV file.
DROP TABLE IF EXISTS Sales
CREATE TABLE [dbo].[Sales](
[Region] [varchar](50) ,
[Country] [varchar](50) ,
[ItemType] [varchar](50) NULL,
[SalesChannel] [varchar](50) NULL,
[OrderPriority] [varchar](50) NULL,
[OrderDate] datetime,
[OrderID] bigint NULL,
[ShipDate] datetime,
[UnitsSold] float,
[UnitPrice] float,
[UnitCost] float,
[TotalRevenue] float,
[TotalCost] float,
[TotalProfit] float
)
The following BULK INSERT statement imports the CSV file to the Sales table.
BULK INSERT Sales
FROM 'C:\1500000 Sales Records.csv'
WITH (FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR='\n' );
While you can store an unlimited number of files/objects in a single bucket, when you go to list a "directory" in a bucket, it will only give you the first 1000 files/objects in that bucket by default. To access all the files in a large "directory" like this, you need to make multiple calls to their API.
ES6:
const promise = new Promise(resolve => resolve('olá'));
console.log(promise.toString().includes('Promise')); //true
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:
HTTP could not register URL http://+:12345/Foo.svc/]. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).
Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258
Hi you should give parent position relative and child absolute and give to height or width to absolute class as like this
Css
.nkhome{
margin-left:260px;
width:59px;
height:59px;
margin-top:170px;
position:relative;
z-index:0;
}
.nkhome a:hover img{
opacity:0.0;
}
.nkhome a:hover{
background:url('http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg');
width:100px;
height:100px;
position:absolute;
top:0;
z-index:1;
}
HTML
<div class="nkhome">
<a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" /></a>
</div>
?
Live demo http://jsfiddle.net/t5FEX/7/
or this
<div class="nkhome">
<a href="Home.html"><img src="http://dummyimage.com/100/000/fff.jpg" onmouseover="this.src='http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg'"
onmouseout="this.src='http://dummyimage.com/100/000/fff.jpg'"
/></a>
</div>?
Live demo http://jsfiddle.net/t5FEX/9/
return value.replaceAll("[^A-Za-z0-9 ]", "");
This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.
image
has a shape of (64,64,3)
.
Your input placeholder _x
have a shape of (?, 64,64,3)
.
The problem is that you're feeding the placeholder with a value of a different shape.
You have to feed it with a value of (1, 64, 64, 3)
= a batch of 1 image.
Just reshape your image
value to a batch with size one.
image = array(img).reshape(1, 64,64,3)
P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel.
You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)
from collections import OrderedDict
list1 = ['k1', 'k2']
list2 = ['v1', 'v2']
new_ordered_dict = OrderedDict(zip(list1, list2))
print new_ordered_dict
# OrderedDict([('k1', 'v1'), ('k2', 'v2')])
Would it be as easy as running a LINQ query on your List?
List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();
Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:
If a module imports objects from another module using
from ... import ...
, callingreload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to useimport
and qualified names (module.*name*
) instead.
However, if using the __all__
variable to define the public API, it is possible to automatically reload all publicly available modules:
# Python >= 3.5
import importlib
import types
def walk_reload(module: types.ModuleType) -> None:
if hasattr(module, "__all__"):
for submodule_name in module.__all__:
walk_reload(getattr(module, submodule_name))
importlib.reload(module)
walk_reload(my_module)
The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__
variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.
In order to deploy your Angular2 app to a production server, first and foremost, ensure your app runs locally on your machine.
Angular2 app can also be deployed as a node app.
So, create a node entry point file server.js/app.js (my example uses express)
var express = require('express'),
path = require('path'),
fs = require('fs');
var app = express();
var staticRoot = __dirname + '/';
app.set('port', (process.env.PORT || 3000));
app.use(express.static(staticRoot));
app.use(function(req, res, next){
// if the request is not html then move along
var accept = req.accepts('html', 'json', 'xml');
if(accept !== 'html'){
return next();
}
// if the request has a '.' assume that it's for a file, move along
var ext = path.extname(req.path);
if (ext !== ''){
return next();
}
fs.createReadStream(staticRoot + 'index.html').pipe(res);
});
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
Also add express as a dependency in your package.json file.
Then deploy it on your preferred environment.
I have put together a small blog for deployment on IIS. follow link
verbose: Integer
. 0, 1, or 2. Verbosity mode.
Verbose=0 (silent)
Verbose=1 (progress bar)
Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc:
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc:
0.8071 - val_loss: 0.4617 - val_acc: 0.8168
Verbose=2 (one line per epoch)
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046
To follow up on Yenchi's comment above, the OK button will also do nothing if the camera app can't write to the directory in question.
That means that you can't create the file in a place that's only writeable by your application (for instance, something under getCacheDir())
Something under getExternalFilesDir()
ought to work, however.
It would be nice if the camera app printed an error message to the logs if it could not write to the specified EXTRA_OUTPUT
path, but I didn't find one.
CustomLinearLayout.kt :
class CustomLayoutManager(private val context: Context, layoutDirection: Int):
LinearLayoutManager(context, layoutDirection, false) {
companion object {
// This determines how smooth the scrolling will be
private
const val MILLISECONDS_PER_INCH = 300f
}
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
val smoothScroller: LinearSmoothScroller = object: LinearSmoothScroller(context) {
fun dp2px(dpValue: Float): Int {
val scale = context.resources.displayMetrics.density
return (dpValue * scale + 0.5f).toInt()
}
// change this and the return super type to "calculateDyToMakeVisible" if the layout direction is set to VERTICAL
override fun calculateDxToMakeVisible(view: View ? , snapPreference : Int): Int {
return super.calculateDxToMakeVisible(view, SNAP_TO_END) - dp2px(50f)
}
//This controls the direction in which smoothScroll looks for your view
override fun computeScrollVectorForPosition(targetPosition: Int): PointF ? {
return this @CustomLayoutManager.computeScrollVectorForPosition(targetPosition)
}
//This returns the milliseconds it takes to scroll one pixel.
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
}
}
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
}
Note: The above example is set to HORIZONTAL direction, you can pass VERTICAL/HORIZONTAL during initialization.
If you set the direction to VERTICAL you should change the "calculateDxToMakeVisible" to "calculateDyToMakeVisible" (also mind the supertype call return value)
Activity/Fragment.kt :
...
smoothScrollerLayoutManager = CustomLayoutManager(context, LinearLayoutManager.HORIZONTAL)
recyclerView.layoutManager = smoothScrollerLayoutManager
.
.
.
fun onClick() {
// targetPosition passed from the adapter to activity/fragment
recyclerView.smoothScrollToPosition(targetPosition)
}
after_initialize method is deprecated, use the callback instead.
after_initialize :defaults
def defaults
self.extras||={}
self.other_stuff||="This stuff"
end
however, using :default in your migrations is still the cleanest way.
In my opinion the most readable version
public enum PIN_PULL_RESISTANCE {
PULL_UP {
@Override
public int getValue() {
return 1;
}
},
PULL_DOWN {
@Override
public int getValue() {
return 0;
}
};
public abstract int getValue();
}
You can probably start a Service
here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.
UDPATE
You can use START_STICKY
to make your Service running continuously.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Following redsquare: You should not use in href attribute javascript code like "javascript:void();" - it is wrong. Better use for example href="#" and then in Your event handler as a last command: "return false;". And even better - use in href correct link - if user have javascript disabled, web browser follows the link - in this case Your webpage should reload with input filled with value of that link.
Use TextureLoader to load a image as texture and then simply apply that texture to scene background.
new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
{
scene.background = texture;
});
Result:
https://codepen.io/hiteshsahu/pen/jpGLpq?editors=0011
See the Pen Flat Earth Three.JS by Hitesh Sahu (@hiteshsahu) on CodePen.The selected answer did not work in my Web API application. I had to use
System.Web.HttpRuntime.AppDomainAppPath
How about String.format("%.2f", i2)
?
I used @LiorH's example and expanded it to:
@XmlRootElement(name="List")
public class JaxbList<T>{
protected List<T> list;
public JaxbList(){}
public JaxbList(List<T> list){
this.list=list;
}
@XmlElement(name="Item")
public List<T> getList(){
return list;
}
}
Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:
@GET
@Path("/test2")
public JaxbList test2(){
List list=new Vector();
list.add("a");
list.add("b");
return new JaxbList(list);
}
Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?
For anyone want to get time elapsed value instead of console output :
use process.hrtime() as @D.Deriso suggestion, below is my simpler approach :
function functionToBeMeasured() {
var startTime = process.hrtime();
// do some task...
// ......
var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
console.log('It takes ' + elapsedSeconds + 'seconds');
}
function parseHrtimeToSeconds(hrtime) {
var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
return seconds;
}
works for me
<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>
The Java Language Specification, section 15.10, states:
An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7).
and
The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
The closest you can do is use an unchecked cast, either from the raw type, as you have done, or from an unbounded wildcard:
HashMap<String, String>[] responseArray = (Map<String, String>[]) new HashMap<?,?>[games.size()];
Your version is clearly better :-)
We can emulate a do-while loop in Bash with while [[condition]]; do true; done
like this:
while [[ current_time <= $cutoff ]]
check_if_file_present
#do other stuff
do true; done
For an example. Here is my implementation on getting ssh connection in bash script:
#!/bin/bash
while [[ $STATUS != 0 ]]
ssh-add -l &>/dev/null; STATUS="$?"
if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done
It will give the output in sequence as below:
Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"
Or you could use this line when dealing with WPF or Silverlight, especially where you have the source string already in the XAML markup:
(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);
Where the ImagePath is something like:
string ImagePath = "/ProjectName;component/Resource/ImageName.png";
I have finally found a working code - try this:
document.getElementById("button").style.background='#000000';
My solution introduces a static function for the global Object
object.
(function() {
var lastStorageId = 0;
this.Object.hash = function(object) {
var hash = object.__id;
if (!hash)
hash = object.__id = lastStorageId++;
return '#' + hash;
};
}());
I think this is more convenient with other object manipulating functions in JavaScript.
There is an Ini Parser available in CommonLibrary.NET
This has various very convenient overloads for getting sections/values and is very light weight.
This might be what you are looking for:
yourStream
.filter(/* your criteria */)
.findFirst()
.get();
And better, if there's a possibility of matching no element, in which case get()
will throw a NPE. So use:
yourStream
.filter(/* your criteria */)
.findFirst()
.orElse(null); /* You could also create a default object here */
public static void main(String[] args) {
class Stop {
private final String stationName;
private final int passengerCount;
Stop(final String stationName, final int passengerCount) {
this.stationName = stationName;
this.passengerCount = passengerCount;
}
}
List<Stop> stops = new LinkedList<>();
stops.add(new Stop("Station1", 250));
stops.add(new Stop("Station2", 275));
stops.add(new Stop("Station3", 390));
stops.add(new Stop("Station2", 210));
stops.add(new Stop("Station1", 190));
Stop firstStopAtStation1 = stops.stream()
.filter(e -> e.stationName.equals("Station1"))
.findFirst()
.orElse(null);
System.out.printf("At the first stop at Station1 there were %d passengers in the train.", firstStopAtStation1.passengerCount);
}
Output is:
At the first stop at Station1 there were 250 passengers in the train.
try like this
if (!(a | b)) {
//blahblah
}
It's same with
if (a | b) {}
else {
// blahblah
}
This is possible using this cross browser javascript implementation of the HTML5 saveAs
function: https://github.com/koffsyrup/FileSaver.js
If all you want to do is save text then the above script works in all browsers(including all versions of IE), using nothing but JS.
In simple words
Amazon EBS provides block level storage .
Amazon EFS provides network-attached shared file storage.
Amazon S3 provides object storage .
In JavaScript when you create any object through a constructor call like below
step 1 : create a function say Person..
function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}
step 2 : create an instance for this function..
var obj=new Person('venkat')
//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}
if you don't want to instantiate this function and call at same time.we can also do like below..
var Person = {
init: function(name){
this.name=name;
},
print: function(){
console.log(this.name);
}
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();
in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.
You can use it as follows,
<td>
<input type="submit" name="save" class="noborder" id="save" value="Save" alt="Save"
tabindex="4" />
</td>
<td>
<input type="submit" name="publish" class="noborder" id="publish" value="Publish"
alt="Publish" tabindex="5" />
</td>
And in PHP,
<?php
if($_POST['save'])
{
//Save Code
}
else if($_POST['publish'])
{
//Publish Code
}
?>
var div = document.createElement('div');
document.body.appendChild(div);
div.style.left = '32px';
div.style.top = '-16px';
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
div.parentNode.removeChild(div);
div = document.getElementById('test');
array = document.getElementsByTagName('div');
array = document.getElementsByClassName('ui-modal');
div = document.querySelector('div #test .ui-modal');
array = document.querySelectorAll('div');
This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.
I just finished a sample app that does this in a pretty basic, but clear way. It uses mongoose with mongodb to store users and passport for auth management.
Yes, use mktemp.
It will create a temporary file inside a folder that is designed for storing temporary files, and it will guarantee you a unique name. It outputs the name of that file:
> mktemp
/tmp/tmp.xx4mM3ePQY
>
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
You can loop through a hash map like this
<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);
%>
<c:forEach items="${itemList}" var="itemrow">
<input type="text" value="<c:out value='${itemrow.test}'/>"/>
</c:forEach>
For more JSTL functionality look here
You can use df.isnull().sum()
. It shows all columns and the total NaNs of each feature.
If you just want to check if certain characters are actually in the string or not, use strtok:
$string = 'abcdefg';
if (strtok($string, 'acd') === $string) {
// not found
} else {
// found
}
The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.
If you view the code that is used for the demo website and basically copy/paste, you'll be fine.
To get an inline Fancybox working, you will need to have this code present in your index.html file:
<head>
<link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
<script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#various1").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
</script>
</head>
<body>
<a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
<div style="display: none;">
<div id="inline1" style="width:400px;height:100px;overflow:auto;">
Write whatever text you want right here!!
</div>
</div>
</body>
Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.
I am using Debian but this solution should work fine with Ubuntu.
You have to add a line in the neo4j-service script.
Here is what I have done :
nano /etc/init.d/neo4j-service
Add « ulimit –n 40000 » just before the start-stop-daemon line in the do_start section
Note that I am using version 2.0 Enterprise edition. Hope this will help you.
delimiter //
CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
declare str VARCHAR(255) default '';
declare x INT default 0;
SET x = 1;
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
select str;
END//
Which prints:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
delimiter //
CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 5;
SET str = '';
REPEAT
SET str = CONCAT(str,x,',');
SET x = x - 1;
UNTIL x <= 0
END REPEAT;
SELECT str;
END//
Which prints:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
delimiter //
CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = -5;
SET str = '';
loop_label: LOOP
IF x > 0 THEN
LEAVE loop_label;
END IF;
SET str = CONCAT(str,x,',');
SET x = x + 1;
ITERATE loop_label;
END LOOP;
SELECT str;
END//
Which prints:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx
If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.
Try
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'
_x000D_
I would suggest for a responsive approach the best practice would be using the Viewport units and min/max attributes as follows:
img{
display: block;
width: 12vw;
height:12vw;
max-width:100%;
min-width:100px;
min-height:100px;
object-fit:contain;
}
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
Should be
~/([^/]*)$~
Means: Match a /
and then everything, that is not a /
([^/]*
) until the end ($
, "end"-anchor).
I use the ~
as delimiter, because now I don't need to escape the forward-slash /
.
use:
/^[ A-Za-z0-9_@./#&+-]*$/
You can also use the character class \w to replace A-Za-z0-9_
Recreating an AVD with the Hardware Keyboard + setting the boolean to true was the only solution that worked for me; the other two main solutions (terminal or editing an existing AVD via GUI) both resulted in software/emulator crashes on my Mac. Making a new AVD resulted in the keyboard working just fine.
from urllib.request import urlopen, Request
Should solve everything
Good solutions explained pretty well here. But Here is one more.
Create your own CustomContextWrapper
class extending ContextWrapper
and use it to change Locale setting for the complete application.
Here is a GIST with usage.
And then call the CustomContextWrapper
with saved locale identifier e.g. 'hi'
for Hindi language in activity lifecycle method attachBaseContext
. Usage here:
@Override
protected void attachBaseContext(Context newBase) {
// fetch from shared preference also save the same when applying. Default here is en = English
String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}
Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.
While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend @ugly_syntax calls:
smaller design space.
This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.
Therefore my current favourite zero-config JS code style:
UPDATE:
Flow has improved a lot. With it, you can add types to your JS with will help you prevent a lot of bugs. But it can also stay out of your way, for instance when interfacing untyped JS. Give it a try!
Add standard
as a dependency to you project
npm install --save standard
Then in package.json
, add the following test script:
"scripts": {
"test": "node_modules/.bin/standard && echo put further tests here"
},
For snazzier output while developing, npm install --global snazzy
and run it instead of npm test
.
My friend when mentioning design space referred to Elm and I encourage you to give that language a try.
Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.
Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.
We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.
(ps. note that the React code is not idiomatic and could be improved)
the reality is that JS is untyped. Who am I to suggest typed programming to you?
See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).
But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.
I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.
Peace.
Keep it simple! Original Google maps variable, none of the extra stuff.
var mapOptions = {
zoom: 16,
center: myLatlng,
scrollwheel: false
}