Follow these steps :
Thats All.
Well, you need to install it. You're looking for:
I find letter identifiers to be more readable and more indicative of parsed type:
1 - 7f / 10
1 - 7 / 10f
or:
1 - 7d / 10
1 - 7 / 10d
I suggest you to use provider
.
Provide is good when you want to configure it first before to use (against Service/Factory)
Something like:
.provider('Magazines', function() {
this.url = '/';
this.urlArray = '/';
this.organId = 'Default';
this.$get = function() {
var url = this.url;
var urlArray = this.urlArray;
var organId = this.organId;
return {
invoke: function() {
return ......
}
}
};
this.setUrl = function(url) {
this.url = url;
};
this.setUrlArray = function(urlArray) {
this.urlArray = urlArray;
};
this.setOrganId = function(organId) {
this.organId = organId;
};
});
.config(function(MagazinesProvider){
MagazinesProvider.setUrl('...');
MagazinesProvider.setUrlArray('...');
MagazinesProvider.setOrganId('...');
});
And now controller:
function MyCtrl($scope, Magazines) {
Magazines.invoke();
....
}
If you are using NumPy arrays, shape can be used. For example
>>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
>>> a
array([[[ 1, 2, 3],
[ 1, 2, 3]],
[[12, 3, 4],
[ 2, 1, 3]]])
>>> a.shape
(2, 2, 3)
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
Maybe you can use this properties:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
and
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
You seem to assign Double object into native double value field. Does that really compile?
Double.valueOf() creates a Double object so .doubleValue() should not be necessary.
If you want native double field, you need to define the field as double and then use .doubleValue()
Just to stick with the proposed question as indicated by the title, you can actually iterate over each match in a string using String.prototype.replace()
. For example the following does just that to get an array of all words based on a regular expression:
function getWords(str) {
var arr = [];
str.replace(/\w+/g, function(m) {
arr.push(m);
});
return arr;
}
var words = getWords("Where in the world is Carmen Sandiego?");
// > ["Where", "in", "the", "world", "is", "Carmen", "Sandiego"]
If I wanted to get capture groups or even the index of each match I could do that too. The following shows how each match is returned with the entire match, the 1st capture group and the index:
function getWords(str) {
var arr = [];
str.replace(/\w+(?=(.*))/g, function(m, remaining, index) {
arr.push({ match: m, remainder: remaining, index: index });
});
return arr;
}
var words = getWords("Where in the world is Carmen Sandiego?");
After running the above, words
will be as follows:
[
{
"match": "Where",
"remainder": " in the world is Carmen Sandiego?",
"index": 0
},
{
"match": "in",
"remainder": " the world is Carmen Sandiego?",
"index": 6
},
{
"match": "the",
"remainder": " world is Carmen Sandiego?",
"index": 9
},
{
"match": "world",
"remainder": " is Carmen Sandiego?",
"index": 13
},
{
"match": "is",
"remainder": " Carmen Sandiego?",
"index": 19
},
{
"match": "Carmen",
"remainder": " Sandiego?",
"index": 22
},
{
"match": "Sandiego",
"remainder": "?",
"index": 29
}
]
In order to match multiple occurrences similar to what is available in PHP with preg_match_all
you can use this type of thinking to make your own or use something like YourJS.matchAll()
. YourJS more or less defines this function as follows:
function matchAll(str, rgx) {
var arr, extras, matches = [];
str.replace(rgx.global ? rgx : new RegExp(rgx.source, (rgx + '').replace(/[\s\S]+\//g , 'g')), function() {
matches.push(arr = [].slice.call(arguments));
extras = arr.splice(-2);
arr.index = extras[0];
arr.input = extras[1];
});
return matches[0] ? matches : null;
}
FOR MANY NESTED FRAGMENTS (for example, when using a ViewPager in a fragment)
In your main activity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
In your fragment:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
In your nested fragment
Call activity
getParentFragment().startActivityForResult(intent, uniqueInstanceInt);
uniqueInstanceInt - replace it with an int that is unique among the nested fragments to prevent another fragment treat the answer.
Receive response
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == uniqueInstanceInt ) {
// TODO your code
}
}
Attention
A number between 0 and 65536 need be used in uniqueInstanceInt for error avoid "Can only use lower 16 bits for requestCode".
As stated in one of the comments, this works for Mac (probably for Windows/Linux too):
I WANT TO CONNECT FROM A CONTAINER TO A SERVICE ON THE HOST
The host has a changing IP address (or none if you have no network access). We recommend that you connect to the special DNS name
host.docker.internal
which resolves to the internal IP address used by the host. This is for development purpose and will not work in a production environment outside of Docker Desktop for Mac.You can also reach the gateway using
gateway.docker.internal
.
Quoted from https://docs.docker.com/docker-for-mac/networking/
This worked for me without using --net=host
.
The documentation is your friend, NSString
supports a call substringWithRange
that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString
it is immutable. If you have an NSMutableString
is has a method called deleteCharactersInRange
that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...
This is not restricted to dictionaries, but every mapping type that implements .items(). Further ist faster as it avoides an if condition. Nevertheless credits go to Imran:
def flatten(d, parent_key=''):
items = []
for k, v in d.items():
try:
items.extend(flatten(v, '%s%s_' % (parent_key, k)).items())
except AttributeError:
items.append(('%s%s' % (parent_key, k), v))
return dict(items)
Another way is to create functions in global scope. This was necessary for me since it wasn't possible in Angular 1.5 to reach a component's scope.
Example:
angular.module("app", []).component("component", {_x000D_
controller: ["$window", function($window) {_x000D_
var self = this;_x000D_
_x000D_
self.logg = function() {_x000D_
console.log("logging!");_x000D_
};_x000D_
_x000D_
$window.angularControllerLogg = self.logg;_x000D_
}_x000D_
});_x000D_
_x000D_
window.angularControllerLogg();
_x000D_
For me I had all of the namespaces on the pages and none of the solutions above fixed it. My problem was in:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeBehind="xxx.aspx.cs"
Inherits="xxx.xxx.xxx"
MasterPageFile="~masterurl/default.master" %>
Then in my aspx.cs
file the namespace did not match the Inherits
tag. So it needed
namespace xxx.xxx.xxx
In the .cs
to match the Inherits
.
A previous answer using LPAD()
is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.
UPDATE
mytable
SET
mycolumn = CONCAT(
REPEAT(
"0",
8 - LENGTH(mycolumn)
),
mycolumn
)
WHERE
LENGTH(mycolumn) < 8;
Don't create your own list - pytz
has a built-in set:
import pytz
set(pytz.all_timezones_set)
>>> {'Europe/Vienna', 'America/New_York', 'America/Argentina/Salta',..}
You can then apply a timezone:
import datetime
tz = pytz.timezone('Pacific/Johnston')
ct = datetime.datetime.now(tz=tz)
>>> ct.isoformat()
2017-01-13T11:29:22.601991-05:00
Or if you already have a datetime
object that is TZ aware (not naive):
# This timestamp is in UTC
my_ct = datetime.datetime.now(tz=pytz.UTC)
# Now convert it to another timezone
new_ct = my_ct.astimezone(tz)
>>> new_ct.isoformat()
2017-01-13T11:29:22.601991-05:00
check out this.
<activity android:name=".Calculator"
android:windowSoftInputMode="stateHidden|adjustResize"
android:theme="@android:style/Theme.Black.NoTitleBar">
</activity>
It is because you forgot to pass in event
into the click
function:
$('.menuOption').on('click', function (e) { // <-- the "e" for event
e.preventDefault(); // now it'll work
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
On a side note, e
is more commonly used as opposed to the word event
since Event
is a global variable in most browsers.
In Chrome version 49
you need always this code
$("select option:first").prop('selected', true)
SELECT t1.cname, t1.wmname, t2.max
FROM makerar t1 JOIN (
SELECT cname, MAX(avg) max
FROM makerar
GROUP BY cname ) t2
ON t1.cname = t2.cname AND t1.avg = t2.max;
Using rank()
window function:
SELECT cname, wmname, avg
FROM (
SELECT cname, wmname, avg, rank()
OVER (PARTITION BY cname ORDER BY avg DESC)
FROM makerar) t
WHERE rank = 1;
Note
Either one will preserve multiple max values per group. If you want only single record per group even if there is more than one record with avg equal to max you should check @ypercube's answer.
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \
escapes, etc.
Example:
$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")
The Bash manual has this to say:
Enclosing characters in single quotes (
'
) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.Enclosing characters in double quotes (
"
) preserves the literal value of all characters within the quotes, with the exception of$
,`
,\
, and, when history expansion is enabled,!
. The characters$
and`
retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters:$
,`
,"
,\
, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an!
appearing in double quotes is escaped using a backslash. The backslash preceding the!
is not removed.The special parameters
*
and@
have special meaning when in double quotes (see Shell Parameter Expansion).
Use the function removeAtIndex(i: String.Index) -> Character
:
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
I required a specific colour, so filter didn't work for me.
Instead, I created a div, exploiting CSS multiple background images and the linear-gradient function (which creates an image itself). If you use the overlay blend mode, your actual image will be blended with the generated "gradient" image containing your desired colour (here, #BADA55)
.colored-image {_x000D_
background-image: linear-gradient(to right, #BADA55, #BADA55), url("https://i.imgur.com/lYXT8R6.png");_x000D_
background-blend-mode: overlay;_x000D_
background-size: contain;_x000D_
width: 200px;_x000D_
height: 200px; _x000D_
}
_x000D_
<div class="colored-image"></div>
_x000D_
Just apply the style attribute to the tr tag. In the case of multiple tr tags, you will have to apply the style to each element, or wrap them in a tbody tag:
<table>
<tr><th>Test Table</th><tr>
<tbody style="display:none">
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
<tr><td>123456789</td><tr>
</tbody>
</table>
This has to do with the browser's box model. Use something like jQuery or another JavaScript abstraction library to normalize the DOM model.
I fixed that error by adding this conflict code
<script type="text/javascript">
jQuery.noConflict();
</script>
after my jQuery and js files and get the file was the error (found by the console of browser) and replace all the '$' by jQuery following this on all error js files in my Magento website. It's working for me good. Find more details on my blog here
Fully example to demonstrate how jQuery query all data in HTML table.
Assume there is a table like the following in your HTML code.
<table id="someTable">
<thead>
<tr>
<td>title 0</td>
<td>title 1</td>
<td>title 2</td>
</tr>
</thead>
<tbody>
<tr>
<td>row 0 td 0</td>
<td>row 0 td 1</td>
<td>row 0 td 2</td>
</tr>
<tr>
<td>row 1 td 0</td>
<td>row 1 td 1</td>
<td>row 1 td 2</td>
</tr>
<tr>
<td>row 2 td 0</td>
<td>row 2 td 1</td>
<td>row 2 td 2</td>
</tr>
<tr> ... </tr>
<tr> ... </tr>
...
<tr> ... </tr>
<tr>
<td>row n td 0</td>
<td>row n td 1</td>
<td>row n td 2</td>
</tr>
</tbody>
</table>
Then, The Answer, the code to print all row all column, should like this
$('#someTable tbody tr').each( (tr_idx,tr) => {
$(tr).children('td').each( (td_idx, td) => {
console.log( '[' +tr_idx+ ',' +td_idx+ '] => ' + $(td).text());
});
});
After running the code, the result will show
[0,0] => row 0 td 0
[0,1] => row 0 td 1
[0,2] => row 0 td 2
[1,0] => row 1 td 0
[1,1] => row 1 td 1
[1,2] => row 1 td 2
[2,0] => row 2 td 0
[2,1] => row 2 td 1
[2,2] => row 2 td 2
...
[n,0] => row n td 0
[n,1] => row n td 1
[n,2] => row n td 2
Summary.
In the code,
tr_idx is the row index start from 0.
td_idx is the column index start from 0.
From this double-loop code,
you can get all loop-index and data in each td cell after comparing the Answer's source code and the output result.
The Problem is with your code formatting,
inorder to use strtotime()
You should replace '06/Oct/2011:19:00:02'
with 06/10/2011 19:00:02
and date('d/M/Y:H:i:s', $date);
with date('d/M/Y H:i:s', $date);
. Note the spaces in between.
So the final code looks like this
$s = '06/10/2011 19:00:02';
$date = strtotime($s);
echo date('d/M/Y H:i:s', $date);
This solution should work for IE9 and up.
It's like jQuery's parents() method when you need to get a parent container which might be up a few levels from the given element, like finding the containing <form>
of a clicked <button>
. Looks through the parents until the matching selector is found, or until it reaches the <body>
. Returns either the matching element or the <body>
.
function parents(el, selector){
var parent_container = el;
do {
parent_container = parent_container.parentNode;
}
while( !parent_container.matches(selector) && parent_container !== document.body );
return parent_container;
}
I know this is an old question, but HTML5 offers a couple new options.
The first is to separate the form from the toolbar in the markup, add another form for the delete action, and associate the buttons in the toolbar with their respective forms using the form
attribute.
<form id="saveForm" action="/post/dispatch/save" method="post">
<input type="text" name="foo" /> <!-- several of those here -->
</form>
<form id="deleteForm" action="/post/dispatch/delete" method="post">
<input type="hidden" value="some_id" />
</form>
<div id="toolbar">
<input type="submit" name="save" value="Save" form="saveForm" />
<input type="submit" name="delete" value="Delete" form="deleteForm" />
<a href="/home/index">Cancel</a>
</div>
This option is quite flexible, but the original post also mentioned that it may be necessary to perform different actions with a single form. HTML5 comes to the rescue, again. You can use the formaction
attribute on submit buttons, so different buttons in the same form can submit to different URLs. This example just adds a clone method to the toolbar outside the form, but it would work the same nested in the form.
<div id="toolbar">
<input type="submit" name="clone" value="Clone" form="saveForm"
formaction="/post/dispatch/clone" />
</div>
http://www.whatwg.org/specs/web-apps/current-work/#attributes-for-form-submission
The advantage of these new features is that they do all this declaratively without JavaScript. The disadvantage is that they are not supported on older browsers, so you'd have to do some polyfilling for older browsers.
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Regards
I would definitly go with a clean way like this :
<?php
class Person {
private $name;
private $age;
private $sexe;
function __construct ($payload)
{
if (is_array($payload))
$this->from_array($payload);
}
public function from_array($array)
{
foreach(get_object_vars($this) as $attrName => $attrValue)
$this->{$attrName} = $array[$attrName];
}
public function say_hi ()
{
print "hi my name is {$this->name}";
}
}
print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();
?>
if you submit:
you will get this:
I found this more logical comparing the above answers from Objects should be used for the purpose they've been made for (encapsulated cute little objects).
Also using get_object_vars ensure that no extra attributes are created in the manipulated Object (you don't want a car having a family name, nor a person behaving 4 wheels).
When you call loadTeachers()
on DOMReady the context of this
will not be the #CourseSelect
element.
You can fix this by triggering a change()
event on the #CourseSelect
element on load of the DOM:
$("#CourseSelect").change(loadTeachers).change(); // or .trigger('change');
Alternatively can use $.proxy
to change the context the function runs under:
$("#CourseSelect").change(loadTeachers);
$.proxy(loadTeachers, $('#CourseSelect'))();
Or the vanilla JS equivalent of the above, bind()
:
$("#CourseSelect").change(loadTeachers);
loadTeachers.bind($('#CourseSelect'));
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof
is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof
.
Third, C doesn't have references so your usage of &
in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t
type) as a separate argument, and use sizeof
at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc()
, and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
You can use angular's function called angular.isUndefined(value)
returns boolean.
You may read more about angular's functions here: AngularJS Functions (isUndefined)
To put it in very practical terms:
If you use a const in dll A and dll B references that const, the value of that const will be compiled into dll B. If you redeploy dll A with a new value for that const, dll B will still be using the original value.
If you use a readonly in dll A and dll B references that readonly, that readonly will always be looked up at runtime. This means if you redeploy dll A with a new value for that readonly, dll B will use that new value.
This worked for me using sed [Edit: comment below points out sed doesn't support \s]
[^ ]
while
[^\s]
didn't
# Delete everything except space and 'g'
echo "ghai ghai" | sed "s/[^\sg]//g"
gg
echo "ghai ghai" | sed "s/[^ g]//g"
g g
I had used some of the above solutions but it was working for width
but height
.
compileSdkVersion
greater than 23, you can directly use RecyclerView provided in their respective support libraries of recycler view, like for 23 it will be 'com.android.support:recyclerview-v7:23.2.1'
. These support libraries support attributes of wrap_content
for both width and height.You have to add it to your dependencies
compile 'com.android.support:recyclerview-v7:23.2.1'
compileSdkVersion
less than 23, you can use below-mentioned solution.I found this Google thread regarding this issue. In this thread, there is one contribution which leads to the implementation of LinearLayoutManager.
I have tested it for both height and width and it worked fine for me in both cases.
/*
* Copyright 2015 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Contact details
*
* Email: [email protected]
* Site: http://se.solovyev.org
*/
package org.solovyev.android.views.llm;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import java.lang.reflect.Field;
/**
* {@link android.support.v7.widget.LinearLayoutManager} which wraps its content. Note that this class will always
* wrap the content regardless of {@link android.support.v7.widget.RecyclerView} layout parameters.
* <p/>
* Now it's impossible to run add/remove animations with child views which have arbitrary dimensions (height for
* VERTICAL orientation and width for HORIZONTAL). However if child views have fixed dimensions
* {@link #setChildSize(int)} method might be used to let the layout manager know how big they are going to be.
* If animations are not used at all then a normal measuring procedure will run and child views will be measured during
* the measure pass.
*/
public class LinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {
private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;
private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;
private final int[] childDimensions = new int[2];
private final RecyclerView view;
private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(Context context) {
super(context);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.view = null;
}
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(RecyclerView view) {
super(view.getContext());
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
@SuppressWarnings("UnusedDeclaration")
public LinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
super(view.getContext(), orientation, reverseLayout);
this.view = view;
this.overScrollMode = ViewCompat.getOverScrollMode(view);
}
public void setOverScrollMode(int overScrollMode) {
if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
if (this.view == null) throw new IllegalStateException("view == null");
this.overScrollMode = overScrollMode;
ViewCompat.setOverScrollMode(view, overScrollMode);
}
public static int makeUnspecifiedSpec() {
return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;
final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;
final int unspecified = makeUnspecifiedSpec();
if (exactWidth && exactHeight) {
// in case of exact calculations for both dimensions let's use default "onMeasure" implementation
super.onMeasure(recycler, state, widthSpec, heightSpec);
return;
}
final boolean vertical = getOrientation() == VERTICAL;
initChildDimensions(widthSize, heightSize, vertical);
int width = 0;
int height = 0;
// it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
// happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
// recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
// called whiles scrolling)
recycler.clear();
final int stateItemCount = state.getItemCount();
final int adapterItemCount = getItemCount();
// adapter always contains actual data while state might contain old data (f.e. data before the animation is
// done). As we want to measure the view with actual data we must use data from the adapter and not from the
// state
for (int i = 0; i < adapterItemCount; i++) {
if (vertical) {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, widthSize, unspecified, childDimensions);
} else {
logMeasureWarning(i);
}
}
height += childDimensions[CHILD_HEIGHT];
if (i == 0) {
width = childDimensions[CHILD_WIDTH];
}
if (hasHeightSize && height >= heightSize) {
break;
}
} else {
if (!hasChildSize) {
if (i < stateItemCount) {
// we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
// we will use previously calculated dimensions
measureChild(recycler, i, unspecified, heightSize, childDimensions);
} else {
logMeasureWarning(i);
}
}
width += childDimensions[CHILD_WIDTH];
if (i == 0) {
height = childDimensions[CHILD_HEIGHT];
}
if (hasWidthSize && width >= widthSize) {
break;
}
}
}
if (exactWidth) {
width = widthSize;
} else {
width += getPaddingLeft() + getPaddingRight();
if (hasWidthSize) {
width = Math.min(width, widthSize);
}
}
if (exactHeight) {
height = heightSize;
} else {
height += getPaddingTop() + getPaddingBottom();
if (hasHeightSize) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
|| (!vertical && (!hasWidthSize || width < widthSize));
ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
}
}
private void logMeasureWarning(int child) {
if (BuildConfig.DEBUG) {
Log.w("LinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
"To remove this message either use #setChildSize() method or don't run RecyclerView animations");
}
}
private void initChildDimensions(int width, int height, boolean vertical) {
if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
// already initialized, skipping
return;
}
if (vertical) {
childDimensions[CHILD_WIDTH] = width;
childDimensions[CHILD_HEIGHT] = childSize;
} else {
childDimensions[CHILD_WIDTH] = childSize;
childDimensions[CHILD_HEIGHT] = height;
}
}
@Override
public void setOrientation(int orientation) {
// might be called before the constructor of this class is called
//noinspection ConstantConditions
if (childDimensions != null) {
if (getOrientation() != orientation) {
childDimensions[CHILD_WIDTH] = 0;
childDimensions[CHILD_HEIGHT] = 0;
}
}
super.setOrientation(orientation);
}
public void clearChildSize() {
hasChildSize = false;
setChildSize(DEFAULT_CHILD_SIZE);
}
public void setChildSize(int childSize) {
hasChildSize = true;
if (this.childSize != childSize) {
this.childSize = childSize;
requestLayout();
}
}
private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
final View child;
try {
child = recycler.getViewForPosition(position);
} catch (IndexOutOfBoundsException e) {
if (BuildConfig.DEBUG) {
Log.w("LinearLayoutManager", "LinearLayoutManager doesn't work well with animations. Consider switching them off", e);
}
return;
}
final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();
final int hPadding = getPaddingLeft() + getPaddingRight();
final int vPadding = getPaddingTop() + getPaddingBottom();
final int hMargin = p.leftMargin + p.rightMargin;
final int vMargin = p.topMargin + p.bottomMargin;
// we must make insets dirty in order calculateItemDecorationsForChild to work
makeInsetsDirty(p);
// this method should be called before any getXxxDecorationXxx() methods
calculateItemDecorationsForChild(child, tmpRect);
final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);
final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());
child.measure(childWidthSpec, childHeightSpec);
dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;
// as view is recycled let's not keep old measured values
makeInsetsDirty(p);
recycler.recycleView(child);
}
private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
if (!canMakeInsetsDirty) {
return;
}
try {
if (insetsDirtyField == null) {
insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
insetsDirtyField.setAccessible(true);
}
insetsDirtyField.set(p, true);
} catch (NoSuchFieldException e) {
onMakeInsertDirtyFailed();
} catch (IllegalAccessException e) {
onMakeInsertDirtyFailed();
}
}
private static void onMakeInsertDirtyFailed() {
canMakeInsetsDirty = false;
if (BuildConfig.DEBUG) {
Log.w("LinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
}
}
}
There is no pure CSS solution to this classical problem.
If you want to achieve this, you have two solutions:
EDIT: when I say that there is no solution, I take as an hypothesis that you don't know in advance the size of the block to center. If you know it, paislee's solution is very good
I just had a very similar issues with gradle builds / adding .jar library. I got it working by a combination of :
compile fileTree(dir: 'libs', include: '*.jar')}
BUT more importantly and annoyingly, only hours after I get it working, Android Studio have just released 0.3.7, which claims to have solved a lot of gradle issues such as adding .jar libraries
http://tools.android.com/recent
Hope this helps people!
// x has not been defined before
if (typeof x === 'undefined') { // Evaluates to true without errors.
// These statements execute.
}
if (x === undefined) { // Throws a ReferenceError
}
The typical solution is to dump the database as necessary and backup those files.
Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial.
Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment).
First you add the Navigation back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then, add the Method in your HostActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
{
super.onBackPressed();
Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
Try this, definitely work.
From the macOS Terminal, use open
with the -a
flag and give the name of the app you want to open. In this case "Google Chrome". You may pass it a file or URL you want it to open with.
open -a "Google Chrome" index.html
You can try the following code snippet
httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");
Hope it will work for you.
The best option (for my of course) is do it yourserfl. It means you can modify programattly all parts of the SOAP message
Binding binding = prov.getBinding();
List<Handler> handlerChain = binding.getHandlerChain();
handlerChain.add( new ModifyMessageHandler() );
binding.setHandlerChain( handlerChain );
And the ModifyMessageHandler source could be
@Override
public boolean handleMessage( SOAPMessageContext context )
{
SOAPMessage msg = context.getMessage();
try
{
SOAPEnvelope envelope = msg.getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();
SOAPElement ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
ele = header.addChildElement( new QName( "http://uri", "name_of_header" ) );
ele.addTextNode( "value_of_header" );
...
I hope this helps you
Usually, the correct way of updating certain fields in one or more model instances is to use the update()
method on the respective queryset. Then you do something like this:
affected_surveys = Survey.objects.filter(
# restrict your queryset by whatever fits you
# ...
).update(active=True)
This way, you don't need to call save()
on your model anymore because it gets saved automatically. Also, the update()
method returns the number of survey instances that were affected by your update.
Check this solution which will able to find same character string too, let me know if something missing or not right.
function indexes(source, find) {_x000D_
if (!source) {_x000D_
return [];_x000D_
}_x000D_
if (!find) {_x000D_
return source.split('').map(function(_, i) { return i; });_x000D_
}_x000D_
source = source.toLowerCase();_x000D_
find = find.toLowerCase();_x000D_
var result = [];_x000D_
var i = 0;_x000D_
while(i < source.length) {_x000D_
if (source.substring(i, i + find.length) == find)_x000D_
result.push(i++);_x000D_
else_x000D_
i++_x000D_
}_x000D_
return result;_x000D_
}_x000D_
console.log(indexes('aaaaaaaa', 'aaaaaa'))_x000D_
console.log(indexes('aeeaaaaadjfhfnaaaaadjddjaa', 'aaaa'))_x000D_
console.log(indexes('wordgoodwordgoodgoodbestword', 'wordgood'))_x000D_
console.log(indexes('I learned to play the Ukulele in Lebanon.', 'le'))
_x000D_
The way I've done this in the past is first get the first day of this month
dFirstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
Then subtract a day to get end of last month
dLastDayOfLastMonth = dFirstDayOfThisMonth.AddDays (-1);
Then subtract a month to get first day of previous month
dFirstDayOfLastMonth = dFirstDayOfThisMonth.AddMonths(-1);
System is the java class.
out is the instance and also static member of PrintStream.
println is the method of PrintStream.
There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:
HorizontalContentAlignment="Stretch"
... to force the contents of a control to stretch horizontally. Or you can say:
HorizontalAlignment="Stretch"
... to force the control itself to stretch horizontally to fill its parent.
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}
If u need to connect your application to a server you can do it through PHP/MySQL and JSON http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ .Mysql Connection code should be in AsynTask class. Dont run it in Main Thread.
This site gives some options on vertically centering your div: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
I was having the same issue implementing in Angular 9. These are the two steps I did:
Change your YouTube URL from https://youtube.com/your_code
to https://youtube.com/embed/your_code
.
And then pass the URL through DomSanitizer
of Angular.
import { Component, OnInit } from "@angular/core";
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: "app-help",
templateUrl: "./help.component.html",
styleUrls: ["./help.component.scss"],
})
export class HelpComponent implements OnInit {
youtubeVideoLink: any = 'https://youtube.com/embed/your_code'
constructor(public sanitizer: DomSanitizer) {
this.sanitizer = sanitizer;
}
ngOnInit(): void {}
getLink(){
return this.sanitizer.bypassSecurityTrustResourceUrl(this.youtubeVideoLink);
}
}
<iframe width="420" height="315" [src]="getLink()" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
If I am to define the same proptypes for a particular shape multiple times, I like abstract it out to a proptypes file so that if the shape of the object changes, I only have to change the code in one place. It helps dry up the codebase a bit.
Example:
// Inside my proptypes.js file
import PT from 'prop-types';
export const product = {
id: PT.number.isRequired,
title: PT.string.isRequired,
sku: PT.string.isRequired,
description: PT.string.isRequired,
};
// Inside my component file
import PT from 'prop-types';
import { product } from './proptypes;
List.propTypes = {
productList: PT.arrayOf(product)
}
The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.
Like this:
ggplot() +
geom_line(data=Data1, aes(x=A, y=B), color='green') +
geom_line(data=Data2, aes(x=C, y=D), color='red')
instead of
ggplot(data=Data1, aes(x=A, y=B), color='green') +
geom_line() +
geom_line(data=Data2, aes(x=C, y=D), color='red')
For Sublime Text 3, all I had to do was add "highlight_line": true
to my user settings file: Preferences -> Settings - User. It was only once that preference was set that all the color scheme lineHighlight
settings took effect.
Hopefully this will save someone else some of this same flailing about.
If your branch is behind by master then do:
git checkout master (you are switching your branch to master)
git pull
git checkout yourBranch (switch back to your branch)
git merge master
After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:
git push
If there is a conflict then fix your file(s), then:
git add yourFile(s)
git commit -m 'updating my branch'
git push
For everyone using editors like Komodo Edit (win10) add sys.stdout.flush()
to:
def mp_worker((inputs, the_time)):
print " Process %s\tWaiting %s seconds" % (inputs, the_time)
time.sleep(int(the_time))
print " Process %s\tDONE" % inputs
sys.stdout.flush()
or as first line to:
if __name__ == '__main__':
sys.stdout.flush()
This helps to see what goes on during the run of the script; in stead of having to look at the black command line box.
Since I think you are new with Python, lets do the long way, iterate thru your list using for loop and multiply and append each element to a new list.
using for loop
lst = [5, 20 ,15]
product = []
for i in lst:
product.append(i*5)
print product
using list comprehension, this is also same as using for-loop but more 'pythonic'
lst = [5, 20 ,15]
prod = [i * 5 for i in lst]
print prod
For me, installing development version of libyaml did it.
yum install libyaml-devel #centos
apt-get install libyaml-dev # ubuntu
The problem is that the default option of "yearRange" is 10 years.
So 2012 - 10 = 2002
.
So change the yearRange to c-20:c
or just 1999 (yearRange: '1999:c'
), and use that in combination with restrict dates (mindate, maxdate).
For more info: http://jqueryui.com/demos/datepicker/#option-yearRange
See example: http://jsfiddle.net/kGjdL/
And your code with the addition:
$(function () {
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
showButtonPanel: true,
changeMonth: true,
changeYear: true,
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
minDate: new Date(1999, 10 - 1, 25),
maxDate: '+30Y',
yearRange: '1999:c',
inline: true
});
});
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
Solution for Kotlin (Android 3.3, Kotlin 1.3.20)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar!!.elevation = 0f
}
Instead of using subclassing/mixins, I like to use a generic class decorator
def comparable(cls):
""" Class decorator providing generic comparison functionality """
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not self.__eq__(other)
cls.__eq__ = __eq__
cls.__ne__ = __ne__
return cls
Usage:
@comparable
class Number(object):
def __init__(self, x):
self.x = x
a = Number(1)
b = Number(1)
assert a == b
The pattern with Optional
is for one to avoid returning null
. It's still perfectly possible to pass in null
to a method.
While these aren't really official yet, you can use JSR-308 style annotations to indicate whether or not you accept null
values into the function. Note that you'd have to have the right tooling to actually identify it, and it'd provide more of a static check than an enforceable runtime policy, but it would help.
public int calculateSomething(@NotNull final String p1, @NotNull final String p2) {}
If you want to do a whole group, not just one field at a time, you can use the HTML5 <fieldset>
tag.
<fieldset [disabled]="killfields ? 'disabled' : null">
<!-- fields go here -->
</fieldset>
I had a similar issue to this. My error needs to be an instanceof
both Error
and NotImplemented
, and it also needs to produce a coherent backtrace in the console.
My solution:
var NotImplemented = (function() {
var NotImplemented, err;
NotImplemented = (function() {
function NotImplemented(message) {
var err;
err = new Error(message);
err.name = "NotImplemented";
this.message = err.message;
if (err.stack) this.stack = err.stack;
}
return NotImplemented;
})();
err = new Error();
err.name = "NotImplemented";
NotImplemented.prototype = err;
return NotImplemented;
}).call(this);
// TEST:
console.log("instanceof Error: " + (new NotImplemented() instanceof Error));
console.log("instanceof NotImplemented: " + (new NotImplemented() instanceofNotImplemented));
console.log("message: "+(new NotImplemented('I was too busy').message));
throw new NotImplemented("just didn't feel like it");
Result of running with node.js:
instanceof Error: true
instanceof NotImplemented: true
message: I was too busy
/private/tmp/t.js:24
throw new NotImplemented("just didn't feel like it");
^
NotImplemented: just didn't feel like it
at Error.NotImplemented (/Users/colin/projects/gems/jax/t.js:6:13)
at Object.<anonymous> (/Users/colin/projects/gems/jax/t.js:24:7)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:487:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
The error passes all 3 of my criteria, and although the stack
property is nonstandard, it is supported in most newer browsers which is acceptable in my case.
You can use LINQ for this
var list = new List<int>();
var sum = list.Sum();
and for a List of strings like Roy Dictus said you have to convert
list.Sum(str => Convert.ToInt32(str));
You have to create a variable of the type of the class, and set it equal to a new instance of the object first.
GradeBook myGradeBook = new GradeBook();
Then call the method on the obect you just created.
myGradeBook.[method you want called]
Lots of good answers but strange that no one has mentioned using a lambda
function.
So if you have no arguments, things become pretty trivial:
def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
method2(method1)
But say you have one (or more) arguments in method1
:
def method1(param):
return 'hello ' + str(param)
def method2(methodToRun):
result = methodToRun()
return result
Then you can simply invoke method2
as method2(lambda: method1('world'))
.
method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader
I find this much cleaner than the other answers mentioned here.
For VB.Net
CType(GridControl1.MainView, GridView).GetFocusedRow()
For C#
((GridView)gridControl1.MainView).GetFocusedRow();
example bind data by linq so use
Dim selRow As CUSTOMER = CType(GridControl1.MainView, GridView).GetFocusedRow()
There is no error in the following piece of code:
float arr[4];
arr[0] = 6.28;
arr[1] = 2.50;
arr[2] = 9.73;
arr[3] = 4.364;
std::vector<float*> vec = std::vector<float*>();
vec.push_back(arr);
float* ptr = vec.front();
for (int i = 0; i < 3; i++)
printf("%g\n", ptr[i]);
OUTPUT IS:
6.28
2.5
9.73
4.364
IN CONCLUSION:
std::vector<double*>
is another possibility apart from
std::vector<std::array<double, 4>>
that James McNellis suggested.
Since it doesn't appear that anyone has mentioned it here yet, the new best way to manage HttpClient and HttpClientHandler in .NET Core 2.1 is using HttpClientFactory.
It solves most of the aforementioned issues and gotchas in a clean and easy-to-use way. From Steve Gordon's great blog post:
Add the following packages to your .Net Core (2.1.1 or later) project:
Microsoft.AspNetCore.All
Microsoft.Extensions.Http
Add this to Startup.cs:
services.AddHttpClient();
Inject and use:
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<ActionResult> Get()
{
var client = _httpClientFactory.CreateClient();
var result = await client.GetStringAsync("http://www.google.com");
return Ok(result);
}
}
Explore the series of posts in Steve's blog for lots more features.
update 2017.12.25
"react-router-dom": "^4.2.2"
url like
BrowserHistory
: http://localhost:3000/demo-7/detail/2?sort=name
HashHistory
: http://localhost:3000/demo-7/#/detail/2?sort=name
with query-string dependency:
this.id = props.match.params.id;
this.searchObj = queryString.parse(props.location.search);
this.from = props.location.state.from;
console.log(this.id, this.searchObj, this.from);
results:
2 {sort: "name"} home
"react-router": "^2.4.1"
Url like http://localhost:8080/react-router01/1?name=novaline&age=26
const queryParams = this.props.location.query;
queryParams is a object contains the query params: {name: novaline, age: 26}
require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()
To undo a github pull request with commits throughout that you do not want to delete, you have to run a:
git reset --hard --merge <commit hash>
with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.
A good way to find this is to go to the now closed pull request and finding this field:
After you run the git reset
, run a:
git push origin --force <branch name>
This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.
EDIT:
If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.
If you're going to call a python script from some other process (say, from the command line), use pythonw.exe
. Otherwise, your user will continuously see a cmd
window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an email; python.exe
will pop up a CLI window, send the email, then close the window. It'll appear as a quick flash, and can be considered somewhat annoying. pythonw.exe
avoids this, but still sends the email.
I think to correctly interpret your question under this form: "OK, I'm already done with all the Ajax stuff; I just wish to know if the JavaScript function my Ajax callback inserted into the DIV is callable at any time from that moment on, that is, I do not want to call it contextually to the callback return".
OK, if you mean something like this the answer is yes, you can invoke your new code by that moment at any time during the page persistence within the browser, under the following conditions:
1) Your JavaScript code returned by Ajax callback must be syntactically OK;
2) Even if your function declaration is inserted into a <script>
block within an existing <div>
element, the browser won't know the new function exists, as the declaration code has never been executed. So, you must eval()
your declaration code returned by the Ajax callback, in order to effectively declare your new function and have it available during the whole page lifetime.
Even if quite dummy, this code explains the idea:
<html>
<body>
<div id="div1">
</div>
<div id="div2">
<input type="button" value="Go!" onclick="go()" />
</div>
<script type="text/javascript">
var newsc = '<script id="sc1" type="text/javascript">function go() { alert("GO!") }<\/script>';
var e = document.getElementById('div1');
e.innerHTML = newsc;
eval(document.getElementById('sc1').innerHTML);
</script>
</body>
</html>
I didn't use Ajax, but the concept is the same (even if the example I chose sure isn't much smart :-)
Generally speaking, I do not question your solution design, i.e. whether it is more or less appropriate to externalize + generalize the function in a separate .js file and the like, but please take note that such a solution could raise further problems, especially if your Ajax invocations should repeat, i.e. if the context of the same function should change or in case the declared function persistence should be concerned, so maybe you should seriously consider to change your design to one of the suggested examples in this thread.
Finally, if I misunderstood your question, and you're talking about contextual invocation of the function when your Ajax callback returns, then my feeling is to suggest the Prototype approach described by krosenvold, as it is cross-browser, tested and fully functional, and this can give you a better roadmap for future implementations.
You are consuming a line at, which is discarded
while((str=input.readLine())!=null && str.length()!=0)
and reading a bigint at
BigInteger n = new BigInteger(input.readLine());
so try getting the bigint from string which is read as
BigInteger n = new BigInteger(str);
Constructor used: BigInteger(String val)
Aslo change while((str=input.readLine())!=null && str.length()!=0)
to
while((str=input.readLine())!=null)
see related post string to bigint
readLine()
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
see javadocs
Spanny make SpannableString easier to use.
Spanny spanny = new Spanny("Underline text", new UnderlineSpan())
.append("\nRed text", new ForegroundColorSpan(Color.RED))
.append("\nPlain text");
textView.setText(spanny)
There are commercial products such as ionCube (which I use), source guardian, and Zen Guard.
There are also postings on the net which claim they can reverse engineer the encoded programs. How reliable they are is questionable, since I have never used them.
Note that most of these solutions require an encoder to be installed on their servers. So you may want to make sure your client is comfortable with that.
The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:
public static object DeserializeFromStream(Stream stream)
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
return serializer.Deserialize(jsonTextReader);
}
}
Documentation: Deserialize JSON from a file stream
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
No npm install required as ES6 Promises is native.
Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6
import http = require('http');
import fs = require('fs');
function findFolderAsync(directory : string): Promise<string> {
let p = new Promise<string>(function (resolve, reject) {
fs.stat(directory, function (err, stats) {
//Check if error defined and the error code is "not exists"
if (err && err.code === "ENOENT") {
reject("Directory does not exist");
}
else {
resolve("Directory exists");
}
});
});
return p;
}
findFolderAsync("myFolder").then(
function (msg : string) {
console.log("Promise resolved as " + msg);
},
function (msg : string) {
console.log("Promise rejected as " + msg);
}
);
If you use jquery then you can also do like this,
$(document).on("keydown", '.class_name', function (event) {
if (event.keyCode == 37) {
console.log('left arrow pressed');
}
if (event.keyCode == 38) {
console.log('up arrow pressed');
}
if (event.keyCode == 39) {
console.log('right arrow pressed');
}
if (event.keyCode == 40) {
console.log('down arrow pressed');
}
});
<Switch
android:thumb="@drawable/thumb"
android:track="@drawable/track"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
If you know the text in the combo box that you want to select, just use the setCurrentText() method to select that item.
ui->comboBox->setCurrentText("choice 2");
From the Qt 5.7 documentation
The setter setCurrentText() simply calls setEditText() if the combo box is editable. Otherwise, if there is a matching text in the list, currentIndex is set to the corresponding index.
So as long as the combo box is not editable, the text specified in the function call will be selected in the combo box.
Reference: http://doc.qt.io/qt-5/qcombobox.html#currentText-prop
You can use SVG to draw the lines.
.diag {_x000D_
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M1 0 L0 1 L99 100 L100 99' fill='black' /><path d='M0 99 L99 0 L100 1 L1 100' fill='black' /></svg>");_x000D_
background-repeat:no-repeat;_x000D_
background-position:center center;_x000D_
background-size: 100% 100%, auto;_x000D_
}
_x000D_
<div class="diag" style="width: 300px; height: 100px;"></div>
_x000D_
Have a play here: http://jsfiddle.net/tyw7vkvm
Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want. using
val args = Bundle()
you can set your args.
You can now use args.putSomthing
to add you args which u give as a prameter in your newInstance function.
putString(key:String,str:String)
to add string for example and so on
Now to get the argument you can use
arguments.getSomthing(Key:String)
=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
To answer your updated question you can do
String[] lines = ("Name = Bob\n" +
"Age = 27\n" +
"Occupation = Student\n" +
"Status = Single").split("\n");
for (String line : lines) {
String[] parts = line.split(" = +");
System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]);
}
prints
Name = Bob
Age = 27
Occupation = Student
Status = Single
To still be able to scroll this worked for me
if (e.changedTouches.length > 1) e.preventDefault();
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
Try:
$post = $wp_query->post;
Then pass the function:
$post->ID
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
You can retrieve the information using the Jenkins Script Console which is accessible by visiting http://<jenkins-url>/script
. (Given that you are logged in and have the required permissions).
Enter the following Groovy script to iterate over the installed plugins and print out the relevant information:
Jenkins.instance.pluginManager.plugins.each{
plugin ->
println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}
It will print the results list like this (clipped):
This solutions is similar to one of the answers above in that it uses Groovy, but here we are using the script console instead. The script console is extremely helpful when using Jenkins.
Update
If you prefer a sorted list, you can call this sort
method:
def pluginList = new ArrayList(Jenkins.instance.pluginManager.plugins)
pluginList.sort { it.getShortName() }.each{
plugin ->
println ("${plugin.getDisplayName()} (${plugin.getShortName()}): ${plugin.getVersion()}")
}
Adjust the Closure to your liking (e.g. here it is sorted by the shortName, in the example it is sorted by DisplayName)
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim
:
input = input.trim();
For my Nexus 6P downloading drivers from Google helped resolved the issue. Here is the URL with documentation. And here you can download the driver itself.
P.S. I saw some people advice to download some drivers from random places on internet. While this might help it's too dangerous in my mind to download unknown drivers from unofficial places. So the one from Google worked well for me :)
Be sure to have both objects created in controller: @post
and @comment
for the post, eg:
@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)
Then in view:
<%= form_for([@post, @comment]) do |f| %>
Be sure to explicitly define the array in the form_for, not just comma separated like you have above.
You can also force flush the buffer to a file programmatically with the flush()
method.
with open('out.log', 'w+') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
# some other work
f.write('done\n')
f.flush()
I have found this useful when tailing an output file with tail -f
.
Just aggregating the answers and expanding on the basics. Here are three options:
We can include echo=FALSE
in the chunk header:
```{r echo=FALSE}
plot(cars)
```
We can change the default behaviour of knitr using the knitr::opts_chunk$set
function. We call this at the start of the document and include include=FALSE
in the chunk header to suppress any output:
---
output: html_document
---
```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```
```{r}
plot(cars)
```
For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.
---
output:
html_document:
code_folding: "hide"
---
```{r}
plot(cars)
```
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
You can use strstr
. Example code here.
Note that the returned result is not null terminated.
Minimal runnable Linux system call example
Linux sets up the interrupt handler for 0x80
such that it implements system calls, a way for userland programs to communicate with the kernel.
.data
s:
.ascii "hello world\n"
len = . - s
.text
.global _start
_start:
movl $4, %eax /* write system call number */
movl $1, %ebx /* stdout */
movl $s, %ecx /* the data to print */
movl $len, %edx /* length of the buffer */
int $0x80
movl $1, %eax /* exit system call number */
movl $0, %ebx /* exit status */
int $0x80
Compile and run with:
as -o main.o main.S
ld -o main.out main.o
./main.out
Outcome: the program prints to stdout:
hello world
and exits cleanly.
You cannot set your own interrupt handlers directly from userland because you only have ring 3 and Linux prevents you from doing so.
GitHub upstream. Tested on Ubuntu 16.04.
Better alternatives
int 0x80
has been superseded by better alternatives for making system calls: first sysenter
, then VDSO.
x86_64 has a new syscall
instruction.
See also: What is better "int 0x80" or "syscall"?
Minimal 16-bit example
First learn how to create a minimal bootloader OS and run it on QEMU and real hardware as I've explained here: https://stackoverflow.com/a/32483545/895245
Now you can run in 16-bit real mode:
movw $handler0, 0x00
mov %cs, 0x02
movw $handler1, 0x04
mov %cs, 0x06
int $0
int $1
hlt
handler0:
/* Do 0. */
iret
handler1:
/* Do 1. */
iret
This would do in order:
Do 0.
Do 1.
hlt
: stop executingNote how the processor looks for the first handler at address 0
, and the second one at 4
: that is a table of handlers called the IVT, and each entry has 4 bytes.
Minimal example that does some IO to make handlers visible.
Minimal protected mode example
Modern operating systems run in the so called protected mode.
The handling has more options in this mode, so it is more complex, but the spirit is the same.
The key step is using the LGDT and LIDT instructions, which point the address of an in-memory data structure (the Interrupt Descriptor Table) that describes the handlers.
I had same problem - when I tried to run a Java program from command line the error message appeared: "Error: could not open jvm.cfg". My Path environment variable included following path:
C:\ProgramData\Oracle\Java\javapath
In the folder there were 3 exe files:
java.exe
javaw.exe
javaws.exe
When I removed the the entry
C:\ProgramData\Oracle\Java\javapath
from the Path environment variable and restarted cmd, I could run the program as usual (java MyProg). Obviously I have corrupted the path pointing to correct java jre installation
C:\Program Files\Java\jre1.8.0_151
somehow previously when I played with my settings.
You can try this
SELECT tbl.* FROM (SELECT * FROM table ORDER BY timestamp DESC) as tbl
GROUP BY tbl.m_id
You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
From the JavaDocs
setOpaque
public void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds. Otherwise,
the component may not paint some or all of its pixels, allowing the underlying
pixels to show through.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:
UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)
in Eclips the Package Explorer Right click on any viewable project and select Show in -> Project Explorer
Package Explorer -> Right click -> Show in ->Project Explorer
you should be able to see all the imported projects in your Eclipse workspace
String test = DateTime.Now.ToString("dd.MM.yyy");
You can do it on a per file basis. Use the path attribute to include the filename
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="YourFileNameHere.xml">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
Using @Marc Gravell 's answer, I found a way to use the following method:
source.TakeWhile(x => x != value).Count();
in order to get -1 when the item cannot be found:
internal static class Utils
{
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item) => enumerable.IndexOf(item, EqualityComparer<T>.Default);
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item, EqualityComparer<T> comparer)
{
int index = enumerable.TakeWhile(x => comparer.Equals(x, item)).Count();
return index == enumerable.Count() ? -1 : index;
}
}
I guess this way could be both the fastest and the simpler. However, I've not tested performances yet.
Screen Size Class
-
Hidden on all .d-none
Hidden only on xs .d-none .d-sm-block
Hidden only on sm .d-sm-none .d-md-block
Hidden only on md .d-md-none .d-lg-block
Hidden only on lg .d-lg-none .d-xl-block
Hidden only on xl .d-xl-none
Visible on all .d-block
Visible only on xs .d-block .d-sm-none
Visible only on sm .d-none .d-sm-block .d-md-none
Visible only on md .d-none .d-md-block .d-lg-none
Visible only on lg .d-none .d-lg-block .d-xl-none
Visible only on xl .d-none .d-xl-block
Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
I solved this issue by fixing some paths in settings.gradle as shown below:
include ':project-external-module'
project(':project-external-module').projectDir = file('/project/wrong/path')
I was including an external module to my project and had the wrong path for it.
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
There is one another method of temp table
create table #TempTable (
ID int,
name varchar(max)
)
insert into #TempTable (ID,name)
Select ID,Name
from Table
SELECT *
FROM #TempTable
WHERE ID = 1
Make Sure You are selecting the right database.
Quote:
The "-a" operator also doesn't work:
if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
For a more elaborate explanation: [
and ]
are not Bash reserved words. The if
keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0
or false otherwise).
For trivial tests, there is the test
program (man test
).
As some find lines like if test -f filename; then foo bar; fi
, etc. annoying, on most systems you find a program called [
which is in fact only a symlink to the test
program. When test
is called as [
, you have to add ]
as the last positional argument.
So if test -f filename
is basically the same (in terms of processes spawned) as if [ -f filename ]
. In both cases the test
program will be started, and both processes should behave identically.
Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
will parse to if
+ some job, the job being everything except the if
itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([
) is the command and the rest its positional arguments. There are remaining arguments after the first ]
.
Also not, [[
is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.
For skipping memory limit and version error use the code below:
COMPOSER_MEMORY_LIMIT=-1 composer require <package-name> --ignore-platform-reqs
v. community 5.0.4 (linux): File -> Settings -> Editor -> General -> Appearance -> now check 'Show line numbers', confirm w. OK an voila :)
<font color="red">This is some text!</font>
This worked the best for me when I only wanted to change one word into the color red in a sentence.
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
You should also keep in mind that when using like
, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.
You should really look at the execution plan for the query and see what it's doing, guess as little as possible.
This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like
for StartsWith
for this very reason.
I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc
path. So if you have a program running, whose ID is 1199, cd
into it:
$ cd /proc/1199
Then look for the fd
directory underneath
$ cd fd
This fd
directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f
the one you need - in this case, stdout):
$ tail -f 1
Simple: don't use an AsyncTask
. AsyncTask
is designed for short operations that end quickly (tens of seconds) and therefore do not need to be canceled. "Audio file playback" does not qualify. You don't even need a background thread for ordinary audio file playback.
U cant try this
for (WordList i : words) {
words.get(words.indexOf(i));
}
One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.
You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only
function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}
and
$(document).ready(function() {
$(window).resize(resize);
resize();
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});
Actually, I figured it out myself that I could do this:
while (rdr.read())
{
string str = rdr.GetValue().ToString().Trim();
}
If you're looking for a portable C compiled tool:
http://stedolan.github.com/jq/
From the website:
jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you’d expect.
Tutorial: http://stedolan.github.com/jq/tutorial/
Manual: http://stedolan.github.com/jq/manual/
Download: http://stedolan.github.com/jq/download/
Best result for me so far:
div to be centered:
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;
I was able to solve that problem by adding this to my controller method:
$title = 'My Title Here';
View::share('title', $title);
$this->layout->title = 'Home page'; did not work either.
This should work fine.
Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
Row row=sheet.getRow(0);
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
If you do not create defaultFont
all your workbook will be using the other one as default.
Simple, edit /etc/nginx/nginx.conf and remove comment from
#server_tokens off;
Search for http section.
1- create new java file (right click the package. new > class > name the file ConnectionDetector.java
2- add the following code to the file
package <add you package name> example com.example.example;
import android.content.Context;
import android.net.ConnectivityManager;
public class ConnectionDetector {
private Context mContext;
public ConnectionDetector(Context context){
this.mContext = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
{
return true;
}
return false;
}
}
3- open your MainActivity.java
- the activity where you want to check connection, and do the following
A- create and define the function.
ConnectionDetector mConnectionDetector;</pre>
B- inside the "OnCreate" add the following
mConnectionDetector = new ConnectionDetector(getApplicationContext());
c- to check connection use the following steps
if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}
Just because I did not see it mentioned.
If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.
Example
Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
Insert Into @YourTable Values
(1,'A','B')
,(2,'R','C')
,(3,'X','D')
Select A.[ID]
,Item = B.[Key]
,Value = B.[Value]
From @YourTable A
Cross Apply ( Select *
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] not in ('ID','Other','Columns','ToExclude')
) B
Returns
ID Item Value
1 Col1 A
1 Col2 B
2 Col1 R
2 Col2 C
3 Col1 X
3 Col2 D
Wait function using timers, no UI locks.
public void wait(int milliseconds)
{
var timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
// Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
// Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
Usage: just placing this inside your code that needs to wait:
wait(1000); //wait one second
In my case git rm --cached
didn't work.
But i got it with a git rebase
In addition to flup's answer you might also want to run the following to set JAVA_HOME and PATH:
sudo apt-get install oracle-java7-set-default
More information at: http://www.ubuntuupdates.org/package/webupd8_java/precise/main/base/oracle-java7-set-default
If those elements have a common class name, one may also use this:
$('#your_div .your_classname').serialize()
This way you can avoid selection of buttons, which will be selected using the jQuery selector :input
. Though this can also be avoided by using $('#your_div :input:not(:button)').serialize();
It could just be because ACID is one set of properties that substances show( in Chemistry) and BASE is a complement set of them.So it could be just to show the contrast between the two that the acronym was made up and then 'Basically Available Soft State Eventual Consistency' was decided as it's full-form.
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:
import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array
res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])
which can be extended to D dimensions.
The results are:
Prediction:
[[1 2]
[2 0]
[2 0]
[1 2]
[1 2]]
Target:
[[0 1]
[1 0]
[2 0]
[0 0]
[2 1]]
Count of correct prediction for D=1: 1
Count of correct prediction for D=2: 2
Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):
Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )
Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.
Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.
Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64
Find extension on this site, then put them into the python folder, and install .whl extension with pip:
python -m pip install extensionname.whl
Enjoy
Why
There is IMHO a good reason why Composer will use the --dev
flag by default (on install and update) nowadays. Composer is mostly run in scenario's where this is desired behavior:
The basic Composer workflow is as follows:
composer.phar install --dev
, json and lock files are commited to VCS.composer.phar install --dev
.composer.phar require <package>
, add --dev
if you want the package in the require-dev
section (and commit).composer.phar install --dev
.composer.phar update --dev <package>
(and commit).composer.phar install --dev
.composer.phar install --no-dev
As you can see the --dev
flag is used (far) more than the --no-dev
flag, especially when the number of developers working on the project grows.
Production deploy
What's the correct way to deploy this without installing the "dev" dependencies?
Well, the composer.json
and composer.lock
file should be committed to VCS. Don't omit composer.lock
because it contains important information on package-versions that should be used.
When performing a production deploy, you can pass the --no-dev
flag to Composer:
composer.phar install --no-dev
The composer.lock
file might contain information about dev-packages. This doesn't matter. The --no-dev
flag will make sure those dev-packages are not installed.
When I say "production deploy", I mean a deploy that's aimed at being used in production. I'm not arguing whether a composer.phar install
should be done on a production server, or on a staging server where things can be reviewed. That is not the scope of this answer. I'm merely pointing out how to composer.phar install
without installing "dev" dependencies.
Offtopic
The --optimize-autoloader
flag might also be desirable on production (it generates a class-map which will speed up autoloading in your application):
composer.phar install --no-dev --optimize-autoloader
Or when automated deployment is done:
composer.phar install --no-ansi --no-dev --no-interaction --no-plugins --no-progress --no-scripts --optimize-autoloader
If your codebase supports it, you could swap out --optimize-autoloader
for --classmap-authoritative
. More info here
You can create your own JsonDeserializer and annotate that property with @JsonDeserialize(as = DefaultZero.class)
For example: To configure BigDecimal to default to ZERO:
public static class DefaultZero extends JsonDeserializer<BigDecimal> {
private final JsonDeserializer<BigDecimal> delegate;
public DefaultZero(JsonDeserializer<BigDecimal> delegate) {
this.delegate = delegate;
}
@Override
public BigDecimal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return jsonParser.getDecimalValue();
}
@Override
public BigDecimal getNullValue(DeserializationContext ctxt) throws JsonMappingException {
return BigDecimal.ZERO;
}
}
And usage:
class Sth {
@JsonDeserialize(as = DefaultZero.class)
BigDecimal property;
}
To people ending up here when searching for the Gradle equivalent of the Maven property maven.compiler.source
(or <source>1.8</source>
):
In build.gradle you can achieve this with
apply plugin: 'java'
sourceCompatibility = 1.8
targetCompatibility = 1.8
See the Gradle documentation on this.
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
Edit:
In the newer version of pandas, you can pass the sheet name as a parameter.
file_name = # path to file + file name
sheet = # sheet name or sheet number or list of sheet numbers and names
import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5)) # print first 5 rows of the dataframe
Check the docs for examples on how to pass sheet_name
:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
Old version:
you can use pandas
package as well....
When you are working with an excel file with multiple sheets, you can use:
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
df.head()
will print first 5 rows of your Excel file
If you're working with an Excel file with a single sheet, you can simply use:
import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
To expand on Peri's post & why we may not want to use viewstate the following code:
style="<%= _myCSS %>"
Protected _myCSS As String = "display: none"
Is the approach to look at if you're using AJAX, it allows for manipulating the display via asp.net back end code rather than jquery/jscript.
You need to look up every class loader entry in the class path:
String pkg = "org/apache/commons/lang";
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader) cl).getURLs();
for (URL url : urls) {
System.out.println(url.getFile());
File jar = new File(url.getFile());
// ....
}
If entry is directory, just look up in the right subdirectory:
if (jar.isDirectory()) {
File subdir = new File(jar, pkg);
if (!subdir.exists())
continue;
File[] files = subdir.listFiles();
for (File file : files) {
if (!file.isFile())
continue;
if (file.getName().endsWith(".class"))
System.out.println("Found class: "
+ file.getName().substring(0,
file.getName().length() - 6));
}
}
If the entry is the file, and it's jar, inspect the ZIP entries of it:
else {
// try to open as ZIP
try {
ZipFile zip = new ZipFile(jar);
for (Enumeration<? extends ZipEntry> entries = zip
.entries(); entries.hasMoreElements();) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
if (!name.startsWith(pkg))
continue;
name = name.substring(pkg.length() + 1);
if (name.indexOf('/') < 0 && name.endsWith(".class"))
System.out.println("Found class: "
+ name.substring(0, name.length() - 6));
}
} catch (ZipException e) {
System.out.println("Not a ZIP: " + e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
Now once you have all class names withing package, you can try loading them with reflection and analyze if they are classes or interfaces, etc.
None of these solutions worked for me. I had to append bash
environment to the zsh
:
echo 'source ~/.bash_profile' >> ~/.zshrc
Take a look at Twitter's:
http://twitter.com/crossdomain.xml
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
<allow-access-from domain="twitter.com" />
<allow-access-from domain="api.twitter.com" />
<allow-access-from domain="search.twitter.com" />
<allow-access-from domain="static.twitter.com" />
<site-control permitted-cross-domain-policies="master-only"/>
<allow-http-request-headers-from domain="*.twitter.com" headers="*" secure="true"/>
</cross-domain-policy>
One liner if you want something compact:
String.prototype.pad = function(len, chr){_x000D_
return((((new Array(len)).fill(chr)).join("") +this).substring(this.length));_x000D_
}
_x000D_
One thing that i didn't see in other answers is To clarify another answers that there is a difference between returning std::unique_ptr that has been created within a function, and one that has been given to that function.
The example could be like this:
class Test
{int i;};
std::unique_ptr<Test> foo1()
{
std::unique_ptr<Test> res(new Test);
return res;
}
std::unique_ptr<Test> foo2(std::unique_ptr<Test>&& t)
{
// return t; // this will produce an error!
return std::move(t);
}
//...
auto test1=foo1();
auto test2=foo2(std::unique_ptr<Test>(new Test));
In Eclipse Helios "Java EE Module Dependencies" in the project properties has been replaced with "Deployment Assembly".
So for solving this problem with Eclipse Helios, the way I did it is the following:
This solves the problem, but if you want to check what has happened in "Deployment Assembly", open the project properties again, select "Deployment Assembly" and you'll see that standard.jar and jstl.jar have been added to WEB-INF/lib folder.
The answers here are outdated, as of today Sep 30 2016. Gmail is currently rolling out support for the style
tag in the head
, as well as media queries. If Gmail is your only concern, you're safe to use classes like a modern developer!
For reference, you can check the official gmail CSS docs.
As a side note, Gmail was the only major client that didn't support style
(reference, until they update anyway). That means you can almost safely stop putting styles inline. Some of the more obscure clients may still need them.
I tend to use xsd from Microsoft to help generate the xsd from a .NET file. I also parse out sections of the xml using xmlstarlet. The final free tool that would be of use to you is altovaxml, which is available at this URL: http://www.altova.com/download_components.html .
This allows me to scan all the xml files picking up which xsd to use by parsing the xml.
# Function:
# verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory
# Parameters:
# The directory where the schema *.xsd files are located. Must be using dos pathing like: VerifySchemas "c:\\XMLSchemas\\"
# Requirements:
# Must be in the directory where the configuration files are located
#
verifyschemas()
{
for FILENAME in $(find . -name '*.xml' -print0 | xargs -0)
do
local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd
altovaxml /validate $FILENAME /schema $SchemaFile > ~/temp.txt 2> /dev/null
if [ $? -ne 0 ]; then
printf "Failed to verify: "
cat ~/temp.txt | tail -1 | tr -d '\r'
printf " - $FILENAME with $SchemaFile\n"
fi
done
}
To generate the xml I use: xsd DOTNET.dll /type:CFGCLASS & rename schema0.xsd CFGCLASS.xsd
To get the xsd name I use: xmlstarlet sel -t -m /XXX/* -v local-name() $1 | sed 's/ $//'
This allows me to pickup the correct XSD using an element tag within the xml file.
The net result is that I can call a bash function to scan all the XML files and verify them. Even if they are in multiple subdirectories.
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
If the elapsed event takes longer then the interval, it will create another thread to raise the elapsed event. But there is a workaround for this
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
timer.Stop();
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
finally
{
timer.Start();
}
}
So wait, this is just a list-within-a-list?
The easiest way is probably just to use nested for loops:
>>> a = [[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> a
[[1, 3, 4], [2, 4, 4], [3, 4, 5]]
>>> for list in a:
... for number in list:
... print number
...
1
3
4
2
4
4
3
4
5
Or is it something more complicated than that? Arbitrary nesting or something? Let us know if there's something else as well.
Also, for performance reasons, you might want to look at using list comprehensions to do this:
http://docs.python.org/tutorial/datastructures.html#nested-list-comprehensions
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
For TypeScript 2.0 it would look like this:
MyStore.ts
export namespace Store {
export type Login = { isLoggedIn: boolean }
export type All = {
login: Login
}
}
import { reducers } from '../Reducers'
import * as Redux from 'redux'
const reduxStore: Redux.Store<Store.All> = Redux.createStore(reducers)
export default reduxStore;
MyClient.tsx
import reduxStore from "../Store";
{reduxStore.dispatch(...)}
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
AS Scott mentioned here http://weblogs.asp.net/scottgu/archive/2010/09/30/asp-net-security-fix-now-on-windows-update.aspx After windows installed security update for .net framework, you will meet this problem. just modify the configuration section in your web.config file and switch to a different cookie name.
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
Try this:
List< Object> myList = x.getName;
myList.sort(Comparator.comparing(Object::getName));
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
SELECT COUNT(*)
FROM table_emp
WHERE YEAR(ARR_DATE) = '2012'
GROUP BY MONTH(ARR_DATE)
Run from the project folder
msbuild /p:DeployOnBuild=true /p:PublishProfile="release-file.pubxml" /p:AspnetMergePath="C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools" /p:Configuration=Release
This takes care of web.config Transform and AspnetMergePath
The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)
ID EXPRESSION "ID_SEQ.nextval"
or
ID SEQUENCE(count)
See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options
The problem with using <Redirect from="/" to="searchDashboard" />
is if you have a different URL, say /indexDashboard
and the user hits refresh or gets a URL sent to them, the user will be redirected to /searchDashboard
anyway.
If you wan't users to be able to refresh the site or send URLs use this:
<Route exact path="/" render={() => (
<Redirect to="/searchDashboard"/>
)}/>
Use this if searchDashboard
is behind login:
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/searchDashboard"/>
) : (
<Redirect to="/login"/>
)
)}/>
This workaround works:
define a “keyframe”:
@-webkit-keyframes fadeIn {
0% { opacity: 0; }
20% { opacity: 0; }
40% { opacity: 0.3; }
60% { opacity: 0.5; }
80% { opacity: 0.9; }
100% { opacity: 1; }
}
@keyframes fadeIn {
0% { opacity: 0; }
20% { opacity: 0; }
40% { opacity: 0.3; }
60% { opacity: 0.5; }
80% { opacity: 0.9; }
100% { opacity: 1; }
}
Use this “keyframe” on “hover”:
div a span {
display: none;
}
div a:hover span {
display: block;
-webkit-animation-name: fadeIn;
-webkit-animation-duration: 1s;
animation-name: fadeIn;
animation-duration: 1s;
}
As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:
#!/usr/bin/python
import sys
from subprocess import call
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
if ref == 'refs/heads/master':
print "=============================================="
print "Pushing to master. Triggering jenkins. "
print "=============================================="
sys.stdout.flush()
call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])
In this case I trigger jenkins jobs only when pushing to master and not other branches.
Out of curiosity, I wanted to see how Value
performed against Value2
. After about 12 trials of similar processes, I could not see any significant differences in speed so I would always recommend using Value
. I used the below code to run some tests with various ranges.
If anyone sees anything contrary regarding performance, please post.
Sub Trial_RUN()
For t = 0 To 5
TestValueMethod (True)
TestValueMethod (False)
Next t
End Sub
Sub TestValueMethod(useValue2 As Boolean)
Dim beginTime As Date, aCell As Range, rngAddress As String, ResultsColumn As Long
ResultsColumn = 5
'have some values in your RngAddress. in my case i put =Rand() in the cells, and then set to values
rngAddress = "A2:A399999" 'I changed this around on my sets.
With ThisWorkbook.Sheets(1)
.Range(rngAddress).Offset(0, 1).ClearContents
beginTime = Now
For Each aCell In .Range(rngAddress).Cells
If useValue2 Then
aCell.Offset(0, 1).Value2 = aCell.Value2 + aCell.Offset(-1, 1).Value2
Else
aCell.Offset(0, 1).Value = aCell.Value + aCell.Offset(-1, 1).Value
End If
Next aCell
Dim Answer As String
If useValue2 Then Answer = " using Value2"
.Cells(Rows.Count, ResultsColumn).End(xlUp).Offset(1, 0) = DateDiff("S", beginTime, Now) & _
" seconds. For " & .Range(rngAddress).Cells.Count & " cells, at " & Now & Answer
End With
End Sub
The solution that worked for me is the following one given by Steve Hansen Smythe. I am just pasting it here. Thanks Steve.
"I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.
I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly."
try to add display: block;
(or replace the <span>
by a <div>
) (note that this could cause other problems becuase a <span>
is inline by default - but you havn't posted the rest of your html)
add an ALIAS
on the subquery,
SELECT COUNT(made_only_recharge) AS made_only_recharge
FROM
(
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER = '0130'
EXCEPT
SELECT DISTINCT (identifiant) AS made_only_recharge
FROM cdr_data
WHERE CALLEDNUMBER != '0130'
) AS derivedTable -- <<== HERE
For windows users look at the .gitconfig file and check what has been configured for the credential helper if you have the following...
[credential "helperselector"] selected = wincred
you'll find the credentials in the Windows Credential Manager.
There you can edit the credential.
EDIT: Wincred has been deprecated, see...
https://github.com/git-for-windows/git-sdk-64/tree/main/mingw64/doc/git-credential-manager
So alternatively you may want to reconfigure git to use the built-in GIT credential manager...
git config --global credential.helper manager
Below applies to all tags with the following two classes
.abc.xyz {
width: 200px !important;
}
applies to div tags with the following two classes
div.abc.xyz {
width: 200px !important;
}
If you wanted to modify this using jQuery
$(document).ready(function() {
$("div.abc.xyz").width("200px");
});
this helper method get fragment from top of stack:
public Fragment getTopFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
Assuming SQL Server 2005+ an example of how to get just the second row (which I think you may be asking - and is the reason why top
won't work for you?)
set statistics io on
;with cte as
(
select *
, ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
)
select *
from cte
where rn = 2
/* Just to add in what I was running RE: Comments */
;with cte as
(
select top 2 *
, ROW_NUMBER() over (order by number) as rn
from master.dbo.spt_values
)
select *
from cte
where rn = 2
Attempt http://challenge.greplin.com/ using Python
Use the "$" on a reg expression to match the end of the string
$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);
//output
'The quick brown fox jumps over the lazy dog'
The IF
statement does not support logical operators AND
and OR
.
Cascading IF
statements make an implicit conjunction:
IF Exist File1.Dat IF Exist File2.Dat GOTO FILE12_EXIST_LABEL
If File1.Dat
and File2.Dat
exist then jump to the label FILE12_EXIST_LABEL
.
See also: IF /?
we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just found the solution to this for myself. What you want to set is the maxIdleTime of WebSocketServlet, in millis. How to do that depends on how you config your servlet. With Guice ServletModule you can do something like this for timeout of 10 hours:
serve("ws").with(MyWSServlet.class,
new HashMap<String, Sring>(){{ put("maxIdleTime", TimeUnit.HOURS.toMillis(10) + ""); }});
Anything <0 is infinite idle time I believe.
ssh -t -t [email protected] << EOF
echo SOMEPASSWORD | sudo -S do something
sudo do something else
exit
EOF
The variables you need are explained here in the jenkins wiki: https://wiki.jenkins.io/display/JENKINS/Features+controlled+by+system+properties
The default variable ITEM_ROOTDIR points to a directory inside the jenkins installation. As you already found out you need:
You need to achieve this through config.xml nowerdays. Citing from the wiki page linked above:
This used to be a UI setting, but was removed in 2.119 as it did not support migration of existing build records and could lead to build-related errors until restart.
Ok First of all this is a very clear error message. Just look at this many devs miss this including my self. Have a look at the screen shot here please.
or just go to this url here (Replace YOUR_APP_ID with your app id lol):
https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/settings/
If you are working on localhost:3000
Make sure you have https://localhost:3000/auth/facebook/callback
Ofcourse you don't have to have the status live (Green Switch on top right corner) but in my case, I am deploying to heroku now and will soon replace localhost:3000
with https://myapp.herokuapp.com/auth/facebook/callback
Of course I will update the urls in Settings/Basic & Settings/Advanced and also add a privacy policy url in the basic section.
I am assuming that you have properly configured initializers/devise.rb if you are using devise and you have the proper facebook gem 'omniauth-facebook', '~> 4.0'
gem installed and gem 'omniauth', '~> 1.6'
, and you have the necessary columns in your users table such as uid, image, and provider. That's it.
The function you're looking for is 'Insert'. It takes as its parameters the index you want to insert at, and an array of values to use for the new row values. Typical usage might include:
myDataGridView.Rows.Insert(4,new object[]{value1,value2,value3});
or something to that effect.
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
We can use generate function which exists in algorithm header file.
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int>v(10);
int n=0;
generate(v.begin(), v.end(), [&n] { return n++;});
for(auto item : v)
{
cout<<item<<" ";
}
cout<<endl;
return 0;
}
The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:
public static void main(String[] args) {
int lines = 0;
// TODO - Need to get the filename to populate sFileName. Could
// come from the command line arguments.
try {
lines = LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
if(lines > 0) {
// Do rest of program.
}
}