Follow the below steps to sign the application in the android studio:-
First Go to Build->Generate Signed APK
Then Once you click on the Generate Signed APK then there is info dialog message appear.
Click on the Create New
button if you don't have any keystore file. If you have click on the Choose Existing
.
Once you click on the Create New
button then now dialog box appear where you need to enter the keystore file info, other signing authority details.
Once you fill complete details then click on the Ok
button then it redirect to this dialog.
Click on the Next button then check mark on the Run ProGuard
and click on the finish. It generate the signed APK.
The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.
Then you can use either _.size(object)
or _.keys(object).length
For your obj.Data
, you could test this with:
console.log( _.size(obj.Data) );
or:
console.log( _.keys(obj.Data).length );
Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)
Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:
function ObjectLength( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
You can test this with:
console.log( ObjectLength(obj.Data) );
That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:
function ObjectLength_Modern( object ) {
return Object.keys(object).length;
}
function ObjectLength_Legacy( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}
var ObjectLength =
Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;
and as before, test it with:
console.log( ObjectLength(obj.Data) );
This code uses Object.keys(object).length
in modern browsers and falls back to counting in a loop for old browsers.
But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.
I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.
Thanks to Barmar for suggesting Object.keys
for newer browsers in his answer.
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
as @MikeM pointed out.
select exists(select 1 from contact where id=12)
with index on contact, it can usually reduce time cost to 1 ms.
CREATE INDEX index_contact on contact(id);
Open cmd type adb shell
then press enter.
Type ls
to view files list.
The secrets
module is new in Python 3.6. This is better than the random
module for cryptography or security uses.
To randomly print an integer in the inclusive range 0-9:
from secrets import randbelow
print(randbelow(10))
For details, see PEP 506.
A soft reset will keep your local changes.
Source: https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree
Edit
About git revert
: This command creates a new commit which will undo other commits. E.g. if you have a commit which adds a new file, git revert
could be used to make a commit which will delete the new file.
About applying a soft reset: Assume you have the commits A
to E
(A---B---C---D---E
) and you like to delete the last commit (E
). Then you can do a soft reset to commit D
. With a soft reset commit E
will be deleted from git but the local changes will be kept. There are more examples in the git reset documentation.
Very simple way (Tested) :-
PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();
Add bellow line in build.gradle :-
compile 'com.commit451:PhotoView:1.2.4'
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
Here is just another option you couold apply for ASP NET MVC.
Normally you shoud use BaseController
class for each Controller
class.
So inside of it's constructor method do following.
public class BaseController : Controller
{
public BaseController()
{
// get the previous url and store it with view model
ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
}
}
And now in ANY view you can do like
<button class="btn btn-success mr-auto" onclick=" window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>
Enjoy!
Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone
returns IANA timezone name by definition, which is in English.
If you want the timezone's name in current user's language, you can parse it from Date
's string representation like so:
function getTimezoneName() {_x000D_
const today = new Date();_x000D_
const short = today.toLocaleDateString(undefined);_x000D_
const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
// Trying to remove date from the string in a locale-agnostic way_x000D_
const shortIndex = full.indexOf(short);_x000D_
if (shortIndex >= 0) {_x000D_
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
_x000D_
// by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
// trim it from both sides_x000D_
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
} else {_x000D_
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
return full;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
Tested in Chrome and Firefox.
Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00
) instead of a name. But I think it's still readable as a fallback.
P.S. Won't work in IE11, just as the Intl...
solution.
You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async
@await Html.PartialAsync("_LoginPartial")
or
@{await Html.RenderPartialAsync("PartialName");}
or if you are using .net core 2.1 > you can just use:
<partial name="Shared/_ProductPartial.cshtml"
for="Product" />
\f
is used for page break.
You cannot see any effect in the console. But when you use this character constant in your file then you can see the difference.
Other example is that if you can redirect your output to a file then you don't have to write a file or use file handling.
For ex:
Write this code in c++
void main()
{
clrscr();
cout<<"helloooooo" ;
cout<<"\f";
cout<<"hiiiii" ;
}
and when you compile this it generate an exe(for ex. abc.exe
)
then you can redirect your output to a file using this:
abc > xyz.doc
then open the file xyz.doc
you can see the actual page break between hellooo and hiiii....
Function matmul (since numpy 1.10.1) works fine for both types and return result as a numpy matrix class:
import numpy as np
A = np.mat('1 2 3; 4 5 6; 7 8 9; 10 11 12')
B = np.array(np.mat('1 1 1 1; 1 1 1 1; 1 1 1 1'))
print (A, type(A))
print (B, type(B))
C = np.matmul(A, B)
print (C, type(C))
Output:
(matrix([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
(array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]), <type 'numpy.ndarray'>)
(matrix([[ 6, 6, 6, 6],
[15, 15, 15, 15],
[24, 24, 24, 24],
[33, 33, 33, 33]]), <class 'numpy.matrixlib.defmatrix.matrix'>)
Since python 3.5 as mentioned early you also can use a new matrix multiplication operator @
like
C = A @ B
and get the same result as above.
Here's a Python version:
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
Fatal Error gave a straightforward possibility: source your second script! if you're worried that this second script may alter some of your precious variables, you can always source it in a subshell:
( . ./test2.sh )
The parentheses will make the source happen in a subshell, so that the parent shell will not see the modifications test2.sh
could perform.
There's another possibility that should definitely be referenced here: use set -a
.
From the POSIX set
reference:
-a
: When this option is on, the export attribute shall be set for each variable to which an assignment is performed; see the Base Definitions volume of IEEE Std 1003.1-2001, Section 4.21, Variable Assignment. If the assignment precedes a utility name in a command, the export attribute shall not persist in the current execution environment after the utility completes, with the exception that preceding one of the special built-in utilities causes the export attribute to persist after the built-in has completed. If the assignment does not precede a utility name in the command, or if the assignment is a result of the operation of the getopts or read utilities, the export attribute shall persist until the variable is unset.
From the Bash Manual:
-a
: Mark variables and function which are modified or created for export to the environment of subsequent commands.
So in your case:
set -a
TESTVARIABLE=hellohelloheloo
# ...
# Here put all the variables that will be marked for export
# and that will be available from within test2 (and all other commands).
# If test2 modifies the variables, the modifications will never be
# seen in the present script!
set +a
./test2.sh
# Here, even if test2 modifies TESTVARIABLE, you'll still have
# TESTVARIABLE=hellohelloheloo
Observe that the specs only specify that with set -a
the variable is marked for export. That is:
set -a
a=b
set +a
a=c
bash -c 'echo "$a"'
will echo c
and not an empty line nor b
(that is, set +a
doesn't unmark for export, nor does it “save” the value of the assignment only for the exported environment). This is, of course, the most natural behavior.
Conclusion: using set -a
/set +a
can be less tedious than exporting manually all the variables. It is superior to sourcing the second script, as it will work for any command, not only the ones written in the same shell language.
Try to cast it as a DATE
SELECT CAST(orders.date_purchased AS DATE) AS DATE_PURCHASED
Your layout in xml probably already has a layout_margin(Left|Right|etc) attribute in it, which means you need to access the object generated by that xml and modify it.
I found this solution to be very simple:
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mTextView
.getLayoutParams();
mlp.setMargins(adjustmentPxs, 0, 0, 0);
break;
Get the LayoutParams instance of your textview, downcast it to MarginLayoutParams, and use the setMargins method to set the margins.
For me, I defined column type as BIT (e.g. "boolean")
When I tried to set column value "1" via UI (Workbench), I was getting a "Data too long for column" error.
Turns out that there is a special syntax for setting BIT values, which is:
b'1'
VS 2012 applications cannot be run under Windows XP.
See this VC++ blog on why and how to make it work.
It seems to be supported/possible from Feb 2013. See noelicus answer below on how to.
Here is how you can create a rounded rectangle with SVG Path:
<path d="M100,100 h200 a20,20 0 0 1 20,20 v200 a20,20 0 0 1 -20,20 h-200 a20,20 0 0 1 -20,-20 v-200 a20,20 0 0 1 20,-20 z" />
Explanation
m100,100: move to point(100,100)
h200: draw a 200px horizontal line from where we are
a20,20 0 0 1 20,20: draw an arc with 20px X radius, 20px Y radius, clockwise, to a point with 20px difference in X and Y axis
v200: draw a 200px vertical line from where we are
a20,20 0 0 1 -20,20: draw an arc with 20px X and Y radius, clockwise, to a point with -20px difference in X and 20px difference in Y axis
h-200: draw a -200px horizontal line from where we are
a20,20 0 0 1 -20,-20: draw an arc with 20px X and Y radius, clockwise, to a point with -20px difference in X and -20px difference in Y axis
v-200: draw a -200px vertical line from where we are
a20,20 0 0 1 20,-20: draw an arc with 20px X and Y radius, clockwise, to a point with 20px difference in X and -20px difference in Y axis
z: close the path
<svg width="440" height="440">_x000D_
<path d="M100,100 h200 a20,20 0 0 1 20,20 v200 a20,20 0 0 1 -20,20 h-200 a20,20 0 0 1 -20,-20 v-200 a20,20 0 0 1 20,-20 z" fill="none" stroke="black" stroke-width="3" />_x000D_
</svg>
_x000D_
Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1
Try to use appendChild method:
select.appendChild(option);
The import line should be:
import React, { Component } from 'react';
Note the uppercase R for React.
You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.
CREATE VIEW MyView
AS
WITH MyVars (SomeVar, Var2)
AS (
SELECT
'something' AS 'SomeVar',
123 AS 'Var2'
)
SELECT *
FROM MyTable
WHERE x = (SELECT SomeVar FROM MyVars)
You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.
<div ng-repeat="week in [1,2]">
<div ng-repeat="day in ['monday', 'tuesday']">
<ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
</div>
</div>
Please try to use this code for converting 3 decimal values after a point into 2 decimal places:
declare @val decimal (8, 2)
select @val = 123.456
select @val = @val
select @val
The output is 123.46
Another way to compare two dates, is through the toISOString()
method. This is especially useful when comparing to a fixed date kept in a string, since you can avoid creating a short-lived object. By virtue of the ISO 8601 format, you can compare these strings lexicographically (at least when you're using the same timezone).
I'm not necessarily saying that it's better than using time objects or timestamps; just offering this as another option. There might be edge cases when this could fail, but I haven't stumbled upon them yet :)
I see most of the developers use inline query without looking out it's impact on huge data.
in simple you can achieve this by:
select a.chargeId, a.chargeType, a.serviceMonth
from invoice a
left outer join invoice b
on a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth
where b.chargeId is null
order by a.serviceMonth desc
The split function separates each part of text with the separator you provide, and you provided "|". So the result would be an array containing "Shimla", "1" and "http://vinspro.org/travel/ind/". You could manipulate that to get the third one, "http://vinspro.org/travel/ind/", and here's an example:
var str="Shimla|1|http://vinspro.org/travel/ind/";
var n = str.split('|');
alert(n[2]);
As mentioned in other answers, this code would differ depending on if it was a string ($(str).split('|');), a textbox input ($(str).val().split('|');), or a DOM element ($(str).text().split('|');).
You could also just use plain JavaScript to get all the stuff after 9 characters, which would be "http://vinspro.org/travel/ind/". Here's an example:
var str="Shimla|1|http://vinspro.org/travel/ind/";
var n=str.substr(9);
alert(n);
Typescript from v1.4 has the type
keyword which declares a type alias (analogous to a typedef
in C/C++). You can declare your callback type thus:
type CallbackFunction = () => void;
which declares a function that takes no arguments and returns nothing. A function that takes zero or more arguments of any type and returns nothing would be:
type CallbackFunctionVariadic = (...args: any[]) => void;
Then you can say, for example,
let callback: CallbackFunctionVariadic = function(...args: any[]) {
// do some stuff
};
If you want a function that takes an arbitrary number of arguments and returns anything (including void):
type CallbackFunctionVariadicAnyReturn = (...args: any[]) => any;
You can specify some mandatory arguments and then a set of additional arguments (say a string, a number and then a set of extra args) thus:
type CallbackFunctionSomeVariadic =
(arg1: string, arg2: number, ...args: any[]) => void;
This can be useful for things like EventEmitter handlers.
Functions can be typed as strongly as you like in this fashion, although you can get carried away and run into combinatoric problems if you try to nail everything down with a type alias.
One simple line in base R:
df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]
Same in two lines, for clarity/efficiency:
fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]
I've been using Jasob for years and it is hands down the best obfuscator out there.
It has an advanced UI but is still intuitive and easy to use.
It will also handle HTML and CSS files.
The best way to use it is to prefix all of your private variables with something like an underscore, then use the sort
feature to group them all together and check them off as targets for obfuscation.
Users can still view your source, but it's much more difficult to decipher when your private variables are converted from something like _sUserPreferredNickName
to a
.
The engine will automatically tally up the number of targeted variables and prioritize them to get the maximum compression.
I don't work for Jasob and I get nothing out of promoting them, just offering some friendly advice.
The downside is that it's not free and is a little pricey, but still worth it when stacked against alternatives - the 'free' options don't even come close.
In /etc/profile , if you open that will you’ll get to know that IT IS no recommended to write on that file. Instead of that make a script of your commands(suppose test.sh)go to /etc/profile.d folder and Put test.sh there. Every time you instance reboot it’ll be automatically called by /etc/profile.
Array#average
.I was doing the same thing quite often so I thought it was prudent to just extend the Array
class with a simple average
method. It doesn't work for anything besides an Array of numbers like Integers or Floats or Decimals but it's handy when you use it right.
I'm using Ruby on Rails so I've placed this in config/initializers/array.rb
but you can place it anywhere that's included on boot, etc.
config/initializers/array.rb
class Array
# Will only work for an Array of numbers like Integers, Floats or Decimals.
#
# Throws various errors when trying to call it on an Array of other types, like Strings.
# Returns nil for an empty Array.
#
def average
return nil if self.empty?
self.sum.to_d / self.size
end
end
if you want to populate a table in SQL SERVER you can use while statement as follows:
declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end
Hope it helps.
It's worth mentioning that if you are simply using S3 for backups, you should just zip the folder and then upload that. This Will save you upload time and costs.
If you are not sure how to do efficient zipping from the terminal have a look here for OSX.
And $ zip -r archive_name.zip folder_to_compress
for Windows.
Alternatively a client such as 7-Zip would be sufficient for Windows users
This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.
After testing with precise instructions (using python2 or python3 instead of just "python") I've constated that no matter what the tutorial says, this works ONLY with python3.
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.
In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.
Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!
Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).
You might need to change your path by:
import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
In my case, clearing caché didn't work.
On SDK Manager, be sure to check the box on "show package descriptions"; then you should also select the "Google APIs" for the version you are willing to install.
Install it and then you should be ok
This code should do it:
manifest.json
{
"name": "Alert 'hello world!' on page opening",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
content.js
alert('Hello world!')
Use something like this in case you also want to output products details per date as JSON and the MySQL
version does not support JSON
functions.
SELECT `date`,
CONCAT('{',GROUP_CONCAT('{\"id\": \"',`product_id`,'\",\"name\": \"',`product_name`,'\"}'),'}') as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC
product_id product_name date
| 1 | azd | 2011-12-12 |
| 2 | xyz | 2011-12-12 |
| 3 | ase | 2011-12-11 |
| 4 | azwed | 2011-12-11 |
| 5 | wed | 2011-12-10 |
| 6 | cvg | 2011-12-10 |
| 7 | cvig | 2011-12-09 |
RESULT
date productsJSON
2011-12-12T00:00:00Z {{"id": "1","name": "azd"},{"id": "2","name": "xyz"}}
2011-12-11T00:00:00Z {{"id": "3","name": "ase"},{"id": "4","name": "azwed"}}
2011-12-10T00:00:00Z {{"id": "5","name": "wed"},{"id": "6","name": "cvg"}}
2011-12-09T00:00:00Z {{"id": "7","name": "cvig"}}
Try it out in SQL Fiddle
If you are using a MySQL
version that supports JSON
functions then the above query could be re-written:
SELECT `date`,JSON_OBJECTAGG(CONCAT('product-',`product_id`),JSON_OBJECT('id', `product_id`, 'name', `product_name`)) as `productsJSON`
FROM `buy` group by `date`
order by `date` DESC;
Try both in DB Fiddle
Sometimes, the same error occurs when you forget to include the corresponding header
.
Update: Since Emacs 24.4:
tab-stop-list
is now implicitly extended to infinity. Its default value is changed tonil
which means a tab stop everytab-width
columns.
which means that there's no longer any need to be setting tab-stop-list
in the way shown below, as you can keep it set to nil
.
Original answer follows...
It always pains me slightly seeing things like (setq tab-stop-list 4 8 12 ................)
when the number-sequence
function is sitting there waiting to be used.
(setq tab-stop-list (number-sequence 4 200 4))
or
(defun my-generate-tab-stops (&optional width max)
"Return a sequence suitable for `tab-stop-list'."
(let* ((max-column (or max 200))
(tab-width (or width tab-width))
(count (/ max-column tab-width)))
(number-sequence tab-width (* tab-width count) tab-width)))
(setq tab-width 4)
(setq tab-stop-list (my-generate-tab-stops))
initialize() method
fullNameColumn = new TableColumn("Full name");
fullNameColumn.setCellValueFactory(new PropertyValueFactory<User, String>("fullName"));
usernameColumn = new TableColumn("Username");
usernameColumn.setCellValueFactory(new PropertyValueFactory<User, String>("test"));
emailColumn = new TableColumn("Email");
emailColumn.setCellValueFactory(new PropertyValueFactory<User, String>("email"));
reseller_table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
reseller_table.getColumns().addAll(usernameColumn, fullNameColumn, emailColumn);
ObservableList<User> data = FXCollections.observableArrayList(User.getResellers());
reseller_table.setItems(data);
User Class (Hibernate POJO Class)
private SimpleStringProperty test;
public void setFullName(String fullName) {
this.fullName = fullName;
this.test = new SimpleStringProperty(fullName);
}
public SimpleStringProperty testProperty() {
return test;
}
refresh() method
ObservableList<User> data = FXCollections.observableArrayList(User.getResellers());
reseller_table.setItems(data);
Anything that is not stored on an EBS volume that is mounted to the instance will be lost.
For example, if you mount your EBS volume at /mystuff
, then anything not in /mystuff
will be lost. If you don't mount an ebs volume and save stuff on it, then I believe everything will be lost.
You can create an AMI from your current machine state, which will contain everything in your ephemeral storage. Then, when you launch a new instance based on that AMI it will contain everything as it is now.
Update: to clarify based on comments by mattgmg1990 and glenn bech:
Note that there is a difference between "stop" and "terminate". If you "stop" an instance that is backed by EBS then the information on the root volume will still be in the same state when you "start" the machine again. According to the documentation, "By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates" but you can modify that via configuration.
If you've upgraded to Mac OS X 10.8 Mountain Lion, and previously had a working system, all you should need to do is re-enable PHP as in Step 1 of the above chosen answer.
You may also find the following Preference Pane useful for managing "web sharing" (Apache web server), which replaces system functionality removed in OS X 10.8: http://clickontyler.com/blog/2012/02/web-sharing-mountain-lion/
I also had to re-add my virtual hosts include line to the httpd.conf
Alternatively, you can use the File.GetCreationTime Method if you need to delete files based on creation dates.
I have a simple workaround.
Suppose your URI has a string stringdata
that is too long. You can simply break it into a number of parts depending on the limits of your server. Then submit the first one, in my case to write a file. Then submit the next ones to append to previously added data.
As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec
needs to understand it. If you don't want to convert the key using openssl pkcs8
or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:
static final Base64.Decoder DECODER = Base64.getMimeDecoder();
private static byte[] buildPKCS8Key(File privateKey) throws IOException {
final String s = new String(Files.readAllBytes(privateKey.toPath()));
if (s.contains("--BEGIN PRIVATE KEY--")) {
return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
}
if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
throw new RuntimeException("Invalid cert format: "+ s);
}
final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
final byte[] result = new byte[innerKey.length + 26];
System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
System.arraycopy(innerKey, 0, result, 26, innerKey.length);
return result;
}
Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec
constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));
<head>
tags in a HTML page.A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.
.ico
image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
to the <head>
element.This isn't a very beautiful answer, but it's what I use to create zero-length vectors:
0[-1] # numeric
""[-1] # character
TRUE[-1] # logical
0L[-1] # integer
A literal is a vector of length 1, and [-1]
removes the first element (the only element in this case) from the vector, leaving a vector with zero elements.
As a bonus, if you want a single NA
of the respective type:
0[NA] # numeric
""[NA] # character
TRUE[NA] # logical
0L[NA] # integer
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
scanf()
statement needs to use %lld
too.There are far too many parentheses and far too few spaces in the expression
pi += pow(-1.0, e) / (2.0*e + 1.0);
int
for main()
.int main(void)
when it ignores its arguments, though that is less of a categorical statement than the rest.main()
and don't use it myself; I write return 0;
to be explicit.I think the whole algorithm is dubious when written using long long
; the data type probably should be more like long double
(with %Lf
for the scanf()
format, and maybe %19.16Lf
for the printf()
formats.
As of Git 2.0, the behavior has become simpler:
You can configure git with push.default = current
to make life easier:
I added this so now I can just push a new branch upstream with
$ git push -u
-u
will track remote branch of the same name. Now with this configuration, you will auto-guess the remote reference to git push. From git.config documentation:
push.default
Defines the action git push should take if no refspec is explicitly given.
push.default = current
- push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.
For me, this is a good simplification of my day-to-day Git workflow. The configuration setting takes care of the 'usual' use case where you add a branch locally and want to create it remotely. Also, I can just as easily create local branches from remotes by just doing git co remote_branch_name
(as opposed to using --set-upstream-to
flag).
I know this question and the accepted answers are rather old, but the behavior has changed so that now configuration options exist to make your workflow simpler.
To add to your global Git configuration, run this on the command line:
$ git config --global push.default current
<input type="text" required="true" value="" readonly="true">
This will make a text box in readonly mode, might be helpful in generating passwords and datepickers.
Not answering the question directly, but it might help someone else.
I have a column called Volume
, having both -
(invalid/NaN) and numbers formatted with ,
df['Volume'] = df['Volume'].astype('str')
df['Volume'] = df['Volume'].str.replace(',', '')
df['Volume'] = pd.to_numeric(df['Volume'], errors='coerce')
Casting to string is required for it to apply to str.replace
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json
have a single export named default
.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default
exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require
gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain
declared by your "*.json"
.
All of this assumes that your module loader is providing the JSON as the default
export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule
compiler flag to have TypeScript analyze imported .json
files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
My Solution was to put a try catch, & is working fine
try {
this.Invoke(new EventHandler(DoUpdate)); }
catch { }
This is my nginx config file and iosocket code. Server(express) is listening on port 9191. It works well: nginx config file:
server {
listen 443 ssl;
server_name localhost;
root /usr/share/nginx/html/rdist;
location /user/ {
proxy_pass http://localhost:9191;
}
location /api/ {
proxy_pass http://localhost:9191;
}
location /auth/ {
proxy_pass http://localhost:9191;
}
location / {
index index.html index.htm;
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
location /socket.io/ {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://localhost:9191/socket.io/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
ssl_certificate /etc/nginx/conf.d/sslcert/xxx.pem;
ssl_certificate_key /etc/nginx/conf.d/sslcert/xxx.key;
}
Server:
const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
handleUserConnect(socket)
socket.on("disconnect", () => {
handleUserDisConnect(socket)
});
})
server.listen(9191, function () {
console.log('Server listening on port 9191')
})
Client(react):
const socket = io.connect('', { secure: true, query: `userId=${this.props.user._id}` })
socket.on('notifications', data => {
console.log('Get messages from back end:', data)
this.props.mergeNotifications(data)
})
I really haven't had good success with convert
[update May 2020: actually: it pretty much never works for me], but I've had EXCELLENT success with pdftoppm
. Here's a couple examples of producing high-quality images from a PDF:
[Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc:
mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg
[Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI:
mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg
[Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI:
mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg
https://askubuntu.com/questions/150100/extracting-embedded-images-from-a-pdf/1187844#1187844.
pdf2searchablepdf
] https://askubuntu.com/questions/473843/how-to-turn-a-pdf-into-a-text-searchable-pdf/1187881#1187881from the python docs:
timedelta.total_seconds()
Return the total number of seconds contained in the duration. Equivalent to
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
computed with true division enabled.
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
This functionality is new in version 2.7.
Dictionaries in python have no order. You could use a list of tuples as your data structure instead.
d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]
Then this code could be used to find the locations of keys with a specific value
locations = [i for i, t in enumerate(newd) if t[0]=='b']
>>> [1]
Is it possible that this is an error avoidance technique (advisable or not..)? Since "" is still a string, you would be able to call string functions on it that would result in an exception if it was NULL?
Here is the most straight forward and simple method I found to install go on Ubuntu 14.04 without any ppa or any other tool.
As of now, The version of GO is 1.7
Get the Go 1.7.tar.gz using wget
wget https://storage.googleapis.com/golang/go1.7.linux-amd64.tar.gz
Extract it and copy it to /usr/local/
sudo tar -C /usr/local -xzvf go1.7.linux-amd64.tar.gz
You have now successfully installed GO. Now You have to set Environment Variables so you can use the go
command from anywhere.
To achieve this we need to add a line to .bashrc
So,
sudo nano ~/.bashrc
and add the following line to the end of file.
export PATH="/usr/local/go/bin:$PATH"
Now, All the commands in go/bin
will work.
Check if the install was successful by doing
go version
For offline Documentation you can do
godoc -http=:6060
Offline documentation will be available at http://localhost:6060
NOTE:
Some people here are suggesting to change the PATH variable.
It is not a good choice.
Changing that to /usr/local/go/bin
is temporary and it'll reset once you close terminal.
go
command will only work in terminal in which you changed the value of PATH.
You'll not be able to use any other command like ls, nano
or just about everything because everything else is in /usr/bin
or in other locations. All those things will stop working and it'll start giving you error.
However, this is permanent and does not disturbs anything else.
Something like this will list and extract the files one by one, if you want to use SharpZipLib:
var zip = new ZipInputStream(File.OpenRead(@"C:\Users\Javi\Desktop\myzip.zip"));
var filestream = new FileStream(@"C:\Users\Javi\Desktop\myzip.zip", FileMode.Open, FileAccess.Read);
ZipFile zipfile = new ZipFile(filestream);
ZipEntry item;
while ((item = zip.GetNextEntry()) != null)
{
Console.WriteLine(item.Name);
using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
{
// stream with the file
Console.WriteLine(s.ReadToEnd());
}
}
Based on this example: content inside zip file
To automatically convert spaces to tabs on save, add the following Python script to a newly created subfolder called "UnexpandTabsOnSave" within "$SUBLIME_HOME$\Packages\":
import sublime, sublime_plugin, os
class ConvertSpacesToTabsOnSave( sublime_plugin.EventListener ):
# Run Sublime's 'unexpand_tabs' command when saving any file
def on_pre_save( self, view ):
view.window().run_command( 'unexpand_tabs' )
Thank you for the initial resource.
Creating an sqlite connection to a file on disk is left as an exercise for the reader ... but there is now a two-liner made possible by the pandas library
df = pandas.read_csv(csvfile)
df.to_sql(table_name, conn, if_exists='append', index=False)
Be careful to realize that there are some differences between OneToOneField(SomeModel)
and ForeignKey(SomeModel, unique=True)
. As stated in The Definitive Guide to Django:
OneToOneField
A one-to-one relationship. Conceptually, this is similar to a
ForeignKey
withunique=True
, but the "reverse" side of the relation will directly return a single object.
In contrast to the OneToOneField
"reverse" relation, a ForeignKey
"reverse" relation returns a QuerySet
.
For example, if we have the following two models (full model code below):
Car
model uses OneToOneField(Engine)
Car2
model uses ForeignKey(Engine2, unique=True)
From within python manage.py shell
execute the following:
OneToOneField
Example>>> from testapp.models import Car, Engine
>>> c = Car.objects.get(name='Audi')
>>> e = Engine.objects.get(name='Diesel')
>>> e.car
<Car: Audi>
ForeignKey
with unique=True
Example>>> from testapp.models import Car2, Engine2
>>> c2 = Car2.objects.get(name='Mazda')
>>> e2 = Engine2.objects.get(name='Wankel')
>>> e2.car2_set.all()
[<Car2: Mazda>]
from django.db import models
class Engine(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car(models.Model):
name = models.CharField(max_length=25)
engine = models.OneToOneField(Engine)
def __unicode__(self):
return self.name
class Engine2(models.Model):
name = models.CharField(max_length=25)
def __unicode__(self):
return self.name
class Car2(models.Model):
name = models.CharField(max_length=25)
engine = models.ForeignKey(Engine2, unique=True, on_delete=models.CASCADE)
def __unicode__(self):
return self.name
A small alternative to Archy Holt's answer, a bit more simple:
a. Set UIViewControllerBasedStatusBarAppearance
to NO
in info.plist
b. In AppDelegate
's application:didFinishLaunchingWithOptions:
, call:
if ([[UIDevice currentDevice].systemVersion floatValue] < 7)
{
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
}
else
{
// handling statusBar (iOS7)
application.statusBarStyle = UIStatusBarStyleLightContent;
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
self.window.clipsToBounds = YES;
// handling screen rotations for statusBar (iOS7)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidChangeStatusBarOrientationNotification:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
And add the method:
- (void)applicationDidChangeStatusBarOrientationNotification:(NSNotification *)notification
{
// handling statusBar (iOS7)
self.window.frame = [UIScreen mainScreen].applicationFrame;
}
You can also consider subclassing UIWindow
to handle UIApplicationDidChangeStatusBarOrientationNotification
itself.
A good option is to use an API like Docverter. Docverter will allow you to convert HTML to PDF or DOCX using an API.
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
Try Atatus which provides Advanced Error Tracking and Real User Monitoring for modern web apps.
Let me explain how to get stacktraces that are reasonably complete in all browsers.
Modern Chrome and Opera fully support the HTML 5 draft spec for ErrorEvent and window.onerror
. In both of these browsers you can either use window.onerror
, or bind to the 'error' event properly:
// Only Chrome & Opera pass the error object.
window.onerror = function (message, file, line, col, error) {
console.log(message, "from", error.stack);
// You can send data to your server
// sendError(data);
};
// Only Chrome & Opera have an error attribute on the event.
window.addEventListener("error", function (e) {
console.log(e.error.message, "from", e.error.stack);
// You can send data to your server
// sendError(data);
})
Unfortunately Firefox, Safari and IE are still around and we have to support them too. As the stacktrace is not available in window.onerror
we have to do a little bit more work.
It turns out that the only thing we can do to get stacktraces from errors is to wrap all of our code in a try{ }catch(e){ }
block and then look at e.stack
. We can make the process somewhat easier with a function called wrap that takes a function and returns a new function with good error handling.
function wrap(func) {
// Ensure we only wrap the function once.
if (!func._wrapped) {
func._wrapped = function () {
try{
func.apply(this, arguments);
} catch(e) {
console.log(e.message, "from", e.stack);
// You can send data to your server
// sendError(data);
throw e;
}
}
}
return func._wrapped;
};
This works. Any function that you wrap manually will have good error handling, but it turns out that we can actually do it for you automatically in most cases.
By changing the global definition of addEventListener
so that it automatically wraps the callback we can automatically insert try{ }catch(e){ }
around most code. This lets existing code continue to work, but adds high-quality exception tracking.
var addEventListener = window.EventTarget.prototype.addEventListener;
window.EventTarget.prototype.addEventListener = function (event, callback, bubble) {
addEventListener.call(this, event, wrap(callback), bubble);
}
We also need to make sure that removeEventListener
keeps working. At the moment it won't because the argument to addEventListener
is changed. Again we only need to fix this on the prototype
object:
var removeEventListener = window.EventTarget.prototype.removeEventListener;
window.EventTarget.prototype.removeEventListener = function (event, callback, bubble) {
removeEventListener.call(this, event, callback._wrapped || callback, bubble);
}
You can send error data using image tag as follows
function sendError(data) {
var img = newImage(),
src = 'http://yourserver.com/jserror&data=' + encodeURIComponent(JSON.stringify(data));
img.crossOrigin = 'anonymous';
img.onload = function success() {
console.log('success', data);
};
img.onerror = img.onabort = function failure() {
console.error('failure', data);
};
img.src = src;
}
Disclaimer: I am a web developer at https://www.atatus.com/.
To get full path of a file :
1) open your terminal in the folder containing your file, by pushing on the keyboard following keys:
CTRL + ALT + T
2) then type "pwd" (acronym of Print name of Working Directory):
your@device ~ $ pwd
that's all folks!
2 month old thread, but better late than never! On 10.6, I have my webserver documents folder set to:
owner:root
group:_www
permission:755
_www is the user that runs apache under Mac OS X. I then added an ACL to allow full permissions to the Administrators group. That way, I can still make any changes with my admin user without having to authenticate as root. Also, when I want to allow the webserver to write to a folder, I can simply chmod to 775, leaving everyone other than root:_www with only read/execute permissions (excluding any ACLs that I have applied)
Pure CSS:
.app-tooltip {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
content: attr(data-title);_x000D_
background-color: rgba(97, 97, 97, 0.9);_x000D_
color: #fff;_x000D_
font-size: 12px;_x000D_
padding: 10px;_x000D_
position: absolute;_x000D_
bottom: -50px;_x000D_
opacity: 0;_x000D_
transition: all 0.4s ease;_x000D_
font-weight: 500;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
left: 5px;_x000D_
bottom: -16px;_x000D_
border-style: solid;_x000D_
border-width: 0 10px 10px 10px;_x000D_
border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
/// <summary>
/// Returns list of items that are in initial but not in final list.
/// </summary>
/// <param name="listA"></param>
/// <param name="listB"></param>
/// <returns></returns>
public static IEnumerable<string> NonIntersect(
List<string> initial, List<string> final)
{
//subtracts the content of initial from final
//assumes that final.length < initial.length
return initial.Except(final);
}
/// <summary>
/// Returns the symmetric difference between the two list.
/// http://en.wikipedia.org/wiki/Symmetric_difference
/// </summary>
/// <param name="initial"></param>
/// <param name="final"></param>
/// <returns></returns>
public static IEnumerable<string> SymmetricDifference(
List<string> initial, List<string> final)
{
IEnumerable<string> setA = NonIntersect(final, initial);
IEnumerable<string> setB = NonIntersect(initial, final);
// sum and return the two set.
return setA.Concat(setB);
}
}
On button click you can try the following.
protected void button1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Admin/Admin.aspx");
}
And on PageLoad you can check whether the loading is coming from that button then increase the count.
protected void Page_Load(object sender, EventArgs e)
{
StackTrace stackTrace = new StackTrace();
string eventName = stackTrace.GetFrame(1).GetMethod().Name; // this will the event name.
if (eventName == "button1_Click")
{
// code to increase the count;
}
}
Thanks
If you want to do it in XML, jus set paddingTop
and paddingLeft
to your RecyclerView
and equal amount of layoutMarginBottom
and layoutMarginRight
to the item you inflate into your RecyclerView
(or vice versa).
This really useful example. It lacks in the documentation doctrine 2.
Very thank you.
For the proxies functions can be done :
class AlbumTrack extends AlbumTrackAbstract {
... proxy method.
function getTitle() {}
}
class TrackAlbum extends AlbumTrackAbstract {
... proxy method.
function getTitle() {}
}
class AlbumTrackAbstract {
private $id;
....
}
and
/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;
/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;
I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:
Your answer (assuming this works, I haven't tried this):
<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
Second option:
@if (Model.Details.Count > 0) {
<div class="details show">
}
else {
<div class="details hide">
}
Third option:
<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
Make sure you have a service started and listening on the port.
netstat -ln | grep 8080
and
sudo netstat -tulpn
Let's say you have two activities.
And on click of a Button, this happens.
1) Enable Content Transition
Go to your style.xml
and add this line to enable the content transition.
<item name="android:windowContentTransitions">true</item>
2) Write Default Enter and Exit Transition for your AllCastActivity
public void setAnimation()
{
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
slide.setDuration(400);
slide.setInterpolator(new AccelerateDecelerateInterpolator());
getWindow().setExitTransition(slide);
getWindow().setEnterTransition(slide);
}
}
3) Start Activity with Intent
Write this method in Your MovieDetailActivity
to start AllCastActivity
public void startActivity(){
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());
if(Build.VERSION.SDK_INT>20)
{
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
startActivity(i,options.toBundle());
}
else {
startActivity(i);
}
}
put your setAnimation()
method before setContentView()
method otherwise the animation will not work.
So your AllCastActivity.java
should look like this
class AllCastActivity extends AppcompatActivity {
@Override
protected void onCreate(Bundle savedInstaceState)
{
super.onCreate(savedInstaceState);
setAnimation();
setContentView(R.layout.all_cast_activity);
.......
}
private void setAnimation(){
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
..........
}
}
Another possible cause for this error message is if the HTTP Method is blocked by the server or load balancer.
It seems to be standard security practice to block unused HTTP Methods. We ran into this because HEAD was being blocked by the load balancer (but, oddly, not all of the load balanced servers, which caused it to fail only some of the time). I was able to test that the request itself worked fine by temporarily changing it to use the GET method.
The error code on iOS was: Error requesting App Code: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
spawn
is called the right wayFirst, review the docs for child_process.spawn( command, args, options ):
Launches a new process with the given
command
, with command line arguments inargs
. If omitted,args
defaults to an empty Array.The third argument is used to specify additional options, which defaults to:
{ cwd: undefined, env: process.env }
Use
env
to specify environment variables that will be visible to the new process, the default isprocess.env
.
Ensure you are not putting any command line arguments in command
and the whole spawn
call is valid. Proceed to next step.
Search on your source code for each call to spawn
, or child_process.spawn
, i.e.
spawn('some-command', [ '--help' ]);
and attach there an event listener for the 'error' event, so you get noticed the exact Event Emitter that is throwing it as 'Unhandled'. After debugging, that handler can be removed.
spawn('some-command', [ '--help' ])
.on('error', function( err ){ throw err })
;
Execute and you should get the file path and line number where your 'error' listener was registered. Something like:
/file/that/registers/the/error/listener.js:29
throw err;
^
Error: spawn ENOENT
at errnoException (child_process.js:1000:11)
at Process.ChildProcess._handle.onexit (child_process.js:791:34)
If the first two lines are still
events.js:72
throw er; // Unhandled 'error' event
do this step again until they are not. You must identify the listener that emits the error before going on next step.
$PATH
is setThere are two possible scenarios:
spawn
behaviour, so child process environment will be the same as process.env
.env
object to spawn
on the options
argument.In both scenarios, you must inspect the PATH
key on the environment object that the spawned child process will use.
Example for scenario 1
// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);
Example for scenario 2
var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });
The absence of PATH
(i.e., it's undefined
) will cause spawn
to emit the ENOENT
error, as it will not be possible to locate any command
unless it's an absolute path to the executable file.
When PATH
is correctly set, proceed to next step. It should be a directory, or a list of directories. Last case is the usual.
command
exists on a directory of those defined in PATH
Spawn may emit the ENOENT
error if the filename command
(i.e, 'some-command') does not exist in at least one of the directories defined on PATH
.
Locate the exact place of command
. On most linux distributions, this can be done from a terminal with the which
command. It will tell you the absolute path to the executable file (like above), or tell if it's not found.
Example usage of which and its output when a command is found
> which some-command
some-command is /usr/bin/some-command
Example usage of which and its output when a command is not found
> which some-command
bash: type: some-command: not found
miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.
When command is a simple script file ensure it's accessible from a directory on the PATH
. If it's not, either move it to one or make a link to it.
Once you determine PATH
is correctly set and command
is accessible from it, you should be able to spawn your child process without spawn ENOENT
being thrown.
For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).
The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.
function getIndexByAttribute(list, attr, val){
var result = null;
$.each(list, function(index, item){
if(item[attr].toString() == val.toString()){
result = index;
return false; // breaks the $.each() loop
}
});
return result;
}
If you only want to test for true
against null
/false
, One I've just used and reads quite well is
bool? someCondition = null
if (someCondition.Equals(true))
...
I came across the same error when trying to add the callback to an event listener. Strangely, setting the callback type to EventListener solved it. It looks more elegant than defining a whole function signature as a type, but I'm not sure if this is the correct way to do this.
class driving {
// the answer from this post - this works
// private callback: () => void;
// this also works!
private callback:EventListener;
constructor(){
this.callback = () => this.startJump();
window.addEventListener("keydown", this.callback);
}
startJump():void {
console.log("jump!");
window.removeEventListener("keydown", this.callback);
}
}
I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
If you need step-by-step you can read this great article:
You can also get stack trace as string via ExceptionUtils.getStackTrace
.
See: ExceptionUtils.java
I use it only for log.debug
, to keep log.error
simple.
In your Controller, you should be able to access a dictionary (hash) called params
. So, if you know what the names of each query parameter is, then just do params[:param1]
to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.
Some simple examples here.
It's a little troublesome for retina screen, i use tkinter to get the fake size, use pilllow grab to get real size :
import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height
InetAddress.getLocalHost().getHostName()
is the more portable way.
exec("hostname")
actually calls out to the operating system to execute the hostname
command.
Here are a couple other related answers on SO:
EDIT: You should take a look at A.H.'s answer or Arnout Engelen's answer for details on why this might not work as expected, depending on your situation. As an answer for this person who specifically requested portable, I still think getHostName()
is fine, but they bring up some good points that should be considered.
Check if this solves the problem:
<div class="container-fluid no-padding">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
CSS
.no-padding {
padding-left: 0;
padding-right: 0;
}
Css class no-padding
will override default bootstrap container padding.
Full example here.
@Update If you use bootstrap 4 it could be done even simpler
<div class="container-fluid px-0">
<div class="row">
<div class="col-md-12">
<img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=1300%C3%97400&w=1300&h=400" alt="placeholder 960" class="img-responsive" />
</div>
</div>
</div>
Updated example here.
Array slicing like in Python (From the rebash library):
array_slice() {
local __doc__='
Returns a slice of an array (similar to Python).
From the Python documentation:
One way to remember how slices work is to think of the indices as pointing
between elements, with the left edge of the first character numbered 0.
Then the right edge of the last element of an array of length n has
index n, for example:
```
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
```
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1:-2 "${a[@]}")
1 2 3
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0:1 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
empty
>>> local a=(0 1 2 3 4 5)
>>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
empty
>>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
empty
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
>>> local a=(0 1 2 3 4 5)
>>> # from the beginning to position 2 (excluded)
>>> echo $(array.slice 0:2 "${a[@]}")
>>> echo $(array.slice :2 "${a[@]}")
0 1
0 1
>>> local a=(0 1 2 3 4 5)
>>> # from position 3 (included) to the end
>>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice 3: "${a[@]}")
3 4 5
3 4 5
>>> local a=(0 1 2 3 4 5)
>>> # from the second-last (included) to the end
>>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
>>> echo $(array.slice -2: "${a[@]}")
4 5
4 5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -4:-2 "${a[@]}")
2 3
If no range is given, it works like normal array indices.
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -1 "${a[@]}")
5
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice -2 "${a[@]}")
4
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 0 "${a[@]}")
0
>>> local a=(0 1 2 3 4 5)
>>> echo $(array.slice 1 "${a[@]}")
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice 6 "${a[@]}"; echo $?
1
>>> local a=(0 1 2 3 4 5)
>>> array.slice -7 "${a[@]}"; echo $?
1
'
local start end array_length length
if [[ $1 == *:* ]]; then
IFS=":"; read -r start end <<<"$1"
shift
array_length="$#"
# defaults
[ -z "$end" ] && end=$array_length
[ -z "$start" ] && start=0
(( start < 0 )) && let "start=(( array_length + start ))"
(( end < 0 )) && let "end=(( array_length + end ))"
else
start="$1"
shift
array_length="$#"
(( start < 0 )) && let "start=(( array_length + start ))"
let "end=(( start + 1 ))"
fi
let "length=(( end - start ))"
(( start < 0 )) && return 1
# check bounds
(( length < 0 )) && return 1
(( start < 0 )) && return 1
(( start >= array_length )) && return 1
# parameters start with $1, so add 1 to $start
let "start=(( start + 1 ))"
echo "${@: $start:$length}"
}
alias array.slice="array_slice"
Use the iFrame's .onload
function of JavaScript:
<iframe id="my_iframe" src="http://www.test.tld/">
<script type="text/javascript">
document.getElementById('my_iframe').onload = function() {
__doPostBack('ctl00$ctl00$bLogout','');
}
</script>
<!--OTHER STUFF-->
</iframe>
You are passing hello()
as a string, also hello()
means execute hello
immediately.
try
onClick={hello}
This worked for me:
$ sudo apt-get install php-gd php-mysql
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable, without stopping further propagation of the event.
Did you try using t.Text
?
Pictures are worth a thousand Unix commands and options:
I draw this to my students each semester and they seem to grasp vi afterwards.
vi is a finite state machine with only three states.
Upon starting, vi goes into COMMAND mode, where you can type short, few character commands, blindly. You know what you are doing; this isn't for amateurs.
When you want to actually edit text, you should go to INSERT mode with some one-character command:
Now, answering the question: exiting.
You can exit vi from EX mode:
w
and x
accept a file name parameter. If you started vi with a filename, you need not give it here again.
At last, the most important: how can you reach EX mode?
EX mode is for long commands that you can see typing at the bottom line of the screen. From COMMAND mode, you push colon, :
, and a colon will appear at the bottom line, where you can type the above commands.
From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then : to go to EX mode.
If you are unsure, push ESC and that will bring you to command mode.
So, the robust method is ESC-:-x-Enter which saves your file and quits.
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find
to check the output string output
.
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
The first column actually refers to Text Field:
// Add the pet to our listview
ListViewItem lvi = new ListViewItem();
lvi.text = pet.Name;
lvi.SubItems.Add(pet.Type);
lvi.SubItems.Add(pet.Age);
listView.Items.Add(lvi);
Or you can use the Constructor
ListViewItem lvi = new ListViewItem(pet.Name);
lvi.SubItems.Add(pet.Type);
....
Below are two simple query using which you can check index created on a table in Oracle.
select index_name
from dba_indexes
where table_name='&TABLE_NAME'
and owner='&TABLE_OWNER';
select index_name
from user_indexes
where table_name='&TABLE_NAME';
Please check for more details and index size below. Index on a table and its size in Oracle
You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout
to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?
To find out, first, make a symbolic link:
$ ln -s /path/referenced/by/symlink symlink
Git doesn't know about this file yet. git ls-files
lets you inspect your index (-s
prints stat
-like output):
$ git ls-files -s ./symlink
[nothing]
Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.
$ git add ./symlink
So, what was added?
$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0 symlink
The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c
in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file
:
$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink
(Note 120000
is the mode listed in ls-files
output. It would be something like 100644
for a regular file.)
But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks
config. From man git-config
:
core.symlinks
If false, symbolic links are checked out as small plain files that contain the link text.
So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks
config.
Either way, the data referenced by the symlink is not stored in the repository.
You can do this with a list comprehension:
T2 = [[int(column) for column in row] for row in T1]
The inner list comprehension ([int(column) for column in row]
) builds a list
of int
s from a sequence of int
-able objects, like decimal strings, in row
. The outer list comprehension ([... for row in T1])
) builds a list of the results of the inner list comprehension applied to each item in T1
.
The code snippet will fail if any of the rows contain objects that can't be converted by int
. You'll need a smarter function if you want to process rows containing non-decimal strings.
If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.
T2 = [parse_a_row_of_T1(row) for row in T1]
Both answers were good so I moved them in to a directive so that it is reusable and a second scope variable doesn't have to be defined.
Here is the fiddle if you want to see it implemented
Below is the directive:
var uniqueItems = function (data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
myApp.filter('groupBy',
function () {
return function (collection, key) {
if (collection === null) return;
return uniqueItems(collection, key);
};
});
Then it can be used as follows:
<div ng-repeat="team in players|groupBy:'team'">
<b>{{team}}</b>
<li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>
</div>
Here is the Query
select count(*) from tablename
or
select count(rownum) from studennt
Use addHeader
Instead of using setHeader
method,
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains
.
For allowing access to specific domain only
:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
Check this blog post
.
Please note that inserted, deleted
means the same thing as inserted CROSS JOIN deleted
and gives every combination of every row. I doubt this is what you want.
Something like this may help get you started...
SELECT
CASE WHEN inserted.primaryKey IS NULL THEN 'This is a delete'
WHEN deleted.primaryKey IS NULL THEN 'This is an insert'
ELSE 'This is an update'
END as Action,
*
FROM
inserted
FULL OUTER JOIN
deleted
ON inserted.primaryKey = deleted.primaryKey
Depending on what you want to do, you then reference the table you are interested in with inserted.userID
or deleted.userID
, etc.
Finally, be aware that inserted
and deleted
are tables and can (and do) contain more than one record.
If you insert 10 records at once, the inserted
table will contain ALL 10 records. The same applies to deletes and the deleted
table. And both tables in the case of an update.
EDIT Examplee Trigger after OPs edit.
ALTER TRIGGER [dbo].[UpdateUserCreditsLeft]
ON [dbo].[Order]
AFTER INSERT,UPDATE,DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE
User
SET
CreditsLeft = CASE WHEN inserted.UserID IS NULL THEN <new value for a DELETE>
WHEN deleted.UserID IS NULL THEN <new value for an INSERT>
ELSE <new value for an UPDATE>
END
FROM
User
INNER JOIN
(
inserted
FULL OUTER JOIN
deleted
ON inserted.UserID = deleted.UserID -- This assumes UserID is the PK on UpdateUserCreditsLeft
)
ON User.UserID = COALESCE(inserted.UserID, deleted.UserID)
END
If the PrimaryKey of UpdateUserCreditsLeft
is something other than UserID, use that in the FULL OUTER JOIN instead.
This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:
RewriteBase /
you can easily access elements by index , by use System.Linq
Here is the sample
First add using in your class file
using System.Linq;
Then
yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value
Hope this helps.
Have a look at this
for outputing from mongo shell to file. There is no support for outputing csv from mongos shell. You would have to write the javascript yourself or use one of the many converters available. Google "convert json to csv" for example.
The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.
Here is the general explanation from the link
WhatsApp server is almost completely implemented in Erlang.
Server systems that do the backend message routing are done in Erlang.
Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.
Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.
WhatsApp server has started from ejabberd
Ejabberd is a famous open source Jabber server written in Erlang.
Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.
The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.
To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.
A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.
Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).
Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.
What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message
How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.
The accepted answer has to be really altered otherwise not working. The getDecimalFormatSymbols makes a defensive copy. Thus,
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));
The new line is this one: formatter.setDecimalFormatSymbols(symbols);
There's an additional factor here; in addition to the java executables that the java installation puts wherever you ask it to put them, on windows, the java installer also puts copies of some of those executables in your windows system32 directory, so you will likely be using which every java executable was installed most recently.
Here's my interpretation as a Function Instead:
'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String
Dim StrFile As String
'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile
StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
Do While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
Loop
End Function
In practice, about methods:
protected - accessible for inherited classes, otherwise private.
internal - public only for classes inside the assembly, otherwise private.
protected internal - means protected or internal - methods become accessible for inherited classes and for any classes inside the assembly.
The value of EOF can't be confused with any real character.
If a= getchar()
, then we must declare a
big enough to hold any value that getchar()
returns. We can't use char
since a
must be big enough to hold EOF in addition to characters.
There is also xclip-copyfile.
ThreadStart delegates in C# used to start threads have return type 'void'.
If you wish to get a 'return value' from a thread, you should write to a shared location (in an appropriate thread-safe manner) and read from that when the thread has completed executing.
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
If you just want to select the used range, use
ActiveSheet.UsedRange.Select
If you want to select from A1 to the end of the used range, you can use the SpecialCells method like this
With ActiveSheet
.Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)).Select
End With
Sometimes Excel gets confused on what is the last cell. It's never a smaller range than the actual used range, but it can be bigger if some cells were deleted. To avoid that, you can use Find and the asterisk wildcard to find the real last cell.
Dim rLastCell As Range
With Sheet1
Set rLastCell = .Cells.Find("*", .Cells(1, 1), xlValues, xlPart, , xlPrevious)
.Range(.Cells(1, 1), rLastCell).Select
End With
Finally, make sure you're only selecting if you really need to. Most of what you need to do in Excel VBA you can do directly to the Range rather than selecting it first. Instead of
.Range(.Cells(1, 1), rLastCell).Select
Selection.Font.Bold = True
You can
.Range(.Cells(1,1), rLastCells).Font.Bold = True
Actually Eclipse does create some other files not within it's directory which survive deleting it's directory.
In Snow Leopard, look in your user's account under:
~/Library/Caches/org.eclipse.eclipse
~/Library/Preferences/org.eclipse.eclipse.plist
Not sure if you need to turn on viewing of hidden files to see those.
This does it for folder names:
def printFolderName(init_indent, rootFolder):
fname = rootFolder.split(os.sep)[-1]
root_levels = rootFolder.count(os.sep)
# os.walk treats dirs breadth-first, but files depth-first (go figure)
for root, dirs, files in os.walk(rootFolder):
# print the directories below the root
levels = root.count(os.sep) - root_levels
indent = ' '*(levels*2)
print init_indent + indent + root.split(os.sep)[-1]
For its base array class, 2d arrays are no more special than 1d or 3d ones. There are some operations the preserve the dimensions, some that reduce them, other combine or even expand them.
M=np.arange(9).reshape(3,3)
M[:,0].shape # (3,) selects one column, returns a 1d array
M[0,:].shape # same, one row, 1d array
M[:,[0]].shape # (3,1), index with a list (or array), returns 2d
M[:,[0,1]].shape # (3,2)
In [20]: np.dot(M[:,0].reshape(3,1),np.ones((1,3)))
Out[20]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
In [21]: np.dot(M[:,[0]],np.ones((1,3)))
Out[21]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
Other expressions that give the same array
np.dot(M[:,0][:,np.newaxis],np.ones((1,3)))
np.dot(np.atleast_2d(M[:,0]).T,np.ones((1,3)))
np.einsum('i,j',M[:,0],np.ones((3)))
M1=M[:,0]; R=np.ones((3)); np.dot(M1[:,None], R[None,:])
MATLAB started out with just 2D arrays. Newer versions allow more dimensions, but retain the lower bound of 2. But you still have to pay attention to the difference between a row matrix and column one, one with shape (1,3)
v (3,1)
. How often have you written [1,2,3].'
? I was going to write row vector
and column vector
, but with that 2d constraint, there aren't any vectors in MATLAB - at least not in the mathematical sense of vector as being 1d.
Have you looked at np.atleast_2d
(also _1d and _3d versions)?
Since you already have sent some data,
System.out.println("going to demo.jsp");
you won't be able to send a redirect.
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
This is a pretty old thread, but there is a work-around solution now, which may not have been in BeautifulSoup at the time.
Here is an example of what I did. I use the "requests" module to read an RSS feed and get its text content in a variable called "rss_text". With that, I run it thru BeautifulSoup, search for the xpath /rss/channel/title, and retrieve its contents. It's not exactly XPath in all its glory (wildcards, multiple paths, etc.), but if you just have a basic path you want to locate, this works.
from bs4 import BeautifulSoup
rss_obj = BeautifulSoup(rss_text, 'xml')
cls.title = rss_obj.rss.channel.title.get_text()
@Bo Persson correctly states in his great answer here:
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
However, let me add also that the above two forms also:
mean exactly the same as
void arraytest(int a[0])
which means exactly the same as
void arraytest(int a[1])
which means exactly the same as
void arraytest(int a[2])
which means exactly the same as
void arraytest(int a[1000])
etc.
In every single one of the array examples above, and as shown in the example calls in the code just below, the input parameter type decays to an int *
, and can be called with no warnings and no errors, even with build options -Wall -Wextra -Werror
turned on (see my repo here for details on these 3 build options), like this:
int array1[2];
int * array2 = array1;
// works fine because `array1` automatically decays from an array type
// to `int *`
arraytest(array1);
// works fine because `array2` is already an `int *`
arraytest(array2);
As a matter of fact, the "size" value ([0]
, [1]
, [2]
, [1000]
, etc.) inside the array parameter here is apparently just for aesthetic/self-documentation purposes, and can be any positive integer (size_t
type I think) you want!
In practice, however, you should use it to specify the minimum size of the array you expect the function to receive, so that when writing code it's easy for you to track and verify. The MISRA-C-2012 standard (buy/download the 236-pg 2012-version PDF of the standard for £15.00 here) goes so far as to state (emphasis added):
Rule 17.5 The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements.
...
If a parameter is declared as an array with a specified size, the corresponding argument in each function call should point into an object that has at least as many elements as the array.
...
The use of an array declarator for a function parameter specifies the function interface more clearly than using a pointer. The minimum number of elements expected by the function is explicitly stated, whereas this is not possible with a pointer.
In other words, they recommend using the explicit size format, even though the C standard technically doesn't enforce it--it at least helps clarify to you as a developer, and to others using the code, what size array the function is expecting you to pass in.
(Not recommended, but possible. See my brief argument against doing this at the end.)
As @Winger Sendon points out in a comment below my answer, we can force C to treat an array type to be different based on the array size!
First, you must recognize that in my example just above, using the int array1[2];
like this: arraytest(array1);
causes array1
to automatically decay into an int *
. HOWEVER, if you take the address of array1
instead and call arraytest(&array1)
, you get completely different behavior! Now, it does NOT decay into an int *
! Instead, the type of &array1
is int (*)[2]
, which means "pointer to an array of size 2 of int", or "pointer to an array of size 2 of type int", or said also as "pointer to an array of 2 ints". So, you can FORCE C to check for type safety on an array, like this:
void arraytest(int (*a)[2])
{
// my function here
}
This syntax is hard to read, but similar to that of a function pointer. The online tool, cdecl, tells us that int (*a)[2]
means: "declare a as pointer to array 2 of int" (pointer to array of 2 int
s). Do NOT confuse this with the version withOUT parenthesis: int * a[2]
, which means: "declare a as array 2 of pointer to int" (AKA: array of 2 pointers to int
, AKA: array of 2 int*
s).
Now, this function REQUIRES you to call it with the address operator (&
) like this, using as an input parameter a POINTER TO AN ARRAY OF THE CORRECT SIZE!:
int array1[2];
// ok, since the type of `array1` is `int (*)[2]` (ptr to array of
// 2 ints)
arraytest(&array1); // you must use the & operator here to prevent
// `array1` from otherwise automatically decaying
// into `int *`, which is the WRONG input type here!
This, however, will produce a warning:
int array1[2];
// WARNING! Wrong type since the type of `array1` decays to `int *`:
// main.c:32:15: warning: passing argument 1 of ‘arraytest’ from
// incompatible pointer type [-Wincompatible-pointer-types]
// main.c:22:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’
arraytest(array1); // (missing & operator)
You may test this code here.
To force the C compiler to turn this warning into an error, so that you MUST always call arraytest(&array1);
using only an input array of the corrrect size and type (int array1[2];
in this case), add -Werror
to your build options. If running the test code above on onlinegdb.com, do this by clicking the gear icon in the top-right and click on "Extra Compiler Flags" to type this option in. Now, this warning:
main.c:34:15: warning: passing argument 1 of ‘arraytest’ from incompatible pointer type [-Wincompatible-pointer-types] main.c:24:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’
will turn into this build error:
main.c: In function ‘main’: main.c:34:15: error: passing argument 1 of ‘arraytest’ from incompatible pointer type [-Werror=incompatible-pointer-types] arraytest(array1); // warning! ^~~~~~ main.c:24:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’ void arraytest(int (*a)[2]) ^~~~~~~~~ cc1: all warnings being treated as errors
Note that you can also create "type safe" pointers to arrays of a given size, like this:
int array[2];
// "type safe" ptr to array of size 2 of int:
int (*array_p)[2] = &array;
...but I do NOT necessarily recommend this (using these "type safe" arrays in C), as it reminds me a lot of the C++ antics used to force type safety everywhere, at the exceptionally high cost of language syntax complexity, verbosity, and difficulty architecting code, and which I dislike and have ranted about many times before (ex: see "My Thoughts on C++" here).
For additional tests and experimentation, see also the link just below.
See links above. Also:
If you are looking at google play and want to know its package name then you can look at url or address bar. You will get package name. Here com.landshark.yaum
is the package name
https://play.google.com/store/apps/details?id=com.landshark.yaum&feature=search_result#?t=W251bGwsMSwyLDEsImNvbS5sYW5kc2hhcmsueWF1bSJd
import os
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
This worked for me
Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
{ "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };
String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };
int noOfColumns = headers.length;
int rowCount = 0;
Row rowZero = sheet.createRow(rowCount++);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int col = 1; col <= noOfColumns; col++) {
Cell cell = rowZero.createCell(col);
cell.setCellValue(headers[col - 1]);
cell.setCellStyle(style);
}
I do this by adding fa-placeholder
class to input text:
<input type="text" name="search" class="form-control" placeholder="" />
so, in css just add this:
.fa-placholder {
font-family: "FontAwesome"; }
It works well for me.
Update:
To change font while user type in your text input, just add your font after font awesome
.fa-placholder {
font-family: "FontAwesome", "Source Sans Pro"; }
My common approach to get date without the time part..
SELECT CONVERT(VARCHAR(MAX),GETDATE(),103)
SELECT CAST(GETDATE() AS DATE)
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
shopList = []
maxLengthList = 6
while len(shopList) < maxLengthList:
item = input("Enter your Item to the List: ")
shopList.append(item)
print shopList
print "That's your Shopping List"
print shopList
These features were added for security and forgery protection purposes.
However, to answer your question, here are some inputs.
You can add these lines after your the controller name.
Like so,
class NameController < ApplicationController
skip_before_action :verify_authenticity_token
Here are some lines for different versions of rails.
Rails 3
skip_before_filter :verify_authenticity_token
Rails 4:
skip_before_action :verify_authenticity_token
Should you intend to disable this security feature for all controller routines, you can change the value of protect_from_forgery to :null_session on your application_controller.rb file.
Like so,
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
end
Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:
function MyController($scope, $http) {
// ...
}
Just add a line after the declaration indicating which objects to inject when the controller is instantiated:
function MyController($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
This makes it minification-safe.
This works on both MacOSX and Linux:
#!/bin/bash
ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offline
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
For the horizontal scrolling you can simply do :
if scrollView.panGestureRecognizer.translation(in: scrollView.superview).x > 0 {
print("left")
} else {
print("right")
}
For vertical scrolling change .x
with .y
$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);
Array ( [0] => apple [1] => cherry )
//...
array_multisort($result, SORT_DESC);
//...
Array ( [0] => cherry [1] => apple )
Simply using an outer directory for the output, solved the problem for me.
sudo tar czf ./../31OCT18.tar.gz ./
Just adding another possibility as it might help someone that's trying to both iterate over an array AND maintain a count. For example, the code below goes through an array named items
and only displays the first 3 items. Notice that the each
and the if
are native jade and don't need a hyphen.
ul
- var count = 0;
each item in items
if count < 3
li= item.name
- count++;
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0
INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;
This will insert one row with 0 value in AutoNumber column, later delete that row.
There is a good polyfill for that: louisremi/background-size-polyfill
To quote the documentation:
Upload backgroundsize.min.htc to your website, along with the .htaccess that will send the mime-type required by IE (Apache only — it's built in nginx, node and IIS).
Everywhere you use background-size in your CSS, add a reference to this file.
.selector { background-size: cover; /* The url is relative to the document, not to the css file! */ /* Prefer absolute urls to avoid confusion. */ -ms-behavior: url(/backgroundsize.min.htc); }
Add the key View controller-based status bar appearance
to Info.plist
file and make it boolean type set to NO
.
Insert one line code in viewDidLoad
(this works on specific class where it is mentioned)
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
you can call javascript version of onload event in angular js. this ng-load event can be applied to any dom element like div, span, body, iframe, img etc. following is the link to add ng-load in your existing project.
download ng-load for angular js
Following is example for iframe, once it is loaded testCallbackFunction will be called in controller
EXAMPLE
JS
// include the `ngLoad` module
var app = angular.module('myApp', ['ngLoad']);
app.controller('myCtrl', function($scope) {
$scope.testCallbackFunction = function() {
//TODO : Things to do once Element is loaded
};
});
HTML
<div ng-app='myApp' ng-controller='myCtrl'>
<iframe src="test.html" ng-load callback="testCallbackFunction()">
</div>
I've had this problem before too and I think I found the answer.
If you are using a button to run the macro, it is likely linked to a different macro, perhaps a save as version of what you are currently working in and you might not even realize it. Try running the macro directly from VBA (F5) instead of running it with the button. My guess is that will work. You just have to reassign the macro on the button to the one you actually want to run.
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
You might take a look at JavaScience's source for OpenSSLKey
There's code in there that does exactly what you want to do.
In fact, they have a lot of crypto source code available here.
Source code snippet:
//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey) ;
BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try {
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt !=0x00)
return null;
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems) ;
Console.WriteLine("showing components ..");
if (verbose) {
showBytes("\nModulus", MODULUS) ;
showBytes("\nExponent", E);
showBytes("\nD", D);
showBytes("\nP", P);
showBytes("\nQ", Q);
showBytes("\nDP", DP);
showBytes("\nDQ", DQ);
showBytes("\nIQ", IQ);
}
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus =MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception) {
return null;
}
finally {
binr.Close();
}
}
Simple example:
public function productsAction()
{
$saveFileName = 'ceneo.xml';
$filename = $this->path . $saveFileName;
if(file_exists($filename)) {
$reader = new XMLReader();
$reader->open($filename);
$countElements = 0;
while($reader->read()) {
if($reader->nodeType == XMLReader::ELEMENT) {
$nodeName = $reader->name;
}
if($reader->nodeType == XMLReader::TEXT && !empty($nodeName)) {
switch ($nodeName) {
case 'id':
var_dump($reader->value);
break;
}
}
if($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == 'offer') {
$countElements++;
}
}
$reader->close();
exit(print('<pre>') . var_dump($countElements));
}
}
Looks like you forgot the mode parameter when calling open
, try w
:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
The default value is r
and will fail if the file does not exist
'r' open for reading (default)
'w' open for writing, truncating the file first
Other interesting options are
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
See Doc for Python2.7 or Python3.6
-- EDIT --
As stated by chepner in the comment below, it is better practice to do it with a with
statement (it guarantees that the file will be closed)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
I decided to go with a for loop and just avoid the item in question, is it an acceptable alternative?
new = ''
for item in str:
if item == str[n]:
continue
else:
new += item
Setting the event to null inside the class works. When you dispose a class you should always set the event to null, the GC has problems with events and may not clean up the disposed class if it has dangling events.
Never ever use a "background color" for your listview rows...
this will block every selector action (was my problem!)
good luck!
Generic Object Oriented Solution
For people like me that use frameworks like angular that don't allow manipulating DOM directly, I created a function that takes a string and returns an array of url
/plainText
objects that can be used to create any UI representation that you want.
URL regex
For URL matching I used (slightly adapted) h0mayun
regex: /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g
My function also drops punctuation characters from the end of a URL like .
and ,
that I believe more often will be actual punctuation than a legit URL ending (but it could be! This is not rigorous science as other answers explain well) For that I apply the following regex onto matched URLs /^(.+?)([.,?!'"]*)$/
.
Typescript code
export function urlMatcherInText(inputString: string): UrlMatcherResult[] {
if (! inputString) return [];
const results: UrlMatcherResult[] = [];
function addText(text: string) {
if (! text) return;
const result = new UrlMatcherResult();
result.type = 'text';
result.value = text;
results.push(result);
}
function addUrl(url: string) {
if (! url) return;
const result = new UrlMatcherResult();
result.type = 'url';
result.value = url;
results.push(result);
}
const findUrlRegex = /(?:(?:https?:\/\/)|(?:www\.))[^\s]+/g;
const cleanUrlRegex = /^(.+?)([.,?!'"]*)$/;
let match: RegExpExecArray;
let indexOfStartOfString = 0;
do {
match = findUrlRegex.exec(inputString);
if (match) {
const text = inputString.substr(indexOfStartOfString, match.index - indexOfStartOfString);
addText(text);
var dirtyUrl = match[0];
var urlDirtyMatch = cleanUrlRegex.exec(dirtyUrl);
addUrl(urlDirtyMatch[1]);
addText(urlDirtyMatch[2]);
indexOfStartOfString = match.index + dirtyUrl.length;
}
}
while (match);
const remainingText = inputString.substr(indexOfStartOfString, inputString.length - indexOfStartOfString);
addText(remainingText);
return results;
}
export class UrlMatcherResult {
public type: 'url' | 'text'
public value: string
}
Its very simple for those who are using API 21 or greater Use this code below
<resources>
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:background">@color/colorDarkGrey</item>
</style>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.ActionBar">
<item name="android:background">@color/colorDarkGrey</item>
</style>
If you are using numpy, the closest, I can think of is using a mask
>>> import numpy as np
>>> arr = np.arange(1,10)
>>> mask = np.ones(arr.shape,dtype=bool)
>>> mask[5]=0
>>> arr[mask]
array([1, 2, 3, 4, 5, 7, 8, 9])
Something similar can be achieved using itertools
without numpy
>>> from itertools import compress
>>> arr = range(1,10)
>>> mask = [1]*len(arr)
>>> mask[5]=0
>>> list(compress(arr,mask))
[1, 2, 3, 4, 5, 7, 8, 9]
This should work
if(!Directory.Exists(@"C:\MP_Upload")) {
Directory.CreateDirectory(@"C:\MP_Upload");
}
A good option is to transform the number into a string and then split it.
// Decimal number
let number = 3.2;
// Convert it into a string
let string = number.toString();
// Split the dot
let array = string.split('.');
// Get both numbers
// The '+' sign transforms the string into a number again
let firstNumber = +array[0]; // 3
let secondNumber = +array[1]; // 2
let [firstNumber, secondNumber] = [+number.toString().split('.')[0], +number.toString().split('.')[1]];
There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.
It says:
ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.
ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.
Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?
Feel free to visit our “<a href="javascript:document.location.href=document.location.origin+'/contact-us'" title="Click to Contact Us" class="coded_link" ><span class="ui-icon ui-icon-newwin"></span>Contact</a>” link
Use ampersand to specify the parent selector.
SCSS syntax:
p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
Use Apache's mod_dumpio. Be careful for obvious reasons.
Note that mod_dumpio stops logging binary payloads at the first null character. For example a multipart/form-data
upload of a gzip'd file will probably only show the first few bytes with mod_dumpio.
Also note that Apache might not mention this module in httpd.conf
even when it's present in the /modules
folder. Just manually adding LoadModule
will work fine.
You have to use the date part fetching method:
SELECT * FROM testbed WHERE start_date ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')
u can use placeholder and when u write a text on the search box placeholder will hidden. Thanks
<input placeholder="Search" type="text" />
Instead of
mount -o rw,remount /system/
use
mount -o rw,remount /system
mind the '/' at the end of the command. you ask why this matters? /system/ is the directory under /system while /system is the volume name.
EditText has singleLine property. You can set in the XML or by calling setSingleLine(false); http://developer.android.com/reference/android/widget/TextView.html#setSingleLine%28%29
Because it's an object, the way to assign value to its properties is using :
.
Change the =
to :
to fix the error.
var options = {
host: 'localhost',
port: 8080,
path: '/',
method: 'POST'
}
Since pandas 0.14.1 my suggestion here to have a keyword argument in the value_counts method has been implemented:
import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
print df[col].value_counts(dropna=False)
2 1
1 1
NaN 1
dtype: int64
NaN 2
1 1
dtype: int64
Simple way to iterate over class fields and obtain values from object:
Class<?> c = obj.getClass();
Field[] fields = c.getDeclaredFields();
Map<String, Object> temp = new HashMap<String, Object>();
for( Field field : fields ){
try {
temp.put(field.getName().toString(), field.get(obj));
} catch (IllegalArgumentException e1) {
} catch (IllegalAccessException e1) {
}
}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
You can; the null pointer is implicitly converted into boolean false while non-null pointers are converted into true. From the C++11 standard, section on Boolean Conversions:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. A zero value, null pointer value, or null member pointer value is converted tofalse
; any other value is converted totrue
. A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; the resulting value isfalse
.
Most of the solutions I see here seem to be doing a double measurement: first measuring the child views, and then calling the super.onMeasure()
I have come up with a custom WrapContentViewPager
that is more efficient, works well with RecyclerView and Fragment
You can check the demo here:
github/ssynhtn/WrapContentViewPager
and the code of the class here: WrapContentViewPager.java
$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.
example:
var self = 'some string';
var $self = 'another string';
These are declared as two different variables. It's like putting underscore before private variables.
A somewhat popular pattern is:
var foo = 'some string';
var $foo = $('.foo');
That way, you know $foo is a cached jQuery object later on in the code.
In Visual Studio 2017 if you want to test public members, simply put your real project and test project in the same solution, and add a reference to your real project in the test project.
See C++ Unit Testing in Visual Studio from the MSDN blog for more details. You can also check Write unit tests for C/C++ in Visual Studio as well as Use the Microsoft Unit Testing Framework for C++ in Visual Studio, the latter being if you need to test non public members and need to put the tests in the same project as your real code.
Note that things you want to test will need to be exported using __declspec(dllexport)
. See Exporting from a DLL Using __declspec(dllexport) for more details.
I got trouble to get it so I post pictures showing different options:
Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]
In tab Sources
:
When button is activated, you can Pause On Caught Exceptions
with the checkbox below:
Chrome 27.0.1453.93 Stable
If you are still finding that the default wrong Java version (1.7) is being used instead of your Java home directory, then all you need to do is simply change the order of your PATH variable to set JAVA_HOME\bin before your Windows directory in your PATH variable, save it and restart cygwin. Test it out to make sure everything will work fine. It should not have any adverse effect because you want your own Java version to override the default which comes with Windows. Good luck!
CSS 3 introduces the background-size property, but support is not universal.
Having the browser resize the image is inefficient though, the large image still has to be downloaded. You should resize it server side (caching the result) and use that instead. It will use less bandwidth and work in more browsers.
It handles gigantic files with ease; most text editors (TextMate especially) slow down to a dead crawl or just crash when presented with a large file.
The regexp and multiple-file Find dialogs beat anything else for usability.
The clippings system works like magic, and has selection, indentation, placeholder, and insertion point tags, it's not just dumb text.
BBEdit is heavily AppleScriptable. Everything can be scripted.
In 9.0, BBEdit has code completion, projects, and a ton of other improvements.
I primarily use it for HTML, CSS, JS, and Python, where it's extremely strong. Some more obscure languages are not as well-supported in it, but for most purposes it's fantastic.
The only devs I know who like TextMate are Ruby fans. I really do not get the appeal, it's marginally better than TextWrangler (BBEdit's free little brother), but if you're spending money, you may as well buy the better tool for a few dollars more.
jEdit does have the virtue of being cross-platform. It's not nearly as good as BBEdit, but it's a competent programmer's editor. If you're ever faced with a Windows or Linux system, it's handy to have one tool you know that works.
Vim is fine if you have to work over ssh and the remote system or your computer can't do X11. I used to love Vim for the ease of editing large files and doing repeated commands. But these days, it's a no-vote for me, with the annoyance of the non-standard search & replace (using (foo) groups instead of (foo), etc.), painfully bad multi-document handling, lack of a project/disk browser view, lack of AppleScript, and bizarre mouse handling in the GVim version.
declare this
var intro;
outside of $(document).ready()
because, $(document).ready()
will hide your variable from global scope.
Code
var intro;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
Another way:
window.intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
window.intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
window.intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
window.intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
outside of DOM ready function (currently you've) will log undefined
, but within DOM ready it will give you true/ false.
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.I need to use it outside of DOM ready function
You can use following approach:
var intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
introCheck();
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function() {
if (this.checked) {
intro = true;
} else {
intro = false;
}
introCheck();
});
});
function introCheck() {
console.log(intro);
}
After change the value of intro
I called a function that will fire with new value of intro
.
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
I had the same problem, and it came from a wrong client_id / Facebook App ID.
Did you switch your Facebook app to "public" or "online ? When you do so, Facebook creates a new app with a new App ID.
You can compare the "client_id" parameter value in the url with the one in your Facebook dashboard.
Also Make sure your app is public. Click on + Add product Now go to products => Facebook Login Now do the following:
Valid OAuth redirect URIs : example.com/
You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:
NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")
The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:
# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd
# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41
# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41
# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41
As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.
this method also encounter a deprecate warning:
org.junit.Assert.assertEquals(float expected,float actual) //deprecated
It is because currently junit prefer a third parameter rather than just two float variables input.
The third parameter is delta:
public static void assertEquals(double expected,double actual,double delta) //replacement
this is mostly used to deal with inaccurate Floating point calculations
for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values
in connection.php: mysqli_set_charset($con,“utf8”); and in sql collation utf=8
This post/question is kind of old, so I will answer a simplified version for OS X Lion users. By default, OSX Lion does not have any of the following files:
At most, if you've done anything in the terminal you might see ~/.bash_history
You must create the file to set your default bash commands (commonly in ~/.bashrc). To do this, use any sort of editor, though it's more simple to do it within the terminal:
source ~/.bashrc
Ctrl + x Ctrl + s
(to save the file)Ctrl + x Ctrl + c
(to close emacs)The next time you quit and reload the terminal, it should load all your bash preferences. For good measure, it's usually a good idea to separate your commands into useful file names. For instance, from within ~/.bashrc, you should have a source ~/.bash_aliases
and put all your alias commands in ~/.bash_aliases.
Have you tried..
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
If you are consuming a trusted source you can skip the verify.