When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.
From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :
int myInt = new Integer(11);
Integer myInt2 = myInt;
The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long
,Double
,Short
too)
You may use int
all the time, but Integer
contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String)
)
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function
, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList
not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join()
, I prefer list comprehensions and generators over map()
so I would probably use the following:
print '\n'.join(str(p) for p in myList)
HashMap<String,Integer> hm = new HashMap();
hm.put("A",1);
hm.put("B",2);
hm.put("C",3);
hm.put("D",4);
hm.forEach((key,value)->{
System.out.println("Key: "+key + " value: "+value);
});
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');
foreach($foo as $key => $item) {
echo $item.' is begin with ('.$key.')';
}
The thing you will need to do here is use a linear gradient as background and animate the background position. In code:
Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.
background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;
On hover, change the background position to right bottom
and with transition:all 2s ease;
, the position will change gradually (it's nicer with linear
tough)
background-position:right bottom;
As for the -vendor-prefix'es, see the comments to your question
extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).
background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;
div {
font: 22px Arial;
display: inline-block;
padding: 1em 2em;
text-align: center;
color: white;
background: red; /* default color */
/* "to left" / "to right" - affects initial color */
background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
background-size: 200%;
transition: .5s ease-out;
}
div:hover {
background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
I actually found a better way to send files using HttpURLConnection using MultipartEntity
private static String multipost(String urlString, MultipartEntity reqEntity) {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
return readStream(conn.getInputStream());
}
} catch (Exception e) {
Log.e(TAG, "multipart post error " + e + "(" + urlString + ")");
}
return null;
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
Assuming you are uploading an image with bitmap data:
Bitmap bitmap = ...;
String filename = "filename.png";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("picture", contentPart);
String response = multipost("http://server.com", reqEntity);
And Voila! Your post data will contain picture field along with the filename and path on your server.
Ordinarily, float
s aren't counted in the layout of their parents.
To prevent that, add overflow: hidden
to the parent.
There should only be one way to do a thing, is contradicted by the usage of multiline strings and single line strings or switch/case and if, different form of loops.
Multiline comments are a pretty common feature and lets face it the multiline string comment is a hack with negative sideffects! I have seen lots of code doing the multiline comment trick and even editors use it.
But I guess every language has its quirks where the devs insist on never fixing it. I know such quirks from the java side as well, which have been open since the late 90s, never to be fixed!
My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)
# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)
# tails of the arrows
tails= np.zeros(len(bvecs))
# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title('b-vectors on unit sphere')
plt.show()
If you want insert all data from one table to another table there is a very simply sql
INSERT INTO destinationTable (SELECT * FROM sourceDbName.SourceTableName);
Use the following code fragment to hide the form on button click.
document.getElementById("your form id").style.display="none";
And the following code to display it:
document.getElementById("your form id").style.display="block";
Or you can use the same function for both purposes:
function asd(a)
{
if(a==1)
document.getElementById("asd").style.display="none";
else
document.getElementById("asd").style.display="block";
}
And the HTML:
<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>
You can use this function, for split string from ?id=
function myfunction(myvar){
var urls = myvar;
var myurls = urls.split("?id=");
var mylasturls = myurls[1];
var mynexturls = mylasturls.split("&");
var url = mynexturls[0];
alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");
here is the fiddle
I have resolved this problem using following steps
1) Remove every file from Git's index.
git rm --cached -r .
2) Rewrite the Git index to pick up all the new line endings.
git reset --hard
Solution was part of steps described on git site https://help.github.com/articles/dealing-with-line-endings/
In Java you can get the keys using ListObjects (see AWS documentation)
FileWriter fileWriter;
BufferedWriter bufferedWriter;
// [...]
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("myprefix");
ObjectListing objectListing;
do {
objectListing = s3client.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary :
objectListing.getObjectSummaries()) {
// write to file with e.g. a bufferedWriter
bufferedWriter.write(objectSummary.getKey());
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
Make sure of the conflict origin: if it is the result of a git merge
, see Brian Campbell's answer.
But if is the result of a git rebase
, in order to discard remote (their) changes and use local changes, you would have to do a:
git checkout --theirs -- .
See "Why is the meaning of “ours
” and “theirs
” reversed"" to see how ours
and theirs
are swapped during a rebase (because the upstream branch is checked out).
This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):
http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html
From the article, the easiest command I saw to revert a previous commit by its commit id, was:
git revert dd61ab32
You can follow this approach:
void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
int val;
if (dic.TryGetValue(key, out val))
{
// yay, value exists!
dic[key] = val + newValue;
}
else
{
// darn, lets add the value
dic.Add(key, newValue);
}
}
The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary.
If you use ContainsKey
to check the existance and update the value using dic[key] = val + newValue;
then you are accessing the dictionary twice.
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
<v-container>
has to be right after <template>
, if there is a <div>
in between, the vertical align will just not work.
<template>
<v-container fill-height>
<v-row class="justify-center align-center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
</template>
You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps
As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface
and Abstract class
.
Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.
The below class acts as a base class for all the cars:
public class Cars
{
public string DigitalFuelMeter()
{
return "I have DigitalFuelMeter";
}
public string AirCondition()
{
return "I have AC";
}
public string SeatAdjust()
{
return "I can Adjust seat";
}
}
Consider we have a separate class for each Cars.
public class Alto : Cars
{
// Have all the features of Car class
}
public class Verna : Cars
{
// Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars
}
public class Cruze : Cars
{
// Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars
}
Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.
public abstract class Brake
{
public abstract string GetBrakeTechnology();
}
Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:
public class Verna : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.
interface IBrakeTechnology
{
string GetBrakeTechnology();
}
And the implementation is given below:
public class Verna : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
Run svn cleanup
command in a terminal (if it fails from Eclipse which was my case):
~/path/to/svn-folder/$ svn cleanup
I tried different solutions explained here, but none worked.
Action Team ? Update to head fails:
svn: E155004: There are unfinished work items in '/home/user/path/to/svn-folder'; run 'svn cleanup' first.
Action Team ? Cleanup fails with same error.
Solution that worked for me: run svn cleanup command in a terminal.
The command succeeded.
Then Team ? Update in Eclipse worked again.
Note: my SVN version is 1.9.3.
Also check Chris's answer if svn cleanup
does not work.
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect javascript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your javascript in an external javascript file that is included with:
<script type="text/javascript" src="http://mydomain.com/xxxx.js"></script>
tags, then the javascript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external javascript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at you do, not by having secrets. That's ultimately how success works on the web anyway.
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for
loop.
for e in filter(f, range(2, 25)):
do_stuff(e)
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
There is a dirty trick, what I have used:
I am using bootstrap, so I just added .disabled
class to the element which I want to disable. Bootstrap handles the rest of the things.
Suggestion are heartily welcome towards this.
Adding class on run time:
$('#element').addClass('disabled');
I had to make few modifications in order to make it with in IE8 (didn't test with other IE flavours)
1) document.frames[param] seem to accept a number, not ID
printIframe(0, 'print');
function printIframe(num, id)
{
var iframe = document.frames ? document.frames[num] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
return false;
}
2) I had a print dialog displayed upon page load and also there was a link to "Click here to start printing" (if it didn't start automatically). In order to get it work I had to add focus() call
<script type="text/javascript">
$(function(){
printPage();
});
function printPage()
{
focus();
print();
}
</script>
You missed putting single quotes around your array keys:
$_POST[email]
should be:
$_POST['email']
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
I had a lecturer who once suggested generating a random array, checking if it was sorted and then checking if the data was the same as the array to be sorted.
Best case O(N) (first time baby!) Worst case O(Never)
Simply get last month.
Today is: 2020-09-02
Code:
echo date('Y-m-d', strtotime(date('Y-m-d')." -1 month"));
Result:
2020-08-02
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTirgger("NewValue");
Or you can override the val function to always call the change when the val is called
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
It may be a permission issue,
Please try the following command /etc/init.d/mysqld start
as root user.
This is a security feature in Rails. Add this line of code in the form:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html
The below worked for me
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.
Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera
Cross-browser caret positioning technique (example: moving the cursor to the END)
// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)
setCaretPosition('IDHERE', 10); // example
The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0)
, in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.
In chrome the biggest issue was that just giving it .focus()
wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value;
before calling our function, and now it has a grasp & position with the input to use selectionStart.
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
call this method and pass your set
func getArrayFromSet(set:NSSet)-> NSArray {
return set.map ({ String($0) })
}
Like This :
var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))
select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;
HTH
Looking at your example, I think this is what you want:
var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);
In Python 3.x basestring
is not available anymore, as str
is the sole string type (with the semantics of Python 2.x's unicode
).
So the check in Python 3.x is just:
isinstance(obj_to_test, str)
This follows the fix of the official 2to3
conversion tool: converting basestring
to str
.
Create a toolbar in your xml...toolbar.xml:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
</android.support.v7.widget.Toolbar>
Then add the following in your toolbar.xml:
app:titleTextColor="@color/colorText"
app:title="@string/app_name">
Remeber @color/colorText is simply your color.xml file with the color attribute named colorText and your color.This is the best way to calll your strings rather than hardcoding your color inside your toolbar.xml. You also have other options to modify your text,such as:textAppearance...etc...just type app:text...and intelisense will give you options in android studio.
your final toolbar should look like this:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="@style/Theme.AppCompat"
app:subtitleTextAppearance="@drawable/icon"
app:title="@string/app_name">
</android.support.v7.widget.Toolbar>
NB:This toolbar should be inside your activity_main.xml.Easy Peasie
Another option is to do it all in your class:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);
Good Luck
You may also need to override UIViewController disablesAutomaticKeyboardDismissal to get this to work in some cases. This may have to be done on the UINavigationController if you have one.
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
With jQuery, I've found that sometimes using val
to clear the value of a textbox has no effect, in those situations I've found that using attr
does the job
$('#searchField').attr("value", "");
I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value
directly without relating to additional objects.
To clarify an already posted solution due to questions in the comments
import numpy
array = numpy.array([49, 51, 53, 56])
array = array - 13
will output:
array([36, 38, 40, 43])
Everything. They're unrelated languages.
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
=
operatorWe can use the public member function std::vector::operator=
of the container std::vector
for assigning values from a vector to another.
Besides, a constructor function also makes sense. A constructor function with another vector as parameter(e.g. x
) constructs a container with a copy of each of the elements in x
, in the same order.
std::vector::swap
std::vector::swap
is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests. In other words, the source vector to copy from is modified after std::vector::swap
is called, which is probably not what you are expected.
If the elements in the source vector are pointers to other data, then a deep copy is wanted sometimes.
According to wikipedia:
A deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B.
Actually, there is no currently a built-in way in C++ to do a deep copy. All of the ways mentioned above are shallow. If a deep copy is necessary, you can traverse a vector and make copy of the references manually. Alternatively, an iterator can be considered for traversing. Discussion on iterator is beyond this question.
You did everything except copying the new pixel value back to the image.
This line takes a copy of the pixel into a local variable:
Vec3b color = image.at<Vec3b>(Point(x,y));
So, after changing color
as you require, just set it back like this:
image.at<Vec3b>(Point(x,y)) = color;
So, in full, something like this:
Mat image = img;
for(int y=0;y<img.rows;y++)
{
for(int x=0;x<img.cols;x++)
{
// get pixel
Vec3b & color = image.at<Vec3b>(y,x);
// ... do something to the color ....
color[0] = 13;
color[1] = 13;
color[2] = 13;
// set pixel
//image.at<Vec3b>(Point(x,y)) = color;
//if you copy value
}
}
You can use the REGEXP_LIKE
function as:
SELECT X
FROM myTable
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
Sample run:
SQL> SELECT X FROM SO;
X
--------------------
12c
123
abc
a12
SQL> SELECT X FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');
X
--------------------
123
SQL>
Also, note that there shouldn't be any space after =
:
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27
You could do what saurik of Cydia does, and write your code on a PC then build it on the iPhone itself (it is a Mac, technically!) after you jailbreak it. However, you don't get Interface Builder, so you're basically creating UIs in code by hand. It'd also be pretty tough to actually submit your app without a Mac.
Had the same problem and just want to add that AndroidManifest.xml also needs this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The easiest option is to make use of the Excel copy/paste.
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
This worked for me. Tested in FF, Chrome, IE11, IE10
.row {
width:99.99%;
}
I discovered this after a lot of experimentation.
In the initialisation of your activity:
setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View view) {
activity.openContextMenu(view);
return true; // avoid extra click events
}
});
setOnTouch(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent e){
switch(e.getAction & MotionEvent.ACTION_MASK){
// do drag/gesture processing.
}
// you MUST return false for ACTION_DOWN and ACTION_UP, for long click to work
// you can return true for ACTION_MOVEs that you consume.
// DOWN/UP are needed by the long click timer.
// if you want, you can consume the UP if you have made a drag - so that after
// a long drag, no long-click is generated.
return false;
}
});
setLongClickable(true);
You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
console.log(guest);_x000D_
});
_x000D_
Example:
renderPayments(noGuest) {
return Array(noGuest).fill(noGuest).map((guess, index) => {
return(
<View key={index}>
<View><TextInput /></View>
<View><TextInput /></View>
<View><TextInput /></View>
</View>
);
}
}
Then use it where you want it
render() {
return(
const { guest } = this.state;
...
{this.renderPayments(guest)}
);
}
Hope you got the idea.
If you want to understand this in simple Javascript check Array.prototype.fill()
All answers above contribute important info on the original question. However, there is a generalization that seems wrong.
It is possible to set width and height to at least one inline element (that I can think of) – the <img>
element.
Both accepted answers here and on this duplicate state that this is not possible but this doesn’t seem like a valid general rule.
Example:
img {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<img src="#" />
_x000D_
The img
has display: inline
, but its width
and height
were successfully set.
This might work for you:
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
If you include all files of *.js in directory example ("app/lib/*.js"):
example.js:
module.exports = function (example) { }
example-2.js:
module.exports = function (example2) { }
index.js:
module.exports = require('./app/lib');
CSV is a Comma Seperated File. Generally the delimiter is a comma, but I have seen many other characters used as delimiters. They are just not as frequently used.
As for advising you on what to use, we need to know your application. Is the file specific to your application/program, or does this need to work with other programs?
I tested all the cases in the latest Chrome, Firefox, Safari in 2019.
Response to Added:
You actually need 3 meta
tags to support Android, iPhone and Windows Phone
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
Your reader
variable is an iterable, by looping over it you retrieve the rows.
To make it skip one item before your loop, simply call next(reader, None)
and ignore the return value.
You can also simplify your code a little; use the opened files as context managers to have them closed automatically:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
reader = csv.reader(infile)
next(reader, None) # skip the headers
writer = csv.writer(outfile)
for row in reader:
# process each row
writer.writerow(row)
# no need to close, the files are closed automatically when you get to this point.
If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next()
to writer.writerow()
:
headers = next(reader, None) # returns the headers or `None` if the input is empty
if headers:
writer.writerow(headers)
rest-fb users (square image, bigger res.): Connection myFriends = fbClient.fetchConnection("me/friends", User.class, Parameter.with("fields", "public_profile,email,first_name,last_name,gender,picture.width(100).height(100)"));
I've been researching this very same problem and couldn't find a decent solution other than having the div with the image as background and the img tag inside of it with visibility none or something like this.
One thing I might add is that you should add a background-size: cover
to the div, so that your image fills the background by clipping it's excess.
This article (Why is window.showModalDialog deprecated? What to use instead?) seems to suggest that showModalDialog has been deprecated.
Things are going better, right now you can use SVG files.
marker = new google.maps.Marker({
position: {lat: 36.720426, lng: -4.412573},
map: map,
draggable: true,
icon: "img/tree.svg"
});
What role do they play when exiting an application in C#?
The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.
But what is the difference?
One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.
If you're using angularJS or some variant of the Q promise library, then you have a .all()
method that solves this exact problem.
var savePromises = [];
angular.forEach(models, function(model){
savePromises.push(
model.saveToServer()
)
});
$q.all(savePromises).then(
function success(results){...},
function failed(results){...}
);
see the full API:
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
I suppose the question is more like "What is linux's native GUI API".
In most cases X (aka X11) will be used for that: http://en.wikipedia.org/wiki/X_Window_System.
You can find the API documentation here
Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.
I received the same issue and the culprit was antivirus software.
EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...
The firstName and lastName fields are indexed, together and individually.
@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"}) // Columns indexed together
public class Employee{
@Id
private long id;
@Index // F_NAME column indexed
@Column(name="F_NAME")
private String firstName;
@Index // L_NAME column indexed
@Column(name="L_NAME")
private String lastName;
...
}
Remove quotes to work properly...
alter table goods add column id int(10) unsigned primary KEY AUTO_INCREMENT;
For me to solve this issue, I had to make sure I had the most current version of Ruby and the gems gem update --system
; then, I had to make sure that Xcode & the Command Line Tools were installed: xcode-select --install
.
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.
I'm surprised nobody mentioned partition
.
def substring_after(s, delim):
return s.partition(delim)[2]
IMHO, this solution is more readable than @arshajii's. Other than that, I think @arshajii's is the best for being the fastest -- it does not create any unnecessary copies/substrings.
Part 1 of your question:
var allChecked = true;
$("input.abc").each(function(index, element){
if(!element.checked){
allChecked = false;
return false;
}
});
EDIT:
The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.
I struggled a lot with something similar. Try the following:
If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.
You can use text classes:
.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white
use text classes in any tag where needed.
<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>
You can add your own classes or modify above classes as your requirement.
I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:
public function up() {
Schema::create('parent_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->timestamps();
});
ParentCategory::create(
[
'id' => 1,
'name' => 'Occasions',
],
);
}
This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8
First of all, Thanks to code author!
I found the below link while googling and it is very simple and works best. Would never fail unless SVG is deprecated.
https://codepen.io/moistpaint/pen/ywFDe/
There is some js loading error in the code here but its perfectly working on the codepen.io link provided.
var mapOptions = {_x000D_
zoom: 16,_x000D_
center: new google.maps.LatLng(-37.808846, 144.963435)_x000D_
};_x000D_
map = new google.maps.Map(document.getElementById('map-canvas'),_x000D_
mapOptions);_x000D_
_x000D_
_x000D_
var pinz = [_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807817,_x000D_
'lon' : 144.958377_x000D_
},_x000D_
'lable' : 2_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.807885,_x000D_
'lon' : 144.965415_x000D_
},_x000D_
'lable' : 42_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811377,_x000D_
'lon' : 144.956596_x000D_
},_x000D_
'lable' : 87_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.811293,_x000D_
'lon' : 144.962883_x000D_
},_x000D_
'lable' : 145_x000D_
},_x000D_
{_x000D_
'location':{_x000D_
'lat' : -37.808089,_x000D_
'lon' : 144.962089_x000D_
},_x000D_
'lable' : 999_x000D_
},_x000D_
];_x000D_
_x000D_
_x000D_
_x000D_
for(var i = 0; i <= pinz.length; i++){_x000D_
var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';_x000D_
_x000D_
_x000D_
var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);_x000D_
var marker = new google.maps.Marker({_x000D_
position: myLatLng,_x000D_
map: map,_x000D_
icon: image_x000D_
});_x000D_
}
_x000D_
html, body, #map-canvas {_x000D_
height: 100%;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}
_x000D_
<div id="map-canvas"></div>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>
_x000D_
You just need to uri-encode your SVG html and replace the one in the image variable after "data:image/svg+xml" in the for loop.
For uri encoding you can use uri-encoder-decoder
You can decode the existing svg code first to get a better understanding of what is written.
If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.
Confirm "Certificates" category is selected.
Remove expired Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab.
Here's Apple's answer.
Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.
AD Powershell module should be listed under installed Features. See image:
.
PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.
Example PHP file:
#!/usr/bin/env php
<?php
echo("Hello World!\n")
?>
How to run it:
$ chmod 755 hello.php # do this only once
$ ./hello.php
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
Attempt 2 was close to perfect. Just modify it slightly:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Multiple parameters can be given like below,
@RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
, @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
//logic
}
Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.
But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:
<parent>
<sibling></sibling>
<child></child>
</parent>
The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!
Now, how to style the sibling?
When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:
parent sibling { }
parent sibling:hover { }
parent:hover sibling { }
These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:
div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}
Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.
Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.
I've been struggling with this for 3 days now while attempting to connect to a local API running Laravel valet. I finally figured it out. In my case I had to drag and drop over the LaravelValetCASelfSigned.pem file from ~/.config/valet/CA/LaravelValetCASelfSigned.pem
After verifying the installing within the simulator I had to go to Settings > About > Certificate Trust Settings > and Enable the Laravel Valet VA Self Signed CN
Finally working!!!
With ES2017 async/await
support, this is how to POST
a JSON payload:
(async () => {_x000D_
const rawResponse = await fetch('https://httpbin.org/post', {_x000D_
method: 'POST',_x000D_
headers: {_x000D_
'Accept': 'application/json',_x000D_
'Content-Type': 'application/json'_x000D_
},_x000D_
body: JSON.stringify({a: 1, b: 'Textual content'})_x000D_
});_x000D_
const content = await rawResponse.json();_x000D_
_x000D_
console.log(content);_x000D_
})();
_x000D_
Can't use ES2017? See @vp_art's answer using promises
The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.
chrome devtools doesn't even show the JSON as part of the request
This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.
That code works fine - it is POSTing the JSON correctly, it just cannot be seen.
I'd expect to see the object I've sent back
that's not working because that is not the correct format for JSfiddle's echo.
The correct code is:
var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
For endpoints accepting JSON payloads, the original code is correct
From the designer, you can set the onClick
property of the listItem to a method defined with a single parameter. I have an example method defined below. The method getAdapterPosition will give you the index of the selected listItem.
public void exampleOnClickMethod(View view){
myRecyclerView.getChildViewHolder(view).getAdapterPosition());
}
For information on setting up a RecyclerView, see the documentation here: https://developer.android.com/guide/topics/ui/layout/recyclerview
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
# list of words
words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
"Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP",
"Protijayi","Paikpara","dipSouta","Shyambazaar",
"jayiProti", "North Calcutta", "Sovabazaar"]
#Method 1
A = [''.join(sorted(word)) for word in words]
dict ={}
for indexofsamewords,samewords in enumerate(A):
dict.setdefault(samewords, []).append(indexofsamewords)
print(dict)
#{'AOOPR': [0, 2, 5, 9, 11], 'ABTU': [1, 3, 4], 'Sadioptu': [6, 14], ' KPaaehiklry': [7], 'Taeggllnouy': [8], 'Leov': [10], 'Paiijorty': [12, 16], 'Paaaikpr': [13], 'Saaaabhmryz': [15], ' CNaachlortttu': [17], 'Saaaaborvz': [18]}
for index in dict.values():
print( [words[i] for i in index ] )
The Output :
['ROOPA', 'OOPAR', 'PAROO', 'AROOP', 'AOORP']
['TABU', 'BUTA', 'BUAT']
['Soudipta', 'dipSouta']
['Kheyali Park']
['Tollygaunge']
['Love']
['Protijayi', 'jayiProti']
['Paikpara']
['Shyambazaar']
['North Calcutta']
['Sovabazaar']
Here's a quick solution for most of the cases:
CSS:
.iframe-loading {
background:url(/img/loading.gif) center center no-repeat;
}
You can use an animated loading GIF if you want to,
HTML:
<div class="iframe-loading">
<iframe src="http://your_iframe_url_goes_here" onload="$('.iframe-loading').css('background-image', 'none');"></iframe>
</div>
Using the onload event you can remove the loading image after the source page is loaded inside your iframe.
If you are not using jQuery, just put an id into the div and replace this part of code:
$('.iframe-loading').css('background-image', 'none');
by something like this:
document.getElementById("myDivName").style.backgroundImage = "none";
All the best!
In general, methods that end in !
indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:
foo = "A STRING" # a string called foo
foo.downcase! # modifies foo itself
puts foo # prints modified foo
This will output:
a string
In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the !
and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !
:
foo = "A STRING" # a string called foo
bar = foo.downcase # doesn't modify foo; returns a modified string
puts foo # prints unchanged foo
puts bar # prints newly created bar
This outputs:
A STRING
a string
Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.
I found "npm config edit" to be more useful to update the entries for https-proxy, proxy, registry
I did something like this
There is a small bug in the above code (by the way Dave it was very helpful your post thank you)
In the part where we save the credentials it also needs the following code in order to work properly.
[self.keychainItem setObject:@"myCredentials" forKey:(__bridge id)(kSecAttrService)];
most probably is because the second time we try to (re-)sign in with the same credentials it finds them already assigned in the keychain items and the app crashes. with the above code it works like a charm.
select sum(qty), name
from (
select count(m.owner_id) as qty, o.name
from transport t,owner o,motorbike m
where t.type='motobike' and o.owner_id=m.owner_id
and t.type_id=m.motorbike_id
group by m.owner_id
union all
select count(c.owner_id) as qty, o.name,
from transport t,owner o,car c
where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
group by c.owner_id
) t
group by name
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
check the stack size per thread with ulimit, in my case Redhat Linux 2.6:
ulimit -a
...
stack size (kbytes, -s) 10240
Each of your threads will get this amount of memory (10MB) assigned for it's stack. With a 32bit program and a maximum address space of 4GB, that is a maximum of only 4096MB / 10MB = 409 threads !!! Minus program code, minus heap-space will probably lead to an observed max. of 300 threads.
You should be able to raise this by compiling and running on 64bit or setting ulimit -s 8192 or even ulimit -s 4096. But if this is advisable is another discussion...
I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".
Delete it with git tag -d <tagname>
and then recreate it on the correct commit.
This should work if the date format is consistent:
select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table
In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char *
or const char *
.
However, the difference is that if the pointer is const char *
then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char *
then it does not.
If you are getting back a sun.awt.image.ToolkitImage
, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage
.
So instead of your last line of code where you are casting you would just do:
BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();
This feature if available in Boltons which is a very handy library to have for most projects.
>>> bytes2human(128991)
'126K'
>>> bytes2human(100001221)
'95M'
>>> bytes2human(0, 2)
'0.00B'
If you want to print an arraylist with integer numbers, as an example you can use below code.
class Test{
public static void main(String[] args){
ArrayList<Integer> arraylist = new ArrayList<Integer>();
for(int i=0; i<=10; i++){
arraylist .add(i);
}
for (Integer n : arraylist ){
System.out.println(n);
}
}
}
The output is above code:
0
1
2
3
4
5
6
7
8
9
10
In C/C++, we can do the following, as you mentioned
for(int k = 1; k <= c ; k++)
for(int k = 1; k <= c ; k +=2)
We know that here k
starts with 1 and go till (predefined) c
with step value 1 or 2 gradually. We can do this in Python by following,
for k in range(1,c+1):
for k in range(1,c+1,2):
Check this for more in depth.
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
swal({_x000D_
title: "Are you sure?",_x000D_
text: "You will not be able to recover this imaginary file!",_x000D_
type: "warning",_x000D_
showCancelButton: true,_x000D_
confirmButtonColor: '#DD6B55',_x000D_
confirmButtonText: 'Yes, I am sure!',_x000D_
cancelButtonText: "No, cancel it!",_x000D_
closeOnConfirm: false,_x000D_
closeOnCancel: false_x000D_
},_x000D_
function(isConfirm){_x000D_
_x000D_
if (isConfirm.value){_x000D_
swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
} else {_x000D_
swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
e.preventDefault();_x000D_
}_x000D_
});_x000D_
};
_x000D_
Although the accepted answer works, you should really be using python's json
module:
import json
score=[1,2,3,4,5]
with open("file.json", 'w') as f:
# indent=2 is not needed but makes the file human-readable
json.dump(score, f, indent=2)
with open("file.json", 'r') as f:
score = json.load(f)
print(score)
Advantages:
json
is a widely adopted and standardized data format, so non-python programs can easily read and understand the json filesjson
files are human-readablejson
file (as long as all the contents are serializable).Disadvantages:
hdf5
is for).When to use json
vs pickle
:
pickle
pickle
.json
json
Common use cases:
node.js
uses a package.json
file to track project details, dependencies, scripts, etc ...)REST
APIs use json
to transmit and receive datacsv
, xml
or yaml
filesHow to get rid of a header(first row) and an index(first column).
To write to CSV file:
df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)
To read from CSV file:
df = pandas.read_csv('your_array.csv')
a = df.values
If you want to read a CSV file that doesn't contain a header, pass additional parameter header
:
df = pandas.read_csv('your_array.csv', header=None)
I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar
.
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
See this example:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
Because doA()
does not modify the global total the output is 1 not 11.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
With c++14 you can do this:
std::sort(numbers.begin(), numbers.end(), std::greater<>());
Quick note if you don't have an .aspx in your project (i.e. its XBAP) but you still need to debug using IE, just add a htm page to your project and right click on that to set the default. It's hacky, but it works :P
They are:
Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.
but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:
/api/members?metaonly=true
/api/members?includeitems=0
or something similar...
In C and C++, the &&
and ||
operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to &&
is false, or the first to ||
is true, the rest will not be evaluated.
The code you posted is safe, though I question why you'd include an empty else
block.
Here is a solution for transposing a list of lists that is not necessarily square:
maxCol = len(l[0])
for row in l:
rowLength = len(row)
if rowLength > maxCol:
maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
lTrans.append([])
for row in l:
if colIndex < len(row):
lTrans[colIndex].append(row[colIndex])
No need to add an extra variable to keep track of this. Just use the UIScrollView
's panGestureRecognizer
property like this. Unfortunately, this works only if the velocity isn't 0:
CGFloat yVelocity = [scrollView.panGestureRecognizer velocityInView:scrollView].y;
if (yVelocity < 0) {
NSLog(@"Up");
} else if (yVelocity > 0) {
NSLog(@"Down");
} else {
NSLog(@"Can't determine direction as velocity is 0");
}
You can use a combination of x and y components to detect up, down, left and right.
create model.ts in your component directory as below
export module DataModel {
export interface DataObjectName {
propertyName: type;
}
export interface DataObjectAnother {
propertyName: type;
}
}
then in your component import above as, import {DataModel} from './model';
export class YourComponent {
public DataObject: DataModel.DataObjectName;
}
your DataObject should have all the properties from DataObjectName.
put a int
infront of the all the voxelCoord
's...Like this below :
patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]
You can try this-
mysql> select @@datadir;
PS- It works on every platform.
@cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!
problem:
if you use an url like this: www.somesite.it/?p=1500
in some case you get an internal server error (500),
although in web browser this www.somesite.it/?p=1500
perfectly work.
solution: you have to move out parameters, working code is:
using System.Net;
//...
using (WebClient client = new WebClient ())
{
client.QueryString.Add("p", "1500"); //add parameters
string htmlCode = client.DownloadString("www.somesite.it");
//...
}
You can either use
SELECT * FROM v$version;
or
SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );
if you don't want to parse the output of v$version.
public boolean getcheckboxvalue(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
return webElement.isSelected();
}
const oldFunction = params => {
// do something
};
const clonedFunction = (...args) => oldFunction(...args);
You can’t use \s
in Java to match white space on its own native character set, because Java doesn’t support the Unicode white space property — even though doing so is strictly required to meet UTS#18’s RL1.2! What it does have is not standards-conforming, alas.
Unicode defines 26 code points as \p{White_Space}
: 20 of them are various sorts of \pZ
GeneralCategory=Separator, and the remaining 6 are \p{Cc}
GeneralCategory=Control.
White space is a pretty stable property, and those same ones have been around virtually forever. Even so, Java has no property that conforms to The Unicode Standard for these, so you instead have to use code like this:
String whitespace_chars = "" /* dummy empty string for homogeneity */
+ "\\u0009" // CHARACTER TABULATION
+ "\\u000A" // LINE FEED (LF)
+ "\\u000B" // LINE TABULATION
+ "\\u000C" // FORM FEED (FF)
+ "\\u000D" // CARRIAGE RETURN (CR)
+ "\\u0020" // SPACE
+ "\\u0085" // NEXT LINE (NEL)
+ "\\u00A0" // NO-BREAK SPACE
+ "\\u1680" // OGHAM SPACE MARK
+ "\\u180E" // MONGOLIAN VOWEL SEPARATOR
+ "\\u2000" // EN QUAD
+ "\\u2001" // EM QUAD
+ "\\u2002" // EN SPACE
+ "\\u2003" // EM SPACE
+ "\\u2004" // THREE-PER-EM SPACE
+ "\\u2005" // FOUR-PER-EM SPACE
+ "\\u2006" // SIX-PER-EM SPACE
+ "\\u2007" // FIGURE SPACE
+ "\\u2008" // PUNCTUATION SPACE
+ "\\u2009" // THIN SPACE
+ "\\u200A" // HAIR SPACE
+ "\\u2028" // LINE SEPARATOR
+ "\\u2029" // PARAGRAPH SEPARATOR
+ "\\u202F" // NARROW NO-BREAK SPACE
+ "\\u205F" // MEDIUM MATHEMATICAL SPACE
+ "\\u3000" // IDEOGRAPHIC SPACE
;
/* A \s that actually works for Java’s native character set: Unicode */
String whitespace_charclass = "[" + whitespace_chars + "]";
/* A \S that actually works for Java’s native character set: Unicode */
String not_whitespace_charclass = "[^" + whitespace_chars + "]";
Now you can use whitespace_charclass + "+"
as the pattern in your replaceAll
.
Sorry ’bout all that. Java’s regexes just don’t work very well on its own native character set, and so you really have to jump through exotic hoops to make them work.
And if you think white space is bad, you should see what you have to do to get \w
and \b
to finally behave properly!
Yes, it’s possible, and yes, it’s a mindnumbing mess. That’s being charitable, even. The easiest way to get a standards-comforming regex library for Java is to JNI over to ICU’s stuff. That’s what Google does for Android, because OraSun’s doesn’t measure up.
If you don’t want to do that but still want to stick with Java, I have a front-end regex rewriting library I wrote that “fixes” Java’s patterns, at least to get them conform to the requirements of RL1.2a in UTS#18, Unicode Regular Expressions.
The order in which libraries are linked DOES matter if the libraries depend on each other. In general, if library A
depends on library B
, then libA
MUST appear before libB
in the linker flags.
For example:
// B.h
#ifndef B_H
#define B_H
struct B {
B(int);
int x;
};
#endif
// B.cpp
#include "B.h"
B::B(int xx) : x(xx) {}
// A.h
#include "B.h"
struct A {
A(int x);
B b;
};
// A.cpp
#include "A.h"
A::A(int x) : b(x) {}
// main.cpp
#include "A.h"
int main() {
A a(5);
return 0;
};
Create the libraries:
$ g++ -c A.cpp
$ g++ -c B.cpp
$ ar rvs libA.a A.o
ar: creating libA.a
a - A.o
$ ar rvs libB.a B.o
ar: creating libB.a
a - B.o
Compile:
$ g++ main.cpp -L. -lB -lA
./libA.a(A.o): In function `A::A(int)':
A.cpp:(.text+0x1c): undefined reference to `B::B(int)'
collect2: error: ld returned 1 exit status
$ g++ main.cpp -L. -lA -lB
$ ./a.out
So to repeat again, the order DOES matter!
Try this:
from tkinter import *
import os
import sys
root = Tk()
root.iconbitmap(os.path.join(sys.path[0], '<your-ico-file>'))
root.mainloop()
Note: replace <your-ico-file>
with the name of the ico file you are using otherwise it won't work.
I have tried this in Python 3. It worked.
No, it is not possible. What type should the dereferenced value have?
there is some change since the 0.16 so here how i did,
import in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
then use
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
If you have HTML like this, for example:
<select id='myselect'>
<option value='1'>A</option>
<option value='2'>B</option>
<option value='3'>C</option>
<option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>
All you have to do is bind a function to the change
event of the select, and do what you need there:
<script type='text/javascript'>
$(function() {
$('#myselect').change(function() {
// if changed to, for example, the last option, then
// $(this).find('option:selected').text() == D
// $(this).val() == 4
// get whatever value you want into a variable
var x = $(this).val();
// and update the hidden input's value
$('#myhidden').val(x);
});
});
</script>
All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.
I wouldn't worry about it. Don't put it on your own server, it sounds like this is an issue with Google, but as good as it gets. Putting the file on your own server will create many new problems.
They probably need the file to get called every time rather than getting it from the client's cache, since that way you wouldn't count the visits.
If you have a problem to feel fine with that, run the Google insights URL on Google insights itself, have a laugh, relax and get on with your work.
list multiplication works.
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"
With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.
Try this one on for size.
private static void addSoftwareLibrary(File file) throws Exception {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
method.setAccessible(true);
method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}
This edits the system class loader to include the given library jar. It is pretty ugly, but it works.
You can use std::find
to get an iterator to a value:
#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
myVector.erase(position);
You get a recursion error because your attempt to access the self.__dict__
attribute inside __getattribute__
invokes your __getattribute__
again. If you use object
's __getattribute__
instead, it works:
class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self,name):
if name=='test':
return 0.
else:
return object.__getattribute__(self, name)
This works because object
(in this example) is the base class. By calling the base version of __getattribute__
you avoid the recursive hell you were in before.
Ipython output with code in foo.py:
In [1]: from foo import *
In [2]: d = D()
In [3]: d.test
Out[3]: 0.0
In [4]: d.test2
Out[4]: 21
Update:
There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.
It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.
Here's the fiddle: link.
What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>
s with class="cat1"
or class="cat2"
.
I also mark the links with a simple .toggler
class. It's not good practice to have onclick
attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.
$(".toggler").click(function(e){
// you handle the event here
});
With this format, you are binding an event handler to the click
event of links with class toggler
. In my code, I add a data-prod-cat
attribute to the toggler
links to specify which product rows they should control. (The reason for my using a data-*
attribute is explained here. You can Google 'html5 data attributes' for more information.)
In the event handler, I do this:
$('.cat'+$(this).attr('data-prod-cat')).toggle();
With this code, I'm actually trying to create a selector like $('.cat1')
so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat')
this to access the data-prod-cat
attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible
like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggle
s the visibility of the specified element(s).
I hope this was explanatory enough.
def extended_string (word, length) :
extra_long_word = word * (length//len(word) + 1)
required_string = extra_long_word[:length]
return required_string
print(extended_string("abc", 7))
One more thing you should pay attention to when selecting columns from N-D array using a list like this:
data[:,:,[1,9]]
If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:
print data.shape # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape # gives [2,20] instead of [20,2]!!
The basic difference is, like you stated, generating GUI events from the BackgroundWorker
. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.
linux: shutdown() causes listener thread select() to awake and produce error. shutdown(); close(); will lead to endless wait.
winsock: vice versa - shutdown() has no effect, while close() is successfully catched.
I had the exact same problem, found that I was missing
<mdb>
<resource-adapter-ref resource-adapter-name="hornetq-ra"/>
<bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>
</mdb>
under
<subsystem xmlns="urn:jboss:domain:ejb3:1.2">
in standalone/configuration/standalone.xml
Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick
Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax
The Android SDK can tell you this just fine:
getResources().getConfiguration().orientation
We use a combination of the processor id number (ProcessorID
) from Win32_processor
and the universally unique identifier (UUID
) from Win32_ComputerSystemProduct
:
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
processorId = mo["ProcessorID"] as string;
}
mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
systemId = mo["UUID"] as string;
}
var compIdStr = $"{processorId}{systemId}";
Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor"
) and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"
), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:
Therefore, it is worth considering this situation.
Also keep in mind that the ProcessorID
number may be the same on different computers.
Just cd
in the directory where you have installed git-credential-winstore. If you don't know where, just run this in Git Bash:
cat ~/.gitconfig
It should print something looking like:
[credential]
helper = !'C:\\ProgramFile\\GitCredStore\\git-credential-winstore.exe'
In this case, you repository is C:\ProgramFile\GitCredStore. Once you are inside this folder using Git Bash or the Windows command, just type:
git-credential-winstore.exe erase
host=github.com
protocol=https
Don't forget to press Enter twice after protocol=https
.
There are two ways to iterate an Enum
:
1. var values = Enum.GetValues(typeof(myenum))
2. var values = Enum.GetNames(typeof(myenum))
The first will give you values in form on an array of **object
**s, and the second will give you values in form of an array of **String
**s.
Use it in a foreach
loop as below:
foreach(var value in values)
{
// Do operations here
}
You probably want to read up on slice. Your code will look something like this:
$("a").slice(0,20)
TL;DR
Use Promise.all
for the parallel function calls, the answer behaviors not correctly when the error occurs.
First, execute all the asynchronous calls at once and obtain all the Promise
objects. Second, use await
on the Promise
objects. This way, while you wait for the first Promise
to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:
// Begin first call and store promise without waiting
const someResult = someCall();
// Begin second call and store promise without waiting
const anotherResult = anotherCall();
// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];
// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise
JSbin example: http://jsbin.com/xerifanima/edit?js,console
Caveat: It doesn't matter if the await
calls are on the same line or on different lines, so long as the first await
call happens after all of the asynchronous calls. See JohnnyHK's comment.
Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed.
I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()])
, check the following code snippet
const correctAsync500ms = () => {_x000D_
return new Promise(resolve => {_x000D_
setTimeout(resolve, 500, 'correct500msResult');_x000D_
});_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
return new Promise(resolve => {_x000D_
setTimeout(resolve, 100, 'correct100msResult');_x000D_
});_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
return new Promise((resolve, reject) => {_x000D_
setTimeout(reject, 100, 'reject100msError');_x000D_
});_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
const label = 'test async functions in array';_x000D_
try {_x000D_
console.time(label);_x000D_
const p1 = fun1();_x000D_
const p2 = fun2();_x000D_
const result = [await p1, await p2];_x000D_
console.timeEnd(label);_x000D_
} catch (e) {_x000D_
console.error('error is', e);_x000D_
console.timeEnd(label);_x000D_
}_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
const label = 'test async functions with Promise.all';_x000D_
try {_x000D_
console.time(label);_x000D_
let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
console.timeEnd(label);_x000D_
} catch (e) {_x000D_
console.error('error is', e);_x000D_
console.timeEnd(label);_x000D_
}_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
console.group('async functions without error');_x000D_
console.log('async functions without error: start')_x000D_
await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
console.groupEnd();_x000D_
_x000D_
console.group('async functions with error');_x000D_
console.log('async functions with error: start')_x000D_
await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
console.groupEnd();_x000D_
})();
_x000D_
Just an update to the Java 8 version
public Map<String, List<String>> splitQuery(URL url) {
if (Strings.isNullOrEmpty(url.getQuery())) {
return Collections.emptyMap();
}
return Arrays.stream(url.getQuery().split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, **Collectors**.mapping(Map.Entry::getValue, **Collectors**.toList())));
}
mapping and toList() methods have to be used with Collectors which was not mentioned in the top answer. Otherwise it would throw compilation error in IDE
Use smaller h
// 24 hrs
H:i
// output 14:20
// 12 hrs
h:i
// output 2:20
Finally I found the solution ... It's very easy
Go to the LAN settings (In Chrome : Tools -> Options -> Under the hood -> Change Proxy setting -> LAN Setting)
There will be a checkbox for "Bypass proxy server for local address"
Tick the checkbox.
Done!
On Mac/Apple: Chrome uses system preferences for localhost exclusion:
Go to System Preferences -> Network -> advanced -> Proxy settings
Add 'localhost' at the bottom where it says: 'ignore proxy settings for these hosts and domains' (Exceptions are separated by a comma)
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
In FirstActivity:
Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);
In SecondActivity
In onCreate()
String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");
String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();
You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:
vi test_script.sh
Add the following to your file:
#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>
cd <base directory for your put file>
lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT
And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq
.Then make your script executable chmod +x test_script.sh
and execute it ./test_script.sh
.
No.
If the user is sophisticated or determined enough to:
then they are probably sophisticated or determined enough to:
So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
A few others have posted answers. There are some obvious problems, like it returns false
when the Regex passes, and the ^
and $
operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).
Besides that, the issue is just a typo.
Change this...
var reWhiteSpace = new RegExp("/^\s+$/");
To this...
var reWhiteSpace = new RegExp("\\s+");
When using a regex within RegExp()
, you must do the two following things...
/
brackets.\\s
in place of \s
, etc.Full working demo from source code....
$(document).ready(function(e) { function hasWhiteSpace(s) {
var reWhiteSpace = new RegExp("\\s+");
// Check for white space
if (reWhiteSpace.test(s)) {
//alert("Please Check Your Fields For Spaces");
return 'true';
}
return 'false';
}
$('#whitespace1').html(hasWhiteSpace(' '));
$('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
More compact version working with spaces and newlines in the file name:
find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;
Isnull() syntax is built in for this kind of thing.
declare @Int int = null;
declare @Values table ( id int, def varchar(8) )
insert into @Values values (8, 'I am 8');
-- fails
select *
from @Values
where id = @Int
-- works fine
select *
from @Values
where id = isnull(@Int, 8);
For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.
declare @Int int = null;
declare @Values table ( id int, def varchar(16) )
insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');
select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')
This is the simplest solution to solve horisontal scrolling in Safari.
html, body {
position:relative;
overflow-x:hidden;
}
So how do we copy this arr?
let arr = [1,2,3,4,5];
let arrCopy = [...arr];
let arrCopy = arr.slice();
let arrCopy = [].concat(arr);
Passing one varible to another on Compound values such as Object/Array behave difrently. Using asign operator on copand values we pass reference to an object. This is why the value of both arrays are changing when removing/adding arr elements.
arrCopy[1] = 'adding new value this way will unreference';
When you assign a new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array.
There are few differences between Python and IPython but they are only the interpretation of few syntax like the few mentioned by @Ryan Chase but deep inside the true flavor of Python is maintained even in the Ipython.
The best part of the IPython is the IPython notebook. You can put all your work into a notebook like script, image files, etc. But with base Python, you can only make the script in a file and execute it.
At start, you need to understand that the IPython is developed with the intention of supporting rich media and Python script in a single integrated container.
Talking in terms of performance :
TL;DR
Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.
Sorted by performance:
Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.
In theory
Using a soft like bytecode viewer we can translate each operator into bytecode.
In the context of:
package foo;
public class Benchmark
{
public static final Object a = new A();
public static final Object b = new B();
...
}
JAVA:
b instanceof A;
Bytecode:
getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A
JAVA:
A.class.isInstance(b);
Bytecode:
ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);
JAVA:
A.class.isAssignableFrom(b.getClass());
Bytecode:
ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);
Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.
The benchmark
Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):
class A {}
class B extends A {}
public class Benchmark {
public static final Object a = new A();
public static final Object b = new B();
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testInstanceOf()
{
return b instanceof A;
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testIsInstance()
{
return A.class.isInstance(b);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public boolean testIsAssignableFrom()
{
return A.class.isAssignableFrom(b.getClass());
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(TestPerf2.class.getSimpleName())
.warmupIterations(20)
.measurementIterations(2000)
.forks(1)
.build();
new Runner(opt).run();
}
}
Gave the following results (score is a number of operations in a time unit, so the higher the score the better):
Benchmark Mode Cnt Score Error Units
Benchmark.testIsInstance thrpt 2000 373,061 ± 0,115 ops/us
Benchmark.testInstanceOf thrpt 2000 371,047 ± 0,131 ops/us
Benchmark.testIsAssignableFrom thrpt 2000 363,648 ± 0,289 ops/us
Warning
instanceof
in the context of your code might get optimized more easily than an isInstance
for example... To give you an example, take the following loop:
class A{}
class B extends A{}
A b = new B();
boolean execute(){
return A.class.isAssignableFrom(b.getClass());
// return A.class.isInstance(b);
// return b instanceof A;
}
// Warmup the code
for (int i = 0; i < 100; ++i)
execute();
// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
execute();
}
final long elapsed = System.nanoTime() - start;
Thanks to the JIT, the code is optimized at some point and we get:
Note
Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details
Related questions
You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.
In addition to all the great information on optimising your application on the server side I'd say you should take a look at YSlow. It's a superb resource for improving site performance on the client side.
This applies to all sites, not just ASP.NET MVC.
Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:
int x = *(int*)"abcd";
Or a bit more specific:
int x = *(int32_t*)"abcd";
One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):
int x = ((union {char s[5]; int number;}){"abcd"}).number;
/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");
Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).
Try this query
select
*,
Days = datediff(dd,0,DateDif),
Hours = datepart(hour,DateDif),
Minutes = datepart(minute,DateDif),
Seconds = datepart(second,DateDif),
MS = datepart(ms,DateDif)
from
(select
DateDif = EndDate-StartDate,
aa.*
from
( -- Test Data
Select
StartDate = convert(datetime,'20090213 02:44:37.923'),
EndDate = convert(datetime,'20090715 13:24:45.837')) aa
) a
Output
DateDif StartDate EndDate Days Hours Minutes Seconds MS
----------------------- ----------------------- ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913 2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 152 10 40 7 913
(1 row(s) affected)
If the id
column has no default value, but has NOT NULL
constraint, then you have to provide a value yourself
INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())
I am a bit lazy, so I like simple things:
let users = await Users.find({}, null, {limit: 50});
The one-liner to disable SSH password authentication:
sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate
in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault()
. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
If you care about specific moments, specific points on the timeline, do not use LocalDate
. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate
.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Call toString
to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter
class.
Though now supplanted by java.time, you can use the similar LocalDate
class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Just for a more animated and cute solution:
$(window).scroll(function(){
$("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});
And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb
Update: and a non-animated jQuery solution:
$(window).scroll(function(){
$("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});
Using Lambda:
new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
.setTitle(getString(R.string.info))
.setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
moveTaskToBack(true);
finish();
})
.setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
})
.show();
You also need to set level language to support java 8 in your gradle.build:
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
$total = count($_FILES['txt_gallery']['name']);
$filename_arr = [];
$filename_arr1 = [];
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
$newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$filename_arr[] = $newFilePath;
$filename_arr1[] = $newFilePath1;
}
}
}
$file_names = implode(',', $filename_arr1);
var_dump($file_names); exit;
While this previous answer might be the reason, this snipped worked for me as a solution (in Ubuntu 14.04
):
First remove the package from the package manager:
# apt-get remove python-pip
And then install the latest version by side:
# easy_install pip
(thanks to @Aufziehvogel, @JunchaoGu)
You can try: Using the --authenticationDatabase flag helps.
mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"
You can do one of two things:
^\s*$
; a match means the string is "empty"
^
, $
are the beginning and end of string anchors respectively\s
is a whitespace character*
is zero-or-more repetition of\S
; an occurrence means the string is NOT "empty"
\S
is the negated version of \s
(note the case difference)\S
therefore matches any non-whitespace characterRegexOptions.ECMAScript
, \s
matches things like ellipsis …
At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.
You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.
You can add the TimeSpan
to a DateTime
, for example:
TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");
Demo: http://ideone.com/veJ6tT
04:00 PM
Pass param rot=0
to rotate the xticks:
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()
yields plot:
import datetime
def age(date_of_birth):
if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
return datetime.date.today().year - date_of_birth.year - 1
else:
return datetime.date.today().year - date_of_birth.year
In your case:
import datetime
# your model
def age(self):
if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
return datetime.date.today().year - self.birthdate.year - 1
else:
return datetime.date.today().year - self.birthdate.year
In my case this is incorrect/improper dependency
Markers > Problems is highlighting
spring/.gradle/cache/httpcomponents.......pom is not valid archive
I removed
compile group: 'org.apache.httpcomponents', name: 'httpcomponents-client', version: '4.5.6', ext: 'pom'
changed to
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.6'