Ben's code requires the parent div to have the form-group class (I was using btn-group), this is a slightly different version which just searches for the closest div and may even be a bit faster.
$(".dropdown-menu li a").click(function(){
var selText = $(this).text();
$(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
});
How to create an array size 5 containing pointers to characters:
char *array_of_pointers[ 5 ]; //array size 5 containing pointers to char
char m = 'm'; //character value holding the value 'm'
array_of_pointers[0] = &m; //assign m ptr into the array position 0.
printf("%c", *array_of_pointers[0]); //get the value of the pointer to m
How to create a pointer to an array of characters:
char (*pointer_to_array)[ 5 ]; //A pointer to an array containing 5 chars
char m = 'm'; //character value holding the value 'm'
*pointer_to_array[0] = m; //dereference array and put m in position 0
printf("%c", (*pointer_to_array)[0]); //dereference array and get position 0
How to create an 2D array containing pointers to characters:
char *array_of_pointers[5][2];
//An array size 5 containing arrays size 2 containing pointers to char
char m = 'm';
//character value holding the value 'm'
array_of_pointers[4][1] = &m;
//Get position 4 of array, then get position 1, then put m ptr in there.
printf("%c", *array_of_pointers[4][1]);
//Get position 4 of array, then get position 1 and dereference it.
How to create a pointer to an 2D array of characters:
char (*pointer_to_array)[5][2];
//A pointer to an array size 5 each containing arrays size 2 which hold chars
char m = 'm';
//character value holding the value 'm'
(*pointer_to_array)[4][1] = m;
//dereference array, Get position 4, get position 1, put m there.
printf("%c", (*pointer_to_array)[4][1]);
//dereference array, Get position 4, get position 1
To help you out with understanding how humans should read complex C/C++ declarations read this: http://www.programmerinterview.com/index.php/c-cplusplus/c-declarations/
There is another possible scenario that might get some people as well (if you have python and python3 on your system):
pip3 install boto3
Note the use of pip3
indicates the use of Python 3's pip installation vs just pip
which indicates the use of Python 2's.
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.
C90 does not support the boolean data type.
C99 does include it with this include:
#include <stdbool.h>
When I make a new project using React, to install the React modules I have to run "npm install" (PowerShell) from within the new projects ClientApp folder (e.g. "C:\Users\Chris\source\repos\HelloWorld2\HelloWorld2\ClientApp"). The .NET core WebApp with React needs to have the React files installed in the correct location for React commands to work properly.
I want to mention that.
Open VirtualBox and shut down every VM running.
The shut down should be power off.
And if your virtualbox has been added in the Path in linux (Mine is Ubuntu). You can just use command:
virtualbox restart
I assumed the first DIV is #content
:
<div id="content">
<img src="@Url.Content("~/images/image1.bmp")" alt="" />
<img src="@Url.Content("~/images/image2.bmp")" alt="" />
<img src="@Url.Content("~/images/image3.bmp")" alt="" />
</div>
And CSS :
#content{
width: 700px;
display: block;
height: auto;
}
#content > img{
float: left; width: 200px;
height: 200px;
margin: 5px 8px;
}
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
var decPlaces = (int)(((decimal)number % 1) * 100);
This presumes your number only has two decimal places.
Many good solutions have been provided already. However, if he text is provided in a very simple comma delimited format or similar, and speed is of importance, then I have for you a solution with a TABLE
function (in PL/SQL). I have also provided a rundown of some other solutions.
Please see more on the Blog Entry on Parsing a CSV into multiple columns.
Create interfaces:
BackButtonHandlerInterface
public interface BackButtonHandlerInterface {
void addBackClickListener (OnBackClickListener onBackClickListener);
void removeBackClickListener (OnBackClickListener onBackClickListener);
}
OnBackClickListener
public interface OnBackClickListener {
boolean onBackClick();
}
In Activity:
public class MainActivity extends AppCompatActivity implements BackButtonHandlerInterface {
private ArrayList<WeakReference<OnBackClickListener>> backClickListenersList = new ArrayList<>();
@Override
public void addBackClickListener(OnBackClickListener onBackClickListener) {
backClickListenersList.add(new WeakReference<>(onBackClickListener));
}
@Override
public void removeBackClickListener(OnBackClickListener onBackClickListener) {
for (Iterator<WeakReference<OnBackClickListener>> iterator = backClickListenersList.iterator();
iterator.hasNext();){
WeakReference<OnBackClickListener> weakRef = iterator.next();
if (weakRef.get() == onBackClickListener){
iterator.remove();
}
}
}
@Override
public void onBackPressed() {
if(!fragmentsBackKeyIntercept()){
super.onBackPressed();
}
}
private boolean fragmentsBackKeyIntercept() {
boolean isIntercept = false;
for (WeakReference<OnBackClickListener> weakRef : backClickListenersList) {
OnBackClickListener onBackClickListener = weakRef.get();
if (onBackClickListener != null) {
boolean isFragmIntercept = onBackClickListener.onBackClick();
if (!isIntercept) isIntercept = isFragmIntercept;
}
}
return isIntercept;
}
}
In Fragment:
public class MyFragment extends Fragment implements OnBackClickListener{
private BackButtonHandlerInterface backButtonHandler;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
backButtonHandler = (BackButtonHandlerInterface) activity;
backButtonHandler.addBackClickListener(this);
}
@Override
public void onDetach() {
super.onDetach();
backButtonHandler.removeBackClickListener(this);
backButtonHandler = null;
}
@Override
public boolean onBackClick() {
//This method handle onBackPressed()! return true or false
return false;
}
}
Provide custom back navigation
class MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This callback will only be called when MyFragment is at least Started.
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
// The callback can be enabled or disabled here or in the lambda
}
}
Verify you are editing the correct php.ini file.
Reference: https://github.com/composer/composer/issues/1440
"WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-X.Y.Z\php.ini to enable it for the CLI."
As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:
$('#your-parent .collapse').on('show.bs.collapse', function (e) {
var actives = $('#your-parent').find('.in, .collapsing');
actives.each( function (index, element) {
$(element).collapse('hide');
})
})
I got here with an MS Access problem.
Backticks are good for MySQL, but they create weird errors, like "Invalid Query Name: Query1" in MS Access, for MS Access only, use square brackets:
It should look like this
SELECT Customer.[Customer ID], Customer.[Full Name] ...
Type aptitude
to start the package manager. There you can see which applications are installed.
Use /
to search for packages. Try searching for apache2
and php5
(or whatever versions you want to use). If they are installed, they should be bold and have an i
in front of them. If they are not installed (p
in front of the line) and you want to install them (and you have root permissions), use +
to select them and then g
(twice) to install it.
Word of warning: Before doing that, it might be wise to have a quick look at some aptitude tutorial on the web.
TouchableOpacity
extents TouchableWithoutFeedback
, so you can just use the disabled
property :
<TouchableOpacity disabled={true}>
<Text>I'm disabled</Text>
</TouchableOpacity>
React Native TouchableWithoutFeedback #disabled documentation
The new Pressable API has a disabled
option too :
<Pressable disable={true}>
{({ pressed }) => (
<Text>I'm disabled</Text>
)}
</Pressable>
Both the size
attribute in HTML and the width
property in CSS will set the width of an <input>
. If you want to set the width to something closer to the width of each character use the **ch**
unit as in:
input {
width: 10ch;
}
I use my own custom function...
public function areNull() {
if (func_num_args() == 0) return false;
$arguments = func_get_args();
foreach ($arguments as $argument):
if (is_null($argument)) return true;
endforeach;
return false;
}
$var = areNull("username", "password", "etc");
I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);?
result
1234561613213213
You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.
CSS:
body{
background-image: url(SO_texture_bg.jpg);
background-repeat:repeat;
}
But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.
Wish you good luck.
We had the same issue when we had a typo in the mybatis mapping file like
....
#{column1Name, jdbcType=INTEGER},
#{column2Name, jdbcType=VARCHAR},
#{column3Name, jdbcTyep=VARCHAR} -- do you see the typo ?
.....
So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.
I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress
P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.
After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text"
button is pushed:
import tkinter as tk
class App(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master, height=42, width=42)
self.entry = tk.Entry(self)
self.entry.focus()
self.entry.pack()
self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
self.clear_button.pack()
def clear_text(self):
self.entry.delete(0, 'end')
def main():
root = tk.Tk()
App(root).pack(expand=True, fill='both')
root.mainloop()
if __name__ == "__main__":
main()
List <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
You can set the datatable as a datasource to many elements.
For eg
gridView
repeater
datalist
etc etc
If you need to extract data from each row then you can use
table.rows[rowindex][columnindex]
or
if you know the column name
table.rows[rowindex][columnname]
If you need to iterate the table then you can either use a for loop or a foreach loop like
for ( int i = 0; i < table.rows.length; i ++ )
{
string name = table.rows[i]["columnname"].ToString();
}
foreach ( DataRow dr in table.Rows )
{
string name = dr["columnname"].ToString();
}
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
I got this error when trying to add the Service reference for the first Silverlight enabled WCF in the same solution. I just build the .Web project and it started working..
Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.
import React from 'react';
import withRouter from 'react-router-dom';
const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)
export withRouter(MyComponent);
First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.
Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing
and concurrent.futures
libraries both wraps up most of the details for you.
The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures
, 4 lines with multiprocessing
.)
If you're using 2.6-2.7 or 3.0-3.1, futures
isn't built in, but you can install it from PyPI (pip install futures
).
Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map
), so let's do that first:
def try_my_operation(item):
try:
api.my_operation(item)
except:
print('error with item')
Putting it all together:
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)
If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper
from the itertools
recipes, which you can copy and paste into your code, or get from the more-itertools
project on PyPI):
def try_multiple_operations(items):
for item in items:
try:
api.my_operation(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group)
for group in grouper(5, items)]
concurrent.futures.wait(futures)
Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.
So, how do you use threads instead of processes? Just change ProcessPoolExecutor
to ThreadPoolExecutor
.
If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.
Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?
Yes. In fact, there are two different ways to do it.
First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.
Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.
If you don't know which is appropriate for your program, usually it's the first.
I built this code using a number of other posts, with the following enhancements:
display: block
to the style, so spans workCSS:
.ellipsis {
white-space: nowrap;
overflow: hidden;
display: block;
}
.ellipsis.multiline {
white-space: normal;
}
jquery.ellipsis.js
(function ($) {
// this is a binary search that operates via a function
// func should return < 0 if it should search smaller values
// func should return > 0 if it should search larger values
// func should return = 0 if the exact value is found
// Note: this function handles multiple matches and will return the last match
// this returns -1 if no match is found
function binarySearch(length, func) {
var low = 0;
var high = length - 1;
var best = -1;
var mid;
while (low <= high) {
mid = ~ ~((low + high) / 2); //~~ is a fast way to convert something to an int
var result = func(mid);
if (result < 0) {
high = mid - 1;
} else if (result > 0) {
low = mid + 1;
} else {
best = mid;
low = mid + 1;
}
}
return best;
}
// setup handlers for events for show/hide
$.each(["show", "toggleClass", "addClass", "removeClass"], function () {
//get the old function, e.g. $.fn.show or $.fn.hide
var oldFn = $.fn[this];
$.fn[this] = function () {
// get the items that are currently hidden
var hidden = this.find(":hidden").add(this.filter(":hidden"));
// run the original function
var result = oldFn.apply(this, arguments);
// for all of the hidden elements that are now visible
hidden.filter(":visible").each(function () {
// trigger the show msg
$(this).triggerHandler("show");
});
return result;
};
});
// create the ellipsis function
// when addTooltip = true, add a title attribute with the original text
$.fn.ellipsis = function (addTooltip) {
return this.each(function () {
var el = $(this);
if (el.is(":visible")) {
if (el.css("overflow") === "hidden") {
var content = el.html();
var multiline = el.hasClass('multiline');
var tempElement = $(this.cloneNode(true))
.hide()
.css('position', 'absolute')
.css('overflow', 'visible')
.width(multiline ? el.width() : 'auto')
.height(multiline ? 'auto' : el.height())
;
el.after(tempElement);
var tooTallFunc = function () {
return tempElement.height() > el.height();
};
var tooWideFunc = function () {
return tempElement.width() > el.width();
};
var tooLongFunc = multiline ? tooTallFunc : tooWideFunc;
// if the element is too long...
if (tooLongFunc()) {
var tooltipText = null;
// if a tooltip was requested...
if (addTooltip) {
// trim leading/trailing whitespace
// and consolidate internal whitespace to a single space
tooltipText = $.trim(el.text()).replace(/\s\s+/g, ' ');
}
var originalContent = content;
var createContentFunc = function (i) {
content = originalContent.substr(0, i);
tempElement.html(content + "…");
};
var searchFunc = function (i) {
createContentFunc(i);
if (tooLongFunc()) {
return -1;
}
return 0;
};
var len = binarySearch(content.length - 1, searchFunc);
createContentFunc(len);
el.html(tempElement.html());
// add the tooltip if appropriate
if (tooltipText !== null) {
el.attr('title', tooltipText);
}
}
tempElement.remove();
}
}
else {
// if this isn't visible, then hook up the show event
el.one('show', function () {
$(this).ellipsis(addTooltip);
});
}
});
};
// ellipsification for items with an ellipsis
$(document).ready(function () {
$('.ellipsis').ellipsis(true);
});
} (jQuery));
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
private void drawArrows(Point[] point, Canvas canvas, Paint paint) {
float [] points = new float[8];
points[0] = point[0].x;
points[1] = point[0].y;
points[2] = point[1].x;
points[3] = point[1].y;
points[4] = point[2].x;
points[5] = point[2].y;
points[6] = point[0].x;
points[7] = point[0].y;
canvas.drawVertices(VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
Path path = new Path();
path.moveTo(point[0].x , point[0].y);
path.lineTo(point[1].x,point[1].y);
path.lineTo(point[2].x,point[2].y);
canvas.drawPath(path,paint);
}
I liked this question and some answers was helpful to me, but i need to convert the xml to one domination array, so i will post my solution maybe someone need it later:
<?php
$xml = json_decode(json_encode((array)simplexml_load_string($xml)),1);
$finalItem = getChild($xml);
var_dump($finalItem);
function getChild($xml, $finalItem = []){
foreach($xml as $key=>$value){
if(!is_array($value)){
$finalItem[$key] = $value;
}else{
$finalItem = getChild($value, $finalItem);
}
}
return $finalItem;
}
?>
Simple, use array_intersect()
instead:
$result = array_intersect($array1, $array2);
Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013
I know I'm coming to this very late. However, for anyone who's searching, I thought I'd publish what FINALLY worked for me. I'm not claiming it's the best solution - only that it worked.
Our WebApi service uses the config.EnableCors(corsAttribute) method. However, even with that, it would still fail on the pre-flight requests. @Mihai-Andrei Dinculescu's answer provided the clue for me. First of all, I added his Application_BeginRequest() code to flush the options requests. That STILL didn't work for me. The issue is that WebAPI still wasn't adding any of the expected headers to the OPTIONS request. Flushing it alone didn't work - but it gave me an idea. I added the custom headers that would otherwise be added via the web.config to the response for the OPTIONS request. Here's my code:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:44343");
Response.Headers.Add("Access-Control-Allow-Headers",
"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Response.Headers.Add("Access-Control-Allow-Credentials", "true");
Response.Flush();
}
}
Obviously, this only applies to the OPTIONS requests. All other verbs are handled by the CORS configuration. If there's a better approach to this, I'm all ears. It feels like a cheat to me and I would prefer if the headers were added automatically, but this is what finally worked and allowed me to move on.
Just add the this annotation @Temporal(TemporalType.DATE)
for a java.util.Date
field in your entity class.
More information available in this stackoverflow answer.
The easiest way is to pickle it using to_pickle
:
df.to_pickle(file_name) # where to save it, usually as a .pkl
Then you can load it back using:
df = pd.read_pickle(file_name)
Note: before 0.11.1 save
and load
were the only way to do this (they are now deprecated in favor of to_pickle
and read_pickle
respectively).
Another popular choice is to use HDF5 (pytables) which offers very fast access times for large datasets:
import pandas as pd
store = pd.HDFStore('store.h5')
store['df'] = df # save it
store['df'] # load it
More advanced strategies are discussed in the cookbook.
Since 0.13 there's also msgpack which may be be better for interoperability, as a faster alternative to JSON, or if you have python object/text-heavy data (see this question).
You must use the name of the subform control, not the name of the subform, though these are often the same:
Forms![MainForm]![subform control name Name].Form.Requery
Or, if you are on the main form:
Me.[subform control name Name].Form.Requery
More Info: http://www.mvps.org/access/forms/frm0031.htm
If on click of the button, you're opening a new fragment, just add android:clickable="true"
to the root view of the new fragment being opened.
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
Just put here some useful comment made by Jonathan Watt to drop all tables
MYSQL="mysql -h HOST -u USERNAME -pPASSWORD DB_NAME"
$MYSQL -BNe "show tables" | awk '{print "set foreign_key_checks=0; drop table `" $1 "`;"}' | $MYSQL
unset MYSQL
It helps me and I hope it could be useful
Alternative solution on Windows is to install python-certifi-win32 that will allow Python to use Windows Certificate Store.
pip install python-certifi-win32
You could also define a __call__()
method inside your someClass()
, which calls someClass.go()
and then pass an instance of someClass()
to the pool. This object is pickleable and it works fine (for me)...
class someClass(object):
def __init__(self):
pass
def f(self, x):
return x*x
def go(self):
p = Pool(4)
sc = p.map(self, range(4))
print sc
def __call__(self, x):
return self.f(x)
sc = someClass()
sc.go()
try this type of format:
SELECT to_char(sysdate,'dd-mm-rrrr') FROM dual
With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current
.
See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis
).
(Merged by Junio C Hamano -- gitster
-- in commit 3710f60, 07 Mar 2019)
branch
: introduce--show-current
display option
When called with
--show-current
,git branch
will print the current branch name and terminate.
Only the actual name gets printed, withoutrefs/heads
.
In detached HEAD state, nothing is output.
Intended both for scripting and interactive/informative use.
Unlikegit branch --list
, no filtering is needed to just get the branch name.
See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.
Element, Pseudo Element: d = 1 – (0,0,0,1)
Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
Id: b = 1 – (0,1,0,0)
Inline Style: a = 1 – (1,0,0,0)
Inline css ( html style attribute ) overrides css rules in style tag and css file
A more specific selector takes precedence over a less specific one.
Rules that appear later in the code override earlier rules if both have the same specificity.
When I tried to compute w^T * x
using numpy, it was super confusing for me as well. In fact, I couldn't implement it myself. So, this is one of the few gotchas in NumPy that we need to acquaint ourselves with.
As far as 1D array is concerned, there is no distinction between a row vector and column vector. They are exactly the same.
Look at the following examples, where we get the same result in all cases, which is not true in (the theoretical sense of) linear algebra:
In [37]: w
Out[37]: array([0, 1, 2, 3, 4])
In [38]: x
Out[38]: array([1, 2, 3, 4, 5])
In [39]: np.dot(w, x)
Out[39]: 40
In [40]: np.dot(w.transpose(), x)
Out[40]: 40
In [41]: np.dot(w.transpose(), x.transpose())
Out[41]: 40
In [42]: np.dot(w, x.transpose())
Out[42]: 40
With that information, now let's try to compute the squared length of the vector |w|^2
.
For this, we need to transform w
to 2D array.
In [51]: wt = w[:, np.newaxis]
In [52]: wt
Out[52]:
array([[0],
[1],
[2],
[3],
[4]])
Now, let's compute the squared length (or squared magnitude) of the vector w
:
In [53]: np.dot(w, wt)
Out[53]: array([30])
Note that we used w
, wt
instead of wt
, w
(like in theoretical linear algebra) because of shape mismatch with the use of np.dot(wt, w). So, we have the squared length of the vector as [30]
. Maybe this is one of the ways to distinguish (numpy's interpretation of) row and column vector?
And finally, did I mention that I figured out the way to implement w^T * x
? Yes, I did :
In [58]: wt
Out[58]:
array([[0],
[1],
[2],
[3],
[4]])
In [59]: x
Out[59]: array([1, 2, 3, 4, 5])
In [60]: np.dot(x, wt)
Out[60]: array([40])
So, in NumPy, the order of the operands is reversed, as evidenced above, contrary to what we studied in theoretical linear algebra.
P.S. : potential gotchas in numpy
Answer by Maragues made me check out logcat output. Appears that the path you pass to Uri needs to be prefixed with
file:/
Since it is a local path to your storage.
You may want too look at the path itself too.
`05-04 16:37:37.597: WARN/System.err(4065): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=/mnt/sdcard/mnt/sdcard/audio-android.3gp typ=audio/mp3 }`
Mount point seems to appear twice in the full path.
Try this, works!
Excel.Worksheet sheet = xlWorkSheet;
Excel.Series series1 = seriesCollection.NewSeries();
Excel.Range rng = (Excel.Range)xlWorkSheet.Range[xlWorkSheet.Cells[3, 13], xlWorkSheet.Cells[pp, 13]].Cells;
series1.Values = rng;
I was able to update it with markForCheck()
Import ChangeDetectorRef
import { ChangeDetectorRef } from '@angular/core';
Inject and instantiate it
constructor(private ref: ChangeDetectorRef) {
}
Finally mark change detection to take place
this.ref.markForCheck();
Here's an example where markForCheck() works and detectChanges() don't.
https://plnkr.co/edit/RfJwHqEVJcMU9ku9XNE7?p=preview
EDIT: This example doesn't portray the problem anymore :( I believe it might be running a newer Angular version where it's fixed.
(Press STOP/RUN to run it again)
I object the above answer and provide my own. csh
DOES have this capability and here is how it's done:
xxx |& some_exec # will pipe merged output to your some_exec
or
xxx |& cat > filename
or if you just want it to merge streams (to stdout) and not redirect to a file or some_exec:
xxx |& tee /dev/null
If you are converting string to float:
import re
A1 = [' "29.0" ',' "65.2" ',' "75.2" ']
float_values = [float(re.search(r'\d+.\d+',number).group()) for number in A1]
print(float_values)
>>> [29.0, 65.2, 75.2]
With the release of Java 5, the product version was made distinct from the developer version as described here
The reader acts like a generator. On a file with some fake data:
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Using operator.itemgetter as Ignacio suggests:
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> import operator
>>> sortedlist = sorted(data, key=operator.itemgetter(2), reverse=True)
>>> sortedlist
[['x', ' y', ' z'], ['a', ' b', ' c']]
Classic 8-bit LaTeX is very restricted in which UTF8 characters it can use; it's highly dependent on the encoding of the font you're using and which glyphs that font has available.
Since you don't give a specific example, it's hard to know exactly where the problem is — whether you're attempting to use a glyph that your font doesn't have or whether you're not using the correct font encoding in the first place.
Here's a minimal example showing how a few UTF8 characters can be used in a LaTeX document:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[utf8]{inputenc}
\begin{document}
‘Héllø—thêrè.’
\end{document}
You may have more luck with the [utf8x] encoding, but be slightly warned that it's no longer supported and has some idiosyncrasies compared with [utf8] (as far as I recall; it's been a while since I've looked at it). But if it does the trick, that's all that matters for you.
The easiest thing is to run the program, open the task manager, right-click the process and select properties, here is the full address
@user370305's answer is error prone and discouraged by Android OS Developers (check https://groups.google.com/forum/#!msg/android-developers/zH-2bovZSLg/L2YM8Z1N-HwJ)
There is a much more simpler approach:
On a BaseActivity that all Activities extend:
protected static boolean isVisible = false;
@Override
public void onResume() {
super.onResume();
setVisible(true);
}
@Override
public void onPause() {
super.onPause();
setVisible(false);
}
Whenever you need to check if any of your application activities is in foreground just check isVisible();
To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
You can see the error information from:
Magento/var/report
Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server.
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
Based on what type of RFC standard encoding you want to perform or if you need to customize your encoding you might want to create your own class.
/**
* UrlEncoder make it easy to encode your URL
*/
class UrlEncoder{
public const STANDARD_RFC1738 = 1;
public const STANDARD_RFC3986 = 2;
public const STANDARD_CUSTOM_RFC3986_ISH = 3;
// add more here
static function encode($string, $rfc){
switch ($rfc) {
case self::STANDARD_RFC1738:
return urlencode($string);
break;
case self::STANDARD_RFC3986:
return rawurlencode($string);
break;
case self::STANDARD_CUSTOM_RFC3986_ISH:
// Add your custom encoding
$entities = ['%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'];
$replacements = ['!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"];
return str_replace($entities, $replacements, urlencode($string));
break;
default:
throw new Exception("Invalid RFC encoder - See class const for reference");
break;
}
}
}
Use example:
$dataString = "https://www.google.pl/search?q=PHP is **great**!&id=123&css=#kolo&[email protected])";
$dataStringUrlEncodedRFC1738 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC1738);
$dataStringUrlEncodedRFC3986 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC3986);
$dataStringUrlEncodedCutom = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_CUSTOM_RFC3986_ISH);
Will output:
string(126) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP+is+%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(130) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP%20is%20%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(86) "https://www.google.pl/search?q=PHP+is+**great**!&id=123&css=#kolo&[email protected])"
* Find out more about RFC standards: https://datatracker.ietf.org/doc/rfc3986/ and urlencode vs rawurlencode?
I've solved using only @JsonIgnore
like @kryger has suggested.
So your getter will become:
@JsonIgnore
public String getEncryptedPwd() {
return this.encryptedPwd;
}
You can set @JsonIgnore
of course on field, setter or getter like described here.
And, if you want to protect encrypted password only on serialization side (e.g. when you need to login your users), add this @JsonProperty
annotation to your field:
@JsonProperty(access = Access.WRITE_ONLY)
private String encryptedPwd;
More info here.
That's right, if you're on a mac(unix) you won't see .git in finder(the file browser). You can follow the directions above to delete and there are git commands that allow you to delete files as well(they are sometimes difficult to work with and learn, for example: on making a 'git rm -r ' command you might be prompted with a .git/ not found. Here is the git command specs:
usage: git rm [options] [--] ...
-n, --dry-run dry run
-q, --quiet do not list removed files
--cached only remove from the index
-f, --force override the up-to-date check
-r allow recursive removal
--ignore-unmatch exit with a zero status even if nothing matched
When I had to do this, deleting the objects and refs didn't matter. After I deleted the other files in the .git, I initialized a git repo with 'git init' and it created an empty repo.
Using System.Web.HttpContext.Current.User.Identity.Name
should work.
Please check the IIS Site settings on the server that is hosting your site by doing the following:
Go to IIS ? Sites ? Your Site ? Authentication
Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.
Now System.Web.HttpContext.Current.User.Identity.Name
should return something like this:
domain\username
Yes it is possible. You need one ON for each join table.
LEFT JOIN ab
ON ab.sht = cd.sht
LEFT JOIN aa
ON aa.sht = cd.sht
Incidentally my personal formatting preference for complex SQL is described in http://bentilly.blogspot.com/2011/02/sql-formatting-style.html. If you're going to be writing a lot of this, it likely will help.
I used this way in my code
$(function(){
$('.block').affix();
})
You need #include<string>
to use string
AND #include<iostream>
to use cin
and cout
. (I didn't get it when I read the answers). Here's some code which works:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string name;
cin >> name;
string message("hi");
cout << name << message;
return 0;
}
Beside of one view model in asp.net you can also make multiple partial views and assign different model view to every view, for example:
@{
Layout = null;
}
@model Person;
<input type="text" asp-for="PersonID" />
<input type="text" asp-for="PersonName" />
then another partial view Model for order model
@{
Layout = null;
}
@model Order;
<input type="text" asp-for="OrderID" />
<input type="text" asp-for="TotalSum" />
then in your main view load both partial view by
<partial name="PersonPartialView" />
<partial name="OrderPartialView" />
This completely removes the modal from the DOM , is working for the "appended" modals as well .
$(document).on('hidden.bs.modal','#pickoptionmodal',function(e){
e.preventDefault();
$("#pickoptionmodal").remove();
});
Here's how to do it using Xerces2. A tutorial for this, here (req. signup).
Original attribution: blatantly copied from here:
import org.apache.xerces.parsers.DOMParser;
import java.io.File;
import org.w3c.dom.Document;
public class SchemaTest {
public static void main (String args[]) {
File docFile = new File("memory.xml");
try {
DOMParser parser = new DOMParser();
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setProperty(
"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
"memory.xsd");
ErrorChecker errors = new ErrorChecker();
parser.setErrorHandler(errors);
parser.parse("memory.xml");
} catch (Exception e) {
System.out.print("Problem parsing the file.");
}
}
}
I don't want to name names, but someone appears to be completely wrong. The referenced standards body stated the following: submissions 465 tcp Message Submission over TLS protocol [IESG] [IETF_Chair] 2017-12-12 [RFC8314]
If you are so inclined, you may wish to read the referenced RFC.
This seems to clearly imply that port 465 is the best way to force encrypted communication and be sure that it is in place. Port 587 offers no such guarantee.
In oracle, generally speaking, there are number of facts that I will mention in following section:
Therefore, your question, "to see all tablespaces and datafiles belong to SCOTT" is s bit wrong.
However, there are some DBA views encompass information about all database objects, regardless of the owner. Only users with DBA privileges can access these views: DBA_DATA_FILES, DBA_TABLESPACES, DBA_FREE_SPACE, DBA_SEGMENTS.
So, connect to your DB as sysdba and run query through these helpful views. For example this query can help you to find all tablespaces and their data files that objects of your user are located:
SELECT DISTINCT sgm.TABLESPACE_NAME , dtf.FILE_NAME
FROM DBA_SEGMENTS sgm
JOIN DBA_DATA_FILES dtf ON (sgm.TABLESPACE_NAME = dtf.TABLESPACE_NAME)
WHERE sgm.OWNER = 'SCOTT'
To just return a list containing the most common words:
from collections import Counter
words=["i", "love", "you", "i", "you", "a", "are", "you", "you", "fine", "green"]
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
print most_common_words
this prints:
['you', 'i', 'a']
the 3 in "most_common(3)
", specifies the number of items to print.
Counter(words).most_common()
returns a a list of tuples with each tuple having the word as the first member and the frequency as the second member.The tuples are ordered by the frequency of the word.
`most_common = [item for item in Counter(words).most_common()]
print(str(most_common))
[('you', 4), ('i', 2), ('a', 1), ('are', 1), ('green', 1), ('love',1), ('fine', 1)]`
"the word for word, word_counter in
", extracts only the first member of the tuple.
I find I rarely have need to use getCanonicalPath()
but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdir
System property returns, then this method will return the "full" filename.
Maybe "clearing cache" is not as easy as it should be. Instead of clearing cache on my browsers, I realized that "touching" the file will actually change the date of the source file cached on the server (Tested on Edge, Chrome and Firefox) and most browsers will automatically download the most current fresh copy of whats on your server (code, graphics any multimedia too). I suggest you just copy the most current scripts on the server and "do the touch thing" solution before your program runs, so it will change the date of all your problem files to a most current date and time, then it downloads a fresh copy to your browser:
<?php
touch('/www/control/file1.js');
touch('/www/control/file2.js');
touch('/www/control/file2.js');
?>
...the rest of your program...
It took me some time to resolve this issue (as many browsers act differently to different commands, but they all check time of files and compare to your downloaded copy in your browser, if different date and time, will do the refresh), If you can't go the supposed right way, there is always another usable and better solution to it. Best Regards and happy camping.
Simply run sudo dpkg-reconfigure mysql-server-5.7
You can find the version you have installed by running dpkg --get-selections | grep mysql-server
Unit testing is directed at the smallest part of the implementation possible. In Java this means you are testing a single class. If the class depends on other classes these are faked.
When your test calls more than one class, it's an integration test.
Full test suites can take a long time to run, so after a change many teams run some quick to complete tests to detect significant breakages. For example, you have broken the URIs to essential resources. These are the smoke tests.
Regression tests run on every build and allow you to refactor effectively by catching what you break. Any kind of test can be regression test, but I find unit tests are most helpful finding the source of fault.
I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:
You need to frame your query like this
select entity from Entity as entity where ...
Also check such case, it perfectly works for me:
public List<User> findByRole(String role) {
Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
query.setString("role_name", role);
@SuppressWarnings("unchecked")
List<User> users = (List<User>) query.list();
return users;
}
So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.
To render more than one whitespace on most web browsers use
instead of normal white spaces.
echo "<p>Hello punt"; // This will render as Hello Punt (with 4 white spaces)
echo "<p> Hello punt"; // This will render as Hello punt (with one space)
For showing data in raw format (with exact number of spaces and "enters") use HTML <pre>
tag.
echo "<pre>Hello punt</pre>"; //Will render exactly as written here (8 white spaces)
Or you can use some CSS to style current block, not to break text or strip spaces (I don't know, but this one)
Any way you do the output will be the same but the browser itself strips double white spaces and renders as one.
Wouldn't occam's razor say to just do this until you need something more complex? It's a bit of a hack, but may suit the needs of someone that wants a quick fix.
.navbar-default .container-fluid{
background-color:#62ADD7; // Change the color
margin: -1px -1px 10px -1px; // Get rid of the border
}
<a id="reset-authenticator" asp-page="./ResetAuthenticator"><input type="button" class="btn btn-primary" value="Reset app" /></a>
_x000D_
When you create a new class file, try to mark the check box near
public static void main(String[] args) {
this will help you to fix the problem.
As mentioned you can sort by:
Comparable
Comparator
to Collections.sort
If you do both, the Comparable
will be ignored and Comparator
will be used. This helps that the value objects has their own logical Comparable
which is most reasonable sort for your value object, while each individual use case has its own implementation.
If this is useful for anyone, the HOSTALIASES
env variable worked for me:
echo "fakehost realhost" > /etc/host.aliases
export HOSTALIASES=/etc/host.aliases
There are a few possible ways to do this.
One would be
SELECT
...
ORDER BY
CASE
WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value)
ELSE 9999999 -- or something huge
END,
value
the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics.
Note that the performance of this query is probably at least moderately ghastly on large amounts of data.
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
I wrapped Jsch with some utility methods to make it a bit friendlier and called it
Available here: https://github.com/willwarren/jscp
SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.
Usage:
// create secure context
SecureContext context = new SecureContext("userName", "localhost");
// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));
// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());
Jscp.exec(context,
"src/dir",
"destination/path",
// regex ignore list
Arrays.asList("logs/log[0-9]*.txt",
"backups")
);
Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.
Try this
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
//your code here that talks with the UI level widgets/ try to access the UI
//elements from this block because this piece of snippet will run in the UI/MainThread.
}
});
You can think of an ArrayBuffer
as a typed Buffer
.
An ArrayBuffer
therefore always needs a type (the so-called "Array Buffer View"). Typically, the Array Buffer View has a type of Uint8Array
or Uint16Array
.
There is a good article from Renato Mangini on converting between an ArrayBuffer and a String.
I have summarized the essential parts in a code example (for Node.js). It also shows how to convert between the typed ArrayBuffer
and the untyped Buffer
.
function stringToArrayBuffer(string) {
const arrayBuffer = new ArrayBuffer(string.length);
const arrayBufferView = new Uint8Array(arrayBuffer);
for (let i = 0; i < string.length; i++) {
arrayBufferView[i] = string.charCodeAt(i);
}
return arrayBuffer;
}
function arrayBufferToString(buffer) {
return String.fromCharCode.apply(null, new Uint8Array(buffer));
}
const helloWorld = stringToArrayBuffer('Hello, World!'); // "ArrayBuffer" (Uint8Array)
const encodedString = new Buffer(helloWorld).toString('base64'); // "string"
const decodedBuffer = Buffer.from(encodedString, 'base64'); // "Buffer"
const decodedArrayBuffer = new Uint8Array(decodedBuffer).buffer; // "ArrayBuffer" (Uint8Array)
console.log(arrayBufferToString(decodedArrayBuffer)); // prints "Hello, World!"
Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
AS new
ON DUPLICATE KEY UPDATE
age = new.age
...
For earlier versions use the keyword VALUES
(see reference, deprecated with MySQL 8.0.20).
INSERT INTO beautiful (name, age)
VALUES
('Helen', 24),
('Katrina', 21),
('Samia', 22),
('Hui Ling', 25),
('Yumie', 29)
ON DUPLICATE KEY UPDATE
age = VALUES(age),
...
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
I think you could just use the String#length method...
http://ruby-doc.org/core-1.9.3/String.html#method-i-length
Example:
text = 'The quick brown fox jumps over the lazy dog.'
puts text.length > 25 ? 'Too many characters' : 'Accepted'
To quote Wikipedia:
ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably.
A DBMS that supports transactions will strive to support all of these properties - any commercial DBMS (as well as several open-source DBMSs) provide full ACID 'support' - although it's often possible (for example, with varying isolation levels in MSSQL) to lessen the ACIDness - thus losing the guarantee of fully transactional behaviour.
Assuming that you are using a spfile to start the database
alter system set open_cursors = 1000 scope=both;
If you are using a pfile instead, you can change the setting for the running instance
alter system set open_cursors = 1000
You would also then need to edit the parameter file to specify the new open_cursors
setting. It would generally be a good idea to restart the database shortly thereafter to make sure that the parameter file change works as expected (it's highly annoying to discover months later the next time that you reboot the database that some parameter file change than no one remembers wasn't done correctly).
I'm also hoping that you are certain that you actually need more than 300 open cursors per session. A large fraction of the time, people that are adjusting this setting actually have a cursor leak and they are simply trying to paper over the bug rather than addressing the root cause.
To remove whitespace from only the beginning and end of a string in Swift:
string.trimmingCharacters(in: .whitespacesAndNewlines)
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
Always use latest SDK version to build:
compileSdkVersion 23
It does not affect runtime behavior, but give you latest programming features.
In some cases - when not so many columns - useful the WINDOW functions FIRST_VALUE() and LAST_VALUE().
SELECT
FIRST_VALUE(timestamp) over (ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (ORDER BY timestamp ASC) as last_action
FROM events
This query sort data only once.
It can be used for getting fisrt and last rows by some ID
SELECT DISTINCT
order_id,
FIRST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as created_dt,
LAST_VALUE(timestamp) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_update_dt,
LAST_VALUE(action) over (PARTITION BY order_id ORDER BY timestamp ASC) as last_action
FROM events as x
Just figure out the difference in seconds (don't forget JS timestamps are actually measured in milliseconds) and decompose that value:
// get total seconds between the times
var delta = Math.abs(date_future - date_now) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60; // in theory the modulus is not required
EDIT code adjusted because I just realised that the original code returned the total number of hours, etc, not the number of hours left after counting whole days.
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
change to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
You could use the global application state.
Update:
Customize and then add this to your AndroidManifest.xml :
<application android:label="@string/app_name" android:debuggable="true" android:name=".CustomApplication"
And then have a class in your project like this :
package com.example;
import android.app.Application;
public class CustomApplication extends Application {
public int someVariable = -1;
}
And because "It can be accessed via getApplication() from any Activity or Service", you use it like this:
CustomApplication application = (CustomApplication)getApplication();
application.someVariable = 123;
Hope that helps.
If you deal with dates it is a good idea to look at the joda time library for a more sane Date manipulation model.
In Spring Boot 2 the spring.http.multipart
changed to spring.servlet.multipart
Im putting this in an answer because it's too long for a comment:
If you need the VM to be aware when the CheckBox
is changed, you should really bind the CheckBox
to the VM, and not a static value:
public class ViewModel
{
private bool _caseSensitive;
public bool CaseSensitive
{
get { return _caseSensitive; }
set
{
_caseSensitive = value;
NotifyPropertyChange(() => CaseSensitive);
Settings.Default.bSearchCaseSensitive = value;
}
}
}
XAML:
<CheckBox Content="Case Sensitive" IsChecked="{Binding CaseSensitive}"/>
This may work
::selection {
color: none;
background: none;
}
/* For Mozilla Firefox */
::-moz-selection {
color: none;
background: none;
}
You need to pass your components as children, like this:
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
<App>
<SampleComponent name="SomeName"/>
<App>,
document.body
);
And then append them in the component's body:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
{
this.props.children
}
</div>
);
}
});
You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:
var App = React.createClass({
getInitialState: function(){
return [
{id:1,name:"Some Name"}
]
},
addChild: function() {
// State change will cause component re-render
this.setState(this.state.concat([
{id:2,name:"Another Name"}
]))
}
render: function() {
return (
<div>
<h1>App main component! </h1>
<button onClick={this.addChild}>Add component</button>
{
this.state.map((item) => (
<SampleComponent key={item.id} name={item.name}/>
))
}
</div>
);
}
});
With LESS the actual mixin is in vendor-prefixes.less
.placeholder(@color: @input-color-placeholder) {
...
}
This mixin is called in forms.less on line 133:
.placeholder();
Your solution in LESS is:
.placeholder(#fff);
Imho the best way to go. Just use Winless or a composer compiler like Gulp/Grunt works, too and even better/faster.
grep -r --include=*.{cc,h} "hello" .
This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this .
(current) directory
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
This is all perfectly normal. Microsoft added sequences
in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.
If you want to have the old behaviour, you can:
You'll need a using System.Net.Http
at the top.
You can use the properties outline
and outline-offset
with a negative value instead of using a regular border
, works for me:
div{_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
background-color: grey;_x000D_
margin-bottom: 10px; _x000D_
}_x000D_
_x000D_
div#border{_x000D_
border: 2px solid red;_x000D_
}_x000D_
_x000D_
div#outline{_x000D_
outline: 2px solid red;_x000D_
outline-offset: -2px;_x000D_
}
_x000D_
Using a regular border._x000D_
<div id="border"></div>_x000D_
_x000D_
Using outline and outline-offset._x000D_
<div id="outline"></div>
_x000D_
You can use the field truncation option to avoid quite so many %x08
characters. For example:
git log --pretty='format:%h %s%n\t%<(12,trunc)%ci%x08%x08, %an <%ae>'
is equivalent to:
git log --pretty='format:%h %s%n\t%ci%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08%x08, %an <%ae>'
And quite a bit easier on the eyes.
Better still, for this particular example, using %cd
will honor the --date=<format>
, so if you want YYYY-MM-DD
, you can do this and avoid %<
and %x08
entirely:
git log --date=short --pretty='format:%h %s%n\t%cd, %an <%ae>'
I just noticed this was a bit circular with respect to the original post but I'll leave it in case others arrived here with the same search parameters I did.
var output = a.substring(0, position) + b + a.substring(position);
Edit: replaced .substr
with .substring
because .substr
is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
There is a very simple answer to this messy problem--the SUBSTITUTE function. In your example above:
=IF((1/1/INDEX(A,B,C))<>"",(1/1/INDEX(A,B,C)),"")
Can be rewritten as follows:
=SUBSTITUTE((1/1/INDEX(A,B,C), " ", "")
While executing multiple lines of code in R, you need to first select all the lines of code and then click on "Run". This error usually comes up when we don't select our statements and click on "Run".
max(stats, key=stats.get)
In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app)
file and paste this (at the end) :-
dependencies {
compile "com.android.support:appcompat-v7:21.0.+"
}
Note that this dependencies
is different from the dependencies
inside buildscript
in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"
Source : https://developer.android.com/tools/support-library/setup.html#add-library
This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
You can simply cast strings to DateTime:
[DateTime]"2020-7-16"
or
[DateTime]"Jul-16"
or
$myDate = [DateTime]"Jul-16";
And you can format the resulting DateTime variable by doing something like this:
'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
or
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
or
$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate
I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.
/******************
Fit the body to the edges of the screen
******************/
body {
margin:0;
padding:0;
}
header {
background:black;
width:100%;
}
.header {
height:200px;
}
nav {
width:100%;
background:lightseagreen;
}
.nav {
padding:0;
margin:0;
}
.nav a {
padding:10px;
font-family:tahoma;
font-size:12pt;
color:white;
}
/******************
Centered wrapper, all other content divs will go inside this and will never exceed the width of 960px.
******************/
.wrapper {
width:960px;
max-width:100%;
margin:0 auto;
}
<!-------- Start HTML ---------->
<body>
<header>
<div id="header" class="wrapper">
</div>
</header>
<nav>
<div id="nav" class="wrapper">
</div>
</nav>
</body>
You must be in the same directory of Gemfile
<script type="text/javascript" >
function aa()
{
var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
var ObjUl = $('<ul></ul>');
for (i = 0; i < YourArray.length; i++)
{
var Objli = $('<li></li>');
var Obja = $('<a></a>');
ObjUl.addClass("ui-menu-item");
ObjUl.attr("role", "menuitem");
Obja.addClass("ui-all");
Obja.attr("tabindex", "-1");
Obja.text(YourArray[i]);
Objli.append(Obja);
ObjUl.append(Objli);
}
$('.DivSai').append(ObjUl);
}
</script>
</head>
<body onload="aa()">
<form id="form1" runat="server">
<div class="DivSai" >
</div>
</form>
</body>
I found this suggestion useful in my case:
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
Check this link of Xavier's comment on github.
This approach whitelists the entire params[:measurement][:groundtruth] object.
Using the original questions attributes:
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
I'd like to add to OJ's kind clarifications.
Virtual inheritance doesn't come without a price. Like with all things virtual, you get a performance hit. There is a way around this performance hit that is possibly less elegant.
Instead of breaking the diamond by deriving virtually, you can add another layer to the diamond, to get something like this:
B
/ \
D11 D12
| |
D21 D22
\ /
DD
None of the classes inherit virtually, all inherit publicly. Classes D21 and D22 will then hide virtual function f() which is ambiguous for DD, perhaps by declaring the function private. They'd each define a wrapper function, f1() and f2() respectively, each calling class-local (private) f(), thus resolving conflicts. Class DD calls f1() if it wants D11::f() and f2() if it wants D12::f(). If you define the wrappers inline you'll probably get about zero overhead.
Of course, if you can change D11 and D12 then you can do the same trick inside these classes, but often that is not the case.
if you need to change specific option from the select menu you can do it like this
option[value="Basic"] {
color:red;
}
or you can change them all
select {
color:red;
}
I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:
/opt/azure/containers/provision.sh
To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:
systemctl enable kubectl
systemctl restart kubectl
I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.
Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.
sub Demo_array()
Dim MyArray as Variant, MyArray2 as Variant, i as Long
MyArray = Array(1, 10, 20, 50) 'The key - the powerful Array() statement
MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too
For i = 0 to UBound(MyArray)
Debug.Print i, MyArray(i)
Next i
For i = 0 to UBound(MyArray2)
Debug.Print i, MyArray2(i)
Next i
End Sub
I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type
, "Egg"
in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.
If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.
Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.
My example for anonimous types:
private object ConvertNullable(object value, Type nullableType)
{
Type resultType = typeof(Nullable<>).MakeGenericType(nullableType.GetGenericArguments());
return Activator.CreateInstance(resultType, Convert.ChangeType(value, nullableType.GetGenericArguments()[0]));
}
...
Type anonimousType = typeof(Nullable<int>);
object nullableInt1 = ConvertNullable("5", anonimousType);
// or evident Type
Nullable<int> nullableInt2 = (Nullable<int>)ConvertNullable("5", typeof(Nullable<int>));
No object will ever be an IThingy as interfaces are all abstract by definition.
The object you have that was first serialized was of some concrete type, implementing the abstract interface. You need to have this same concrete class revive the serialized data.
The resulting object will then be of some type that implements the abstract interface you are looking for.
From the documentation it follows that you can use
(Thingy)JsonConvert.DeserializeObject(jsonString, typeof(Thingy));
when deserializing to inform JSON.NET about the concrete type.
Async arrow functions look like this:
const foo = async () => {
// do something
}
Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymous form works as well:
const foo = async function() {
// do something
}
An async function declaration looks like this:
async function foo() {
// do something
}
Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
Build solution only builds those projects which have changed in the solution, and does not effect assemblies that have not changed,
ReBuild first cleans, all the assemblies from the solution and then builds entire solution regardless of changes done.
Clean, simply cleans the solution.
you can use layout_constraintCircle for center view inside ConstraintLayout.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mparent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/btn_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_home_black_24dp"
app:layout_constraintCircle="@id/mparent"
app:layout_constraintCircleRadius="0dp"
/>
</android.support.constraint.ConstraintLayout>
with constraintCircle to parent and zero radius you can make your view be center of parent.
Update: Please see marked answer as a better solution to implement this. The following solution is no longer required.
Converting the json date to this format "mm/dd/yyyy HH:MM:ss"
dateFormat is a jasondate format.js file found at blog.stevenlevithan.com
var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");
Try one of these:
Use column alias:
ORDER BY RadioServiceCodeId,RadioService
Use column position:
ORDER BY 1,2
You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.
There's another use I have for git mv
not mentioned above.
Since discovering git add -p
(git add's patch mode; see http://git-scm.com/docs/git-add), I like to use it to review changes as I add them to the index. Thus my workflow becomes (1) work on code, (2) review and add to index, (3) commit.
How does git mv
fit in? If moving a file directly then using git rm
and git add
, all changes get added to the index, and using git diff to view changes is less easy (before committing). Using git mv
, however, adds the new path to the index but not changes made to the file, thus allowing git diff
and git add -p
to work as usual.
You should also try my ServiceStack JsonSerializer - it's the fastest .NET JSON serializer at the moment based on the benchmarks of the leading JSON serializers and supports serializing any POCO Type, DataContracts, Lists/Dictionaries, Interfaces, Inheritance, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>();
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
History from Learn Python the Hard Way:
Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.
They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.
Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object
class or from another class that inherited from object
:
class NewStyle(object):
pass
Another example is:
class AnotherExampleOfNewStyle(NewStyle):
pass
While an old-style base class looks like this:
class OldStyle():
pass
And an old-style child class looks like this:
class OldStyleSubclass(OldStyle):
pass
You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2
There isn't a simple solution. The way I've done it in the past is to start another process to run either the ps
command on Unix-like systems, or the tasklist
command on Windows, and then parse the output of that command for the PID I want. In reality, I ended up putting that code into a separate shell script for each platform which just returned the PID, so that I could keep the Java piece as platform independent as possible. This doesn't work well for short-lived tasks, but that wasn't an issue for me.
I think using LINQ is easier:
Dns.GetHostEntry(Dns.GetHostName())
.AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.ToString()
I normally have all of my work in a dropbox folder. This ensures me that I would have the current folder available outside my local machine and Github. I think it's my other step to guarantee a "version control" other than git. You can follow this in order to revert your file to previous versions of your dropbox files
Hope this helps.
Use the other answers if you don't mind losing local changes. This method can still wreck your remote if you choose the wrong commit hash to go back to.
If you just want to make the remote match a commit that's anywhere in your local repo:
git log
to find the commit you want to the remote to be at. git log -p
to see changes, or git log --graph --all --oneline --decorate
to see a compact tree.Run a command like:
git push --force <remote> <commit-ish>:<the remote branch>
e.g.
git push --force origin 606fdfaa33af1844c86f4267a136d4666e576cdc:master
or
git push --force staging v2.4.0b2:releases
I use convenient alias (git go
) for viewing history as in step 2, which can be added like so:
git config --global alias.go 'log --graph --all --decorate --oneline'`
in case your project use dagger, and then this error show up you can add this at android manifest
<application
...
android: name = ".BaseApplication"
...> ...
I think a better way to do this is to change the base_size
argument. It will increase the text sizes consistently.
g + theme_grey(base_size = 22)
As seen here.
CGI is an interface specification between a web server (HTTP server) and an executable program of some type that is to handle a particular request.
It describes how certain properties of that request should be communicated to the environment of that program and how the program should communicate the response back to the server and how the server should 'complete' the response to form a valid reply to the original HTTP request.
For a while CGI was an IETF Internet Draft and as such had an expiry date. It expired with no update so there was no CGI 'standard'. It is now an informational RFC, but as such documents common practice and isn't a standard itself. rfc3875.txt, rfc3875.html
Programs implementing a CGI interface can be written in any language runnable on the target machine. They must be able to access environment variables and usually standard input and they generate their output on standard output.
Compiled languages such as C were commonly used as were scripting languages such as perl, often using libraries to make accessing the CGI environment easier.
One of the big disadvantages of CGI is that a new program is spawned for each request so maintaining state between requests could be a major performance issue. The state might be handled in cookies or encoded in a URL, but if it gets to large it must be stored elsewhere and keyed from encoded url information or a cookie. Each CGI invocation would then have to reload the stored state from a store somewhere.
For this reason, and for a greatly simple interface to requests and sessions, better integrated environments between web servers and applications are much more popular. Environments like a modern php implementation with apache integrate the target language much better with web server and provide access to request and sessions objects that are needed to efficiently serve http requests. They offer a much easier and richer way to write 'programs' to handle HTTP requests.
Whether you wrote a CGI script rather depends on interpretation. It certainly did the job of one but it is much more usual to run php as a module where the interface between the script and the server isn't strictly a CGI interface.
An easy way to check the CPU usage is to use the adb tool w/ top. I.e.:
adb shell top -m 10
Plain JavaScript modern solution if you don't need IE support (Array.from
is not supported in IE).
You can use combination of Set
and Array.from
.
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];_x000D_
const set = new Set(arr);_x000D_
const uniqueArr = Array.from(set);_x000D_
_x000D_
console.log(uniqueArr);
_x000D_
The Set
object lets you store unique values of any type, whether primitive values or object references.
The Array.from()
method creates a new Array instance from an array-like or iterable object.
Also Array.from()
can be replaced with spread operator.
const arr = [1, 1, 11, 2, 4, 2, 5, 3, 1];_x000D_
const set = new Set(arr);_x000D_
const uniqueArr = [...set];_x000D_
_x000D_
console.log(uniqueArr);
_x000D_
use CHAR(10)
for New Line in SQL
char(9)
for Tab
and Char(13)
for Carriage Return
The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.
fastest way
function:
var x=function(a,b,c,d){d=[];c=b-a+1;while(c--){d[c]=b--}return d},
theArray=x(lowEnd,highEnd);
or
var arr=[],c=highEnd-lowEnd+1;
while(c--){arr[c]=highEnd--}
EDIT
readable version
var arr = [],
c = highEnd - lowEnd + 1;
while ( c-- ) {
arr[c] = highEnd--
}
Demo
FOR THE DOWNVOTERS
performance
http://jsperf.com/for-push-while-set/2
faster in ie and 3x faster in firefox
only on aipad air the for loop is a little faster.
tested on win8, osx10.8, ubuntu14.04, ipad, ipad air, ipod;
with chrome,ff,ie,safari,mobile safari.
i would like to see the performance on older ie browsers where the for loop isn't that optimized!
assertTrue
will fail if the checked value is false, and assertFalse
will do the opposite: fail if the checked value is true.
Another thing, your last assertEquals will very likely fail, as it will compare the "Book was already checked out" string with the output of m1.checkOut(b1,p2). It needs a third parameter (the second value to check for equality).
I think you can't increase the time for query execution, but you need to increase the timeout for the request.
Execution Timeout Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. (Default time is 110 seconds.)
For Details, please have a look at https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx
You can do in the web.config. e.g
<httpRuntime maxRequestLength="2097152" executionTimeout="600" />
I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain
taken from NSURLError.h
/*!
@enum NSURL-related Error Codes
@abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};
Basically, yes. You write alert('<?php echo($phpvariable); ?>');
There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.
SVN is case-sensitive. Make sure that you're spelling it properly. If it got renamed, you can relocate the working folder to the new URL. See https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html
I think you're confused by different paradigms here. First, war files and server deployment -- those things belong to Java Enterprise Edition (Java EE). These concepts have no real place in a spring-boot application, which follows a different model.
Spring-boot is responsible for creating an embedded container and running your services within it directly from standard jar files (although it can do a lot more). I think the intent of this model is to support micro-service development -- where each service has its own container and is completely self contained. You can use your code to generate Java EE apps too, but that would be silly considering that spring-boot is a lot easier (for certain types of application/service).
So, given this information you now have to decide what paradigm you're going to follow, and you need to follow that and only that.
Spring-boot is executable -- you just have to run the main method in the App class which you can do from the command line or using your favourite IDE or maven or gradle (tip: maven is the right answer). This will bring up a tomcat server (by default) and your service will be available within it. Given the configuration you posted above your service should be available at: http://localhost:7777/context/help
-- the context
is meant to be replaced with your context name, which you haven't shared.
You aren't meant to be creating a war, running tomcat, or deploying anything. None of that is necessary in spring-boot. The packaging in your pom should be jar
, not war
and the scope
of the spring-boot-starter-tomcat
should be removed -- it certainly isn't provided.
When you run your main method, the console output should tell you the context that you've registered; use that to get the URL right.
Having said all that, spring-boot has to exist in a JEE world for now (until it is widely adopted). For that reason, the spring people have documented an approach to building a war rather than an executable jar, for deployment to a servlet or JEE container. This allows a lot of the spring-boot tech to be used in environments where there are restrictions against using anything but wars (or ears). However, this is a just a response to the fact that such environments are quite common, and is not seen as a necessary, or even desirable, part of the solution.
If you're outside the request-response handling, you can still:
import os
import signal
sig = getattr(signal, "SIGKILL", signal.SIGTERM)
os.kill(os.getpid(), sig)
You can always escape the reserved keyword if you still want to make your query work!!
Just replace end with `end`
Here is the list of reserved keywords https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
I like Tony approach. It works, but I decided to implement in different way. Here my comments:
1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.
By the way, ui-if was removed. Now you have ng-if build-in.
2) I prefer to write a service like this:
angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {
var factory = {};
factory.getGridHeight = function(gridOptions) {
var length = gridOptions.data.length;
var rowHeight = 30; // your row height
var headerHeight = 40; // your header height
var filterHeight = 40; // your filter height
return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {
return value.replace(unit, '');
}
return factory;
});
And then in the controller write the following:
angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {
...
// Execute this when you have $scope.gridData loaded...
$scope.gridHeight = uiGridService.getGridHeight($scope.gridData);
And at the HTML file:
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>
When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.
3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.
$scope.gridData = {
enableSorting: true,
multiSelect: false,
enableRowSelection: true,
showFooter: false,
enableFiltering: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
enableGridMenu: true,
noUnselect: true,
expandableRowTemplate: 'subGrid.html',
expandableRowHeight: 380, // 10 rows * 30px + 40px (header) + 40px (filters)
onRegisterApi: function(gridApi) {
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));
if (row.isExpanded)
{
height += changedRowHeight;
}
else
{
height -= changedRowHeight;
}
$scope.jdeNewUserConflictsGridHeight = height + 'px';
});
},
columnDefs : [
{ field: 'GridField1', name: 'GridField1', enableFiltering: true }
]
}
I always do it like this:
$("#id").css("width", "50%");
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
You can use pandas.Series.map :
df['col'].map('str{}'.format)
It will apply the word "str" before all your values.
open powershell and run below command:
import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv -NoTypeInformation -Encoding UTF8
The definition of SIZE_T
is found at:
https://msdn.microsoft.com/en-us/library/cc441980.aspx and https://msdn.microsoft.com/en-us/library/cc230394.aspx
Pasting here the required information:
SIZE_T
is a ULONG_PTR
representing the maximum number of bytes to which a pointer can point.
This type is declared as follows:
typedef ULONG_PTR SIZE_T;
A ULONG_PTR
is an unsigned long type used for pointer precision. It is used when casting a pointer to a long type to perform pointer arithmetic.
This type is declared as follows:
typedef unsigned __int3264 ULONG_PTR;
You should always return the same type on all case condition:
In the first one you have an character and on the else you have an int.
You can use:
Select convert(varchar(11),isnull(totalamount,0))
or if you want with your solution:
Case when total_amount = 0 then '0'
else convert(varchar(11),isnull(total_amount, 0))
end as total_amount
I had same issue while moving from AWS to Azure
For express & aws, you can already use, existing time() and timeEnd()
For Azure, use this: https://github.com/manoharreddyporeddy/my-nodejs-notes/blob/master/performance_timers_helper_nodejs_azure_aws.js
These time() and timeEnd() use the existing hrtime() function, which give high-resolution real time.
Hope this helps.
If you're open to a Perl solution, here one similar to fedorqui's awk solution:
perl -F/ -lane 'print $F[-1]' input
-F/
specifies /
as the field separator
$F[-1]
is the last element in the @F
autosplit array
JSON of unknown format to HashMap
public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
writeJson("JsonFile.json");
readgson("JsonFile.json");
}
public static void readgson(String file) {
try {
System.out.println( "Reading JSON file from Java program" );
FileReader fileReader = new FileReader( file );
com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
if ( keys.isEmpty() ) {
System.out.println( "Empty JSON Object" );
}else {
Map<String, Object> map = json_UnKnown_Format( keys );
System.out.println("Json 2 Map : "+map);
}
} catch (IOException ex) {
System.out.println("Input File Does not Exists.");
}
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
Map<String, Object> jsonMap = new HashMap<String, Object>();
for (Entry<String, JsonElement> entry : keys) {
String keyEntry = entry.getKey();
System.out.println(keyEntry + " : ");
JsonElement valuesEntry = entry.getValue();
if (valuesEntry.isJsonNull()) {
System.out.println(valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonPrimitive()) {
System.out.println("P - "+valuesEntry);
jsonMap.put(keyEntry, valuesEntry);
}else if (valuesEntry.isJsonArray()) {
JsonArray array = valuesEntry.getAsJsonArray();
List<Object> array2List = new ArrayList<Object>();
for (JsonElement jsonElements : array) {
System.out.println("A - "+jsonElements);
array2List.add(jsonElements);
}
jsonMap.put(keyEntry, array2List);
}else if (valuesEntry.isJsonObject()) {
com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());
Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
}
}
return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {
JSONObject json = new JSONObject();
json.put("Key1", "Value");
json.put("Key2", 777); // Converts to "777"
json.put("Key3", null);
json.put("Key4", false);
JSONArray jsonArray = new JSONArray();
jsonArray.put("Array-Value1");
jsonArray.put(10);
jsonArray.put("Array-Value2");
json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]
JSONObject jsonObj = new JSONObject();
jsonObj.put("Obj-Key1", 20);
jsonObj.put("Obj-Key2", "Value2");
jsonObj.put(4, "Value2"); // Converts to "4"
json.put("InnerObject", jsonObj);
JSONObject jsonObjArray = new JSONObject();
JSONArray objArray = new JSONArray();
objArray.put("Obj-Array1");
objArray.put(0, "Obj-Array3");
jsonObjArray.put("ObjectArray", objArray);
json.put("InnerObjectArray", jsonObjArray);
Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
sortedTree.put("Sorted1", 10);
sortedTree.put("Sorted2", 103);
sortedTree.put("Sorted3", 14);
json.put("TreeMap", sortedTree);
try {
System.out.println("Writting JSON into file ...");
System.out.println(json);
FileWriter jsonFileWriter = new FileWriter(file);
jsonFileWriter.write(json.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
Others have answered your question, but I'll go into a little bit more detail:
Python's is
compares identity - it asks the question "is this one thing actually the same object as this other thing" (similar to ==
in Java). So, there are some times when using is
makes sense - the most common one being checking for None
. Eg, foo is None
. But, in general, it isn't what you want.
==
, on the other hand, asks the question "is this one thing logically equivalent to this other thing". For example:
>>> [1, 2, 3] == [1, 2, 3]
True
>>> [1, 2, 3] is [1, 2, 3]
False
And this is true because classes can define the method they use to test for equality:
>>> class AlwaysEqual(object):
... def __eq__(self, other):
... return True
...
>>> always_equal = AlwaysEqual()
>>> always_equal == 42
True
>>> always_equal == None
True
But they cannot define the method used for testing identity (ie, they can't override is
).
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
Worked for me by running the command prompt as an administrator
>>> ','.join('{},{}'.format(i, i + 1) for i in range(1, 100, 4))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'
That was a quick and quite dirty solution.
Now, for a solution that is suitable for different kinds of progression problems:
def deltas():
while True:
yield 1
yield 3
def numbers(start, deltas, max):
i = start
while i <= max:
yield i
i += next(deltas)
print(','.join(str(i) for i in numbers(1, deltas(), 100)))
And here are similar ideas implemented using itertools:
from itertools import cycle, takewhile, accumulate, chain
def numbers(start, deltas, max):
deltas = cycle(deltas)
numbers = accumulate(chain([start], deltas))
return takewhile(lambda x: x <= max, numbers)
print(','.join(str(x) for x in numbers(1, [1, 3], 100)))
Sorry for replying on an older question, but I would like to clarify the last question.
You use a "get" method for your form. When the name of your input-field is "g", it will make a URL like this:
https://www.google.com/search?g=[value from input-field]
But when you search with google, you notice the following URL:
https://www.google.nl/search?q=google+search+bar
Google uses the "q" Querystring variable as it's search-query. Therefor, renaming your field from "g" to "q" solved the problem.
Integration Services project templates are now available in the latest release of SSDT for Visual Studio 2017.
Note: if you have recently installed SSDT for Visual Studio 2017. You need to remove the Reporting Services and Analysis Services installations before you proceed with installing SSDT.
I tried to limit Get-ChildItem recursion depth using Resolve-Path
$PATH = "."
$folder = get-item $PATH
$FolderFullName = $Folder.FullName
$PATHs = Resolve-Path $FolderFullName\*\*\*\
$Folders = $PATHs | get-item | where {$_.PsIsContainer}
But this works fine :
gci "$PATH\*\*\*\*"
You can also use within your HTML code:
ng-init="card.description = 12345"
It is not recommended by Angular, and as mentioned above you should use exclusively your controller.
But it works :)
Try:
$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");
And in the partial
, you should have:
<td>row1</td>
<td>row2</td>
Yes, you can concatenate using a +
sign. Kotlin has string templates, so it's better to use them like:
var fn = "Hello"
var ln = "World"
"$fn $ln"
for concatenation.
You can even use String.plus()
method.
One solution, is to add support to the csharp language so that "" isn't the only scheme used for strings.
For another string terminator to the C# language - I'm a fan of backtick in ES6.
string test = `He said to me, "Hello World". How are you?`;
But also, the doubling idea in Markdown might be better:
string test = ""He said to me, "Hello World". How are you?"";
The code does not work at the date of this post. This post is a solution where the visitors to this Q&A jump onto this csharplank ticket for C# and upvote it - https://github.com/dotnet/csharplang/discussions/3917
<?php
class Test {
function MethodA(){
echo __FUNCTION__ ;
}
}
$test = new Test;
echo $test->MethodA();
?>
Result: "MethodA";
you should change import Header from './src/components/header/header' to
import Header from '../src/components/header/header'
If all you're looking to do is change the text you could do exactly as Kevin has said. But if you're trying to run an animation as well as change the text you could accomplish this by first changing the text then running your animation.
For Example:
$("#test").html('The text has now changed!');
$("#test").animate({left: '100px', top: '100px'},500);
Check out this fiddle for full example:
I've just written a library called jsPDF which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license.
I came across this question before I started writing it and thought I'd come back and let you know :)
Example create a "Hello World" PDF file.
// Default export is a4 paper, portrait, using milimeters for units_x000D_
var doc = new jsPDF()_x000D_
_x000D_
doc.text('Hello world!', 10, 10)_x000D_
doc.save('a4.pdf')
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
_x000D_
element.funky = function() {
console.log("Click!");
};
element.funky.type = "click";
element.funky.capt = false;
element.addEventListener(element.funky.type, element.funky, element.funky.capt);
// blah blah blah
element.removeEventListener(element.funky.type, element.funky, element.funky.capt);
Since receiving feedback from Andy (quite right, but as with many examples, I wished to show a contextual expansion of the idea), here's a less complicated exposition:
<script id="konami" type="text/javascript" async>
var konami = {
ptrn: "38,38,40,40,37,39,37,39,66,65",
kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
};
document.body.addEventListener( "keyup", function knm ( evt ) {
konami.kl = konami.kl.slice( -9 );
konami.kl.push( evt.keyCode );
if ( konami.ptrn === konami.kl.join() ) {
evt.target.removeEventListener( "keyup", knm, false );
/* Although at this point we wish to remove a listener
we could easily have had multiple "keyup" listeners
each triggering different functions, so we MUST
say which function we no longer wish to trigger
rather than which listener we wish to remove.
Normal scoping will apply to where we can mention this function
and thus, where we can remove the listener set to trigger it. */
document.body.classList.add( "konami" );
}
}, false );
document.body.removeChild( document.getElementById( "konami" ) );
</script>
This allows an effectively anonymous function structure, avoids the use of the practically deprecated callee, and allows easy removal.
Incidentally: The removal of the script element immediately after setting the listener is a cute trick for hiding code one would prefer wasn't starkly obvious to prying eyes (would spoil the surprise ;-)
So the method (more simply) is:
element.addEventListener( action, function name () {
doSomething();
element.removeEventListener( action, name, capture );
}, capture );
Lodash has a few Math utility methods that can round, floor, and ceil a number to a given decimal precision. This leaves off trailing zeroes.
They take an interesting approach, using the exponent of a number. Apparently this avoids rounding issues.
(Note: func
is Math.round
or ceil
or floor
in the code below)
// Shift with exponential notation to avoid floating-point issues.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}
You can use this if you are using nullable DateFields.
in Notepad++v6.1.8 (Unicode) it works after removing the QuickText plugin.
finalName is created as:
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
One of the solutions is to add own property:
<properties>
<finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
<finalName>${finalName}</finalName>
</build>
And now try:
mvn -DfinalName=build clean package
Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.
It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.
For a good explanation of how, when and where see MSDN