To read only the first row of the csv file use next()
on the reader object.
with open('some.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader) # gets the first line
# now do something here
# if first row is the header, then you can do one more next() to get the next row:
# row2 = next(f)
or :
with open('some.csv', newline='') as f:
reader = csv.reader(f)
for row in reader:
# do something here with `row`
break
Please read the example in rfc6749 sec 7.1 first.
The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.
PoP means kind of multi-factor authentication to make access token more secure. ref
Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).
Maybe it's not the case, but I would say,
BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.
If you use a website and you fill out a form to submit information (your social security number for example) you want to be sure that the information is being sent to the site you think it's being sent to. So browsers were built to say, by default, 'Do not send information to a domain other than the domain being visited).
Eventually that became too limiting but the default idea still remains in browsers. Don't let the web page send information to a different domain. But this is all browser checking. Chrome and firefox, etc have built in code that says 'before send this request, we're going to check that the destination matches the page being visited'.
Postman (or CURL on the cmd line) doesn't have those built in checks. You're manually interacting with a site so you have full control over what you're sending.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
@miyuru. As suggested by him run all the steps.
Ubuntu version 16.04
Still when I ran docker --version
it was returning a version. So to uninstall it completely
Again run the dpkg -l | grep -i docker
which will list package still there in system.
For example:
ii docker-ce-cli 5:19.03.6~3-0~ubuntu-xenial
amd64 Docker CLI: the open-source application container engine
Now remove them as show below :
sudo apt-get purge -y docker-ce-cli
sudo apt-get autoremove -y --purge docker-ce-cli
sudo apt-get autoclean
Hope this will resolve it, as it did in my case.
I was trying to do the same thing, but I wanted the back button to be in the navigation bar. (I actually needed a back button, that would do more than only going back, so I had to use the leftBarButtonItem property). I tried what AndrewS suggested, but in the navigation bar it wouldn't look the way it should, as the UIButton was kind of casted to a UIBarButtonItem.
But I found a way to work around this. I actually just put a UIView under the UIButton and set the customView for the UIBarButtonItem. Here is the code, if somebody needs it:
// initialize button and button view
UIButton *backButton = [UIButton buttonWithType:101];
UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, backButton.frame.size.width, backButton.frame.size.height)];
[backButton addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButtonView addSubview:backButton];
// set buttonview as custom view for bar button item
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
self.navigationItem.leftBarButtonItem = backButtonItem;
// push item to navigationbar items
[self.navigationController.navigationBar setItems:[NSArray arrayWithObject:backButtonItem]];
since you capitalized the word, I assume you are referring to the interface javax.naming.Context
. A few classes implement this interface, and at its simplest description, it (generically) is a set of name/object pairs.
contentType: 'application/x-www-form-urlencoded'
From your question, it is unclear as-to which columns you want to use to determine duplicates. The general idea behind the solution is to create a key based on the values of the columns that identify duplicates. Then, you can use the reduceByKey or reduce operations to eliminate duplicates.
Here is some code to get you started:
def get_key(x):
return "{0}{1}{2}".format(x[0],x[2],x[3])
m = data.map(lambda x: (get_key(x),x))
Now, you have a key-value RDD
that is keyed by columns 1,3 and 4.
The next step would be either a reduceByKey
or groupByKey
and filter
.
This would eliminate duplicates.
r = m.reduceByKey(lambda x,y: (x))
You can use this Eclipse Plugin: http://marketplace.eclipse.org/node/491839#.UIlr8ZDwCUm This is a multi-line string editor popup. Place your caret in a string literal press ctrl-shift-alt-m and paste your text.
You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:
SELECT @NewIdOutputParam = SCOPE_IDENTITY()
Then in test1, retrieve it like so:
DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed
try doing:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardElevation="2dp"
card_view:cardCornerRadius="5dp">
<FrameLayout
android:background="#FF0000"
android:layout_width="4dp"
android:layout_height="match_parent"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:orientation="vertical">
<TextView
style="@style/Base.TextAppearance.AppCompat.Headline"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Title" />
<TextView
style="@style/Base.TextAppearance.AppCompat.Body1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Content here" />
</LinearLayout>
</android.support.v7.widget.CardView>
this removes the padding from the cardview and adds a FrameLayout with a color. You then need to fix the padding in the LinearLayout then for the other fields
Update
If you want to preserve the card corner radius create card_edge.xml in drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#F00" />
<size android:width="10dp"/>
<padding android:bottom="0dp" android:left="0dp" android:right="0dp" android:top="0dp"/>
<corners android:topLeftRadius="5dp" android:bottomLeftRadius="5dp"
android:topRightRadius="0.1dp" android:bottomRightRadius="0.1dp"/>
</shape>
and in the frame layout use android:background="@drawable/card_edge"
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
Here's a version of the accepted answer that 1) returns
a value from the function (bugfix), and 2) doesn't break when using "use strict";
I use this code to pre-load a .txt
file into my <textarea>
when the user loads the page.
function httpGet(theUrl)
{
let xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
return xmlhttp.response;
}
One more way is::
Write a method in your adapter lets say public void callBack(){}.
Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.
Myadapter adapter = new Myadapter() {
@Override
public void callBack() {
// dosomething
}
};
If you have another list that contains all the items you would like to add you can do arList.addAll(otherList)
. Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll()
method, with something like
Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));
or, if you don't want to create that unnecessary array:
arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
Otherwise you will have to have some sort of loop that adds the values to the list individually.
In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:
curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
"properties": {
"new_geo_field": {
"type": "geo_point"
}
}
}'
As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.
You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):
curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
"mappings": {
"properties": {
"foo_field": {
"type": "text"
}
}
}
}'
That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long
values.
You could use *ngIf="teamMembers != 0"
to check whether data is present
Declare this in your CSS and you should be good:
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
This solution can be implemented without using additional wrappers.
This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.
Posting here as I think it may be useful for people using Flask
with pymongo
. This is my current "best practice" setup for allowing flask to marshall pymongo bson data types.
mongoflask.py
from datetime import datetime, date
import isodate as iso
from bson import ObjectId
from flask.json import JSONEncoder
from werkzeug.routing import BaseConverter
class MongoJSONEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, (datetime, date)):
return iso.datetime_isoformat(o)
if isinstance(o, ObjectId):
return str(o)
else:
return super().default(o)
class ObjectIdConverter(BaseConverter):
def to_python(self, value):
return ObjectId(value)
def to_url(self, value):
return str(value)
app.py
from .mongoflask import MongoJSONEncoder, ObjectIdConverter
def create_app():
app = Flask(__name__)
app.json_encoder = MongoJSONEncoder
app.url_map.converters['objectid'] = ObjectIdConverter
# Client sends their string, we interpret it as an ObjectId
@app.route('/users/<objectid:user_id>')
def show_user(user_id):
# setup not shown, pretend this gets us a pymongo db object
db = get_db()
# user_id is a bson.ObjectId ready to use with pymongo!
result = db.users.find_one({'_id': user_id})
# And jsonify returns normal looking json!
# {"_id": "5b6b6959828619572d48a9da",
# "name": "Will",
# "birthday": "1990-03-17T00:00:00Z"}
return jsonify(result)
return app
Why do this instead of serving BSON or mongod extended JSON?
I think serving mongo special JSON puts a burden on client applications. Most client apps will not care using mongo objects in any complex way. If I serve extended json, now I have to use it server side, and the client side. ObjectId
and Timestamp
are easier to work with as strings and this keeps all this mongo marshalling madness quarantined to the server.
{
"_id": "5b6b6959828619572d48a9da",
"created_at": "2018-08-08T22:06:17Z"
}
I think this is less onerous to work with for most applications than.
{
"_id": {"$oid": "5b6b6959828619572d48a9da"},
"created_at": {"$date": 1533837843000}
}
Use dir
or type
on the 'string' to find out what it is. I suspect that it's one of BeautifulSoup's tag objects, that prints like a string, but really isn't one. Otherwise, its inside a list and you need to convert each string separately.
In any case, why are you objecting to using Unicode? Any specific reason?
Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:
<div class="someClass otherClass yetAnotherClass">
<img ... id="image1" name="image1" />
</div>
From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.
another way is;
package person
type Person struct {
Name string
Old int
}
func New(name string, old int) *Person {
// set only specific field value with field key
return &Person{
Name: name,
}
}
We'll do it using just CSS pseudo selectors!
This technique will work with dynamically generated content and different font sizes and widths.
HTML:
<div class='split-color'>Two is better than one.</div>
CSS:
.split-color > span {
white-space: pre-line;
position: relative;
color: #409FBF;
}
.split-color > span:before {
content: attr(data-content);
pointer-events: none; /* Prevents events from targeting pseudo-element */
position: absolute;
overflow: hidden;
color: #264A73;
width: 50%;
z-index: 1;
}
To wrap the dynamically generated string, you could use a function like this:
// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function wrapString(str) {
var output = [];
str.split('').forEach(function(letter) {
var wrapper = document.createElement('span');
wrapper.dataset.content = wrapper.innerHTML = letter;
output.push(wrapper.outerHTML);
});
return output.join('');
}
// Replace the original text with the split-color text
window.onload = function() {
var el = document.querySelector('.split-color'),
txt = el.innerHTML;
el.innerHTML = wrapString(txt);
}
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
//do whatever here
})
I had a similar problem, but it occurred to me inside procedure, when my query param was set using variable e.g. SET @value='foo'
.
What was causing this was mismatched collation_connection
and Database collation. Changed collation_connection
to match collation_database
and problem went away. I think this is more elegant approach than adding COLLATE after param/value.
To sum up: all collations must match. Use SHOW VARIABLES
and make sure collation_connection
and collation_database
match (also check table collation using SHOW TABLE STATUS [table_name]
).
I encountered this problem after these operations:
I finally resolved the problem by forcing the lock again : TortoiseSVN --> Get Lock --> check "steal lock" then commit or release lock.
We can use LIMIT like bellow:
Model::take(20)->get();
Go to mysql edit table
-> change column type to varchar(45)
.
Before writing this off as impossible I suggest you look at the source code of the lsof command.
There may be restrictions but lsof seems capable of determining the file descriptor and file name. This information exists in the /proc filesystem so it should be possible to get at from your program.
In android-N, this feature is included in it. check Number-blocking update for android N
Android N now supports number-blocking in the platform and provides a framework API to let service providers maintain a blocked-number list. The default SMS app, the default phone app, and provider apps can read from and write to the blocked-number list. The list is not accessible to other app.
advantage of are:
For more information, see android.provider.BlockedNumberContract
Update an existing project.
To compile your app against the Android N platform, you need to use the Java 8 Developer Kit (JDK 8), and in order to use some tools with Android Studio 2.1, you need to install the Java 8 Runtime Environment (JRE 8).
Open the build.gradle file for your module and update the values as follows:
android {
compileSdkVersion 'android-N'
buildToolsVersion 24.0.0 rc1
...
defaultConfig {
minSdkVersion 'N'
targetSdkVersion 'N'
...
}
...
}
Try:
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"
Then do another round of copy/paste of all the extensions (joined together with ;
as above) for "All graphics types":
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff"
$("#mydiv").load(location.href + " #mydiv");
Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.
Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.
Run puttygen from Command Prompt
a. Click “Load” button to “Load an existing private key file”
b. Change the file filter to “All Files (.)
c. Select the YourPEMFILE.pem
d. Click Open
e. Puttygen shows a notice saying that it Successfully imported foreign key. Click OK.
f. Click “Save private key” button
g. When asked if you are sure that you want to save without a passphrase entered, answer “Yes”.
h. Enter the file name YourPEMFILE.ppk
i. Click “Save”
I believe it's:
git checkout master
git checkout -b good_quickfix2
git cherry-pick quickfix2^
git cherry-pick quickfix2
What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
Hope this helps.
You can call the button_click event by simply passing the arguments to it:
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
You can use addition to concatenate strings.
Strings are added by being joined into a larger string.
jq '.users[] | .first + " " + .last'
The above works when both first
and last
are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.
jq '.users[] | .first + " " + (.number|tostring)'
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
The default behaviour of Newtonsoft.Json is going to find the public
constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected
or internal
so that Newtonsoft.Json will pick your desired public
constructor.
Admittedly, this solution is rather very limited to specific cases.
internal Result() { }
public Result(int? code, string format, Dictionary<string, string> details = null)
{
Code = code ?? ERROR_CODE;
Format = format;
if (details == null)
Details = new Dictionary<string, string>();
else
Details = details;
}
Well, the first question is easy. There are many en
s (Englishes) but (mostly) only one US English. One would guess there are en-CN
, en-GB
, en-AU
. Guess there might even be Austrian English but that's more yes you can than yes there is.
This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.
double a;
a=3669.0;
int b;
b=a+ 1e-9;
This can be done with standard java properties in combination with the maven-resource-plugin
with enabled filtering on properties.
For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
This will work for standard maven project as for plugin projects
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim
This is a pretty recent addition to javascript, and its not supported by IE.
Use:
vector<vector<float>> vecArray; //both dimensions are open!
The $http
legacy promise methods success
and error
have been deprecated. Use the standard then
method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http
Now the right way to use is:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has these properties:
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:
conda create -n Python27 python=2.7
This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate
(windows) or source deactivate
(linux, osx) in the command line. To activate in the future type activate Python27
(windows) or source activate Python27
(linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.
Update
As of conda
version 4.6 you can now use conda activate
and conda deactivate
. The use of source
is now deprecated and will eventually be removed.
Actually, after waiting some time it eventually goes beyond that step.
Even with --verbose
, you won't have any information that it computes anything, but it does.
Patience is the key :)
PS : For anyone that cancelled at that step, if you try to reinstall the android-sdk package, it will complain that Error: No such file or directory - /usr/local/share/android-sdk
.
You can just touch /usr/local/share/android-sdk
to get rid of that error and go on with the reinstall.
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
List<Student> str = new ArrayList<Student>();
str.add(new Student(101, "aaa"));
str.add(new Student(104, "bbb"));
str.add(new Student(103, "ccc"));
str.add(new Student(105, "ddd"));
str.add(new Student(104, "eee"));
str.add(new Student(102, "fff"));
Collections.sort(str);
for(Student student : str) {
System.out.println(student);
}
}
}
This code gets the maximum value from the maxlength
attribute of the textarea
and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
Try this:
<img src="images/background.jpg"
style="width:100%;height:100%;position:absolute;top:0;left:0;z-index:-5000;">
http://thewebthought.blogspot.com/2010/10/css-making-background-image-fit-any.html
Add this two line in your style.xml
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
Sometimes you inherit brittle code that is already expecting magic values in a lot of places. Everyone is correct, you should use NULL if possible. However, as a shortcut to make sure every reference to that value is the same, I like to put "constants" (for lack of a better name) in SQL in a scaler function and then call that function when I need the value. That way if I ever want to update them all to be something else, I can do so easily. Or if I want to change the default value moving forward, I only have one place to update it.
The following code creates the function and a table using it for the default DateTime value. Then inserts and select from the table without specifying the value for Modified. Then cleans up after itself. I hope this helps.
-- CREATE FUNCTION
CREATE FUNCTION dbo.DateTime_MinValue ( )
RETURNS DATETIME
AS
BEGIN
DECLARE @dateTime_min DATETIME ;
SET @dateTime_min = '1/1/1753 12:00:00 AM'
RETURN @dateTime_min ;
END ;
GO
-- CREATE TABLE USING FUNCTION FOR DEFAULT
CREATE TABLE TestTable
(
TestTableId INT IDENTITY(1, 1)
PRIMARY KEY CLUSTERED ,
Value VARCHAR(50) ,
Modified DATETIME DEFAULT dbo.DateTime_MinValue()
) ;
-- INSERT VALUE INTO TABLE
INSERT INTO TestTable
( Value )
VALUES ( 'Value' ) ;
-- SELECT FROM TABLE
SELECT TestTableId ,
VALUE ,
Modified
FROM TestTable ;
-- CLEANUP YOUR DB
DROP TABLE TestTable ;
DROP FUNCTION dbo.DateTime_MinValue ;
var switchData = $('#show-me');
switchData.hide();
$('input[type="radio"]').change(function(){ var inputData = $(this).attr("value");if(inputData == 'b') { switchData.show();}else{switchData.hide();}});
You can do it like this:
var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");
EDIT: New standard has fromHexString rather than fromString
It's caused by n % x
, when x
is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.
General notes:
q
to be global.For what it's worth, from my IE9 testing, it looks like there's a difference for URLs that contain a hashbang (a single page app, in my case):
http://www.example.com#page
The driver.get("http://www.example.com#anotherpage")
method is handled by the browser as a fragment identifier and JavaScript variables are retained from the previous URL.
While, the navigate().to("http://www.example.com#anotherpage")
method is handled by the browser as a address/location/URL bar input and JavaScript variables are not retained from the previous URL.
A pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
canvas {
background-color: #ccc;
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
</script>
</body>
</html>
Link to the example: http://temporaer.net/open/so/140502_canvas-fit-to-window.html
But take care, as @jerseyboy states in his comment:
Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you'll have to transform the coordinate systems.
If I understand your question correctly, here are four methods to do the equivalent of Excel's VLOOKUP
and fill down using R
:
# load sample data from Q
hous <- read.table(header = TRUE,
stringsAsFactors = FALSE,
text="HouseType HouseTypeNo
Semi 1
Single 2
Row 3
Single 2
Apartment 4
Apartment 4
Row 3")
# create a toy large table with a 'HouseType' column
# but no 'HouseTypeNo' column (yet)
largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)
# create a lookup table to get the numbers to fill
# the large table
lookup <- unique(hous)
HouseType HouseTypeNo
1 Semi 1
2 Single 2
3 Row 3
5 Apartment 4
Here are four methods to fill the HouseTypeNo
in the largetable
using the values in the lookup
table:
First with merge
in base:
# 1. using base
base1 <- (merge(lookup, largetable, by = 'HouseType'))
A second method with named vectors in base:
# 2. using base and a named vector
housenames <- as.numeric(1:length(unique(hous$HouseType)))
names(housenames) <- unique(hous$HouseType)
base2 <- data.frame(HouseType = largetable$HouseType,
HouseTypeNo = (housenames[largetable$HouseType]))
Third, using the plyr
package:
# 3. using the plyr package
library(plyr)
plyr1 <- join(largetable, lookup, by = "HouseType")
Fourth, using the sqldf
package
# 4. using the sqldf package
library(sqldf)
sqldf1 <- sqldf("SELECT largetable.HouseType, lookup.HouseTypeNo
FROM largetable
INNER JOIN lookup
ON largetable.HouseType = lookup.HouseType")
If it's possible that some house types in largetable
do not exist in lookup
then a left join would be used:
sqldf("select * from largetable left join lookup using (HouseType)")
Corresponding changes to the other solutions would be needed too.
Is that what you wanted to do? Let me know which method you like and I'll add commentary.
Use this for print key hash in kotlin
try {
val info = context.getPackageManager().getPackageInfo(context.packageName,
PackageManager.GET_SIGNATURES);
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("Key hash ", android.util.Base64.encodeToString(md.digest(), android.util.Base64.DEFAULT))
}
}catch (e:Exception){
}
std::string bin(uint_fast8_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}
You have to use Appcompat
library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name" />
And at last, your SearchResultsActivity
class code. for showing result of your search.
You can get this result if you are inside a corporate proxy and the new project isn't pointing to the correct settings.xml file with the proxy credentials.
You can also get this if you are using Maven proxy (Nexus, for example) and the index into the proxy is messed up somehow. I don't know a way to describe how to fix this. Fool around with it or call the one who set up the Maven proxy.
You can also get this if the new workspace hasn't yet downloaded the index either from Maven central or from the proxy. (This is the best one as you just have to wait a while and it will work itself out.)
Steven is right, in theory:
the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:
table
{
margin-left: auto;
margin-right: auto;
}
But the article mentioned in the beginning of this answer gives you all the other way to center a table.
An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:
div.centered
{
text-align: center;
}
div.centered table
{
margin: 0 auto;
text-align: left;
}
<div class="centered">
<table>
…
</table>
</div>
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
You have to use target attribute
<a href="newsletter_01.pdf" target="_blank">
something like:
p
{
display:inline;
}
in your stylesheet would do it for all p tags.
I've also had this happen (by accident) after creating a new venv while inside an existing virtual environment. an easy way to diagnose this would be to see where the python
is symlinked to, i.e. run:
ls -l venv/bin/python
and make sure it points to the appropriate Python binary. For most systems this will be /usr/bin/python
or /usr/bin/python3
. while if it points to an existing virtual environment it'll be something like /home/youruser/somedir/bin/python
. if it's the latter than I'd suggest recreating the venv while making sure that you aren't "inside" any existing virtualenv (i.e. run deactivate
)
jarsigner can use your pfx file as the keystore for signing your jar. Be sure that your pfx file has the private key and the cert chain when you export it. There is no need to convert to other formats. The trick is to obtain the Alias of your pfx file:
keytool -list -storetype pkcs12 -keystore your_pfx_file -v | grep Alias
Once you have your alias, signing is easy
jarsigner.exe -storetype pkcs12 -keystore pfx_file jar_file "your alias"
The above two commands will prompt you for the password you specified at pfx export. If you want to have your password hang out in clear text use the -storepass switch before the -keystore switch
Once signed, admire your work:
jarsigner.exe -verify -verbose -certs yourjarfile
In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
In case of entity framework FK in dependent must also be its PK so in your case you should use:
public class Boo
{
[Key, ForeignKey("Foo")]
public string BooId{get;set;}
public Foo Foo{get;set;}
}
Or fluent mapping
modelBuilder.Entity<Foo>()
.HasOptional(f => f.Boo)
.WithRequired(s => s.Foo);
You are just creating your array incorrectly. You could use http_build_query:
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
$fields_string = http_build_query($fields);
So, the entire code that you could use would be:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
Let the given array be A with length N. Lets assume in the given array, the single empty slot is filled with 0.
We can find the solution for this problem using many methods including algorithm used in Counting sort
. But, in terms of efficient time and space usage, we have two algorithms. One uses mainly summation, subtraction and multiplication. Another uses XOR. Mathematically both methods work fine. But programatically, we need to assess all the algorithms with main measures like
A[1...N]
) and/or number of
input values is large(N
))etc. This is because of the limitations in time and/or hardware(Hardware resource limitation) and/or software(Operating System limitation, Programming language limitation, etc), etc. Lets list and assess the pros and cons of each one of them.
In algorithm 1, we have 3 implementations.
Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2
). Here, N=100
. Calculate the total sum of all the given numbers. Subtract the second result from the first result will give the missing number.
Missing Number = (N(N+1))/2) - (A[1]+A[2]+...+A[100])
Calculate the total sum of all the numbers(this includes the unknown missing number) by using the mathematical formula(1+2+3+...+N=(N(N+1))/2
). Here, N=100
. From that result, subtract each given number gives the missing number.
Missing Number = (N(N+1))/2)-A[1]-A[2]-...-A[100]
(Note:
Even though the second implementation's formula is derived from first, from the mathematical point of view both are same. But from programming point of view both are different because the first formula is more prone to bit overflow than the second one(if the given numbers are large enough). Even though addition is faster than subtraction, the second implementation reduces the chance of bit overflow caused by addition of large values(Its not completely eliminated, because there is still very small chance since (N+1
) is there in the formula). But both are equally prone to bit overflow by multiplication. The limitation is both implementations give correct result only if N(N+1)<=MAXIMUM_NUMBER_VALUE
. For the first implementation, the additional limitation is it give correct result only if Sum of all given numbers<=MAXIMUM_NUMBER_VALUE
.)
Calculate the total sum of all the numbers(this includes the unknown missing number) and subtract each given number in the same loop in parallel. This eliminates the risk of bit overflow by multiplication but prone to bit overflow by addition and subtraction.
//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
missingNumber = missingNumber + index;
//Since, the empty slot is filled with 0,
//this extra condition which is executed for N times is not required.
//But for the sake of understanding of algorithm purpose lets put it.
if (inputArray[index] != 0)
missingNumber = missingNumber - inputArray[index];
}
In a programming language(like C, C++, Java, etc), if the number of bits representing a integer data type is limited, then all the above implementations are prone to bit overflow because of summation, subtraction and multiplication, resulting in wrong result in case of large input values(A[1...N]
) and/or large number of input values(N
).
We can use the property of XOR to get solution for this problem without worrying about the problem of bit overflow. And also XOR is both safer and faster than summation. We know the property of XOR that XOR of two same numbers is equal to 0(A XOR A = 0
). If we calculate the XOR of all the numbers from 1 to N(this includes the unknown missing number) and then with that result, XOR all the given numbers, the common numbers get canceled out(since A XOR A=0
) and in the end we get the missing number. If we don't have bit overflow problem, we can use both summation and XOR based algorithms to get the solution. But, the algorithm which uses XOR is both safer and faster than the algorithm which uses summation, subtraction and multiplication. And we can avoid the additional worries caused by summation, subtraction and multiplication.
In all the implementations of algorithm 1, we can use XOR instead of addition and subtraction.
Lets assume, XOR(1...N) = XOR of all numbers from 1 to N
Implementation 1 => Missing Number = XOR(1...N) XOR (A[1] XOR A[2] XOR...XOR A[100])
Implementation 2 => Missing Number = XOR(1...N) XOR A[1] XOR A[2] XOR...XOR A[100]
Implementation 3 =>
//ALGORITHM
missingNumber = 0;
foreach(index from 1 to N)
{
missingNumber = missingNumber XOR index;
//Since, the empty slot is filled with 0,
//this extra condition which is executed for N times is not required.
//But for the sake of understanding of algorithm purpose lets put it.
if (inputArray[index] != 0)
missingNumber = missingNumber XOR inputArray[index];
}
All three implementations of algorithm 2 will work fine(from programatical point of view also). One optimization is, similar to
1+2+....+N = (N(N+1))/2
We have,
1 XOR 2 XOR .... XOR N = {N if REMAINDER(N/4)=0, 1 if REMAINDER(N/4)=1, N+1 if REMAINDER(N/4)=2, 0 if REMAINDER(N/4)=3}
We can prove this by mathematical induction. So, instead of calculating the value of XOR(1...N) by XOR all the numbers from 1 to N, we can use this formula to reduce the number of XOR operations.
Also, calculating XOR(1...N) using above formula has two implementations. Implementation wise, calculating
// Thanks to https://a3nm.net/blog/xor.html for this implementation
xor = (n>>1)&1 ^ (((n&1)>0)?1:n)
is faster than calculating
xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;
So, the optimized Java code is,
long n = 100;
long a[] = new long[n];
//XOR of all numbers from 1 to n
// n%4 == 0 ---> n
// n%4 == 1 ---> 1
// n%4 == 2 ---> n + 1
// n%4 == 3 ---> 0
//Slower way of implementing the formula
// long xor = (n % 4 == 0) ? n : (n % 4 == 1) ? 1 : (n % 4 == 2) ? n + 1 : 0;
//Faster way of implementing the formula
// long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);
long xor = (n>>1)&1 ^ (((n&1)>0)?1:n);
for (long i = 0; i < n; i++)
{
xor = xor ^ a[i];
}
//Missing number
System.out.println(xor);
If you are running Ansible >= 2.0 there is also the dirname filter you can use to extract the directory part of a path. That way you can just use one variable to hold the entire path to make sure both tasks never get out of sync.
So for example if you have playbook with dest_path
defined in a variable like this you can reuse the same variable:
- name: My playbook
vars:
dest_path: /home/ubuntu/some_dir/some_file.txt
tasks:
- name: Make sure destination dir exists
file:
path: "{{ dest_path | dirname }}"
state: directory
recurse: yes
# now this task is always save to run no matter how dest_path get's changed arround
- name: Add file or template to remote instance
template:
src: foo.txt.j2
dest: "{{ dest_path }}"
preg_replace("/[[:blank:]]+/"," ",$input)
With me this error ocurred when I copied and pasted a code in text format to my editor (gedit). The code was in a text document (.odt) and I copied it and pasted it into gedit. If you did the same, you have manually rewrite the code.
You can use serializeArray
[docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
MapReduce is just a computing framework. HBase has nothing to do with it. That said, you can efficiently put or fetch data to/from HBase by writing MapReduce jobs. Alternatively you can write sequential programs using other HBase APIs, such as Java, to put or fetch the data. But we use Hadoop, HBase etc to deal with gigantic amounts of data, so that doesn't make much sense. Using normal sequential programs would be highly inefficient when your data is too huge.
Coming back to the first part of your question, Hadoop is basically 2 things: a Distributed FileSystem (HDFS) + a Computation or Processing framework (MapReduce). Like all other FS, HDFS also provides us storage, but in a fault tolerant manner with high throughput and lower risk of data loss (because of the replication). But, being a FS, HDFS lacks random read and write access. This is where HBase comes into picture. It's a distributed, scalable, big data store, modelled after Google's BigTable. It stores data as key/value pairs.
Coming to Hive. It provides us data warehousing facilities on top of an existing Hadoop cluster. Along with that it provides an SQL like interface which makes your work easier, in case you are coming from an SQL background. You can create tables in Hive and store data there. Along with that you can even map your existing HBase tables to Hive and operate on them.
While Pig is basically a dataflow language that allows us to process enormous amounts of data very easily and quickly. Pig basically has 2 parts: the Pig Interpreter and the language, PigLatin. You write Pig script in PigLatin and using Pig interpreter process them. Pig makes our life a lot easier, otherwise writing MapReduce is always not easy. In fact in some cases it can really become a pain.
I had written an article on a short comparison of different tools of the Hadoop ecosystem some time ago. It's not an in depth comparison, but a short intro to each of these tools which can help you to get started. (Just to add on to my answer. No self promotion intended)
Both Hive and Pig queries get converted into MapReduce jobs under the hood.
HTH
You may use closest()
in modern browsers:
var div = document.querySelector('div#myDiv');
div.closest('div[someAtrr]');
Use object detection to supply a polyfill or alternative method for backwards compatability with IE.
Essentially, PHPStorm = WebStorm + PHP, SQL and more.
BUT (and this is a very important "but") because it is capable of parsing so much more, it quite often fails to parse Node.js dependencies, as they (probably) conflict with some other syntax it is capable of parsing.
The most notable example of that would be Mongoose model definition, where WebStorm easily recognizes mongoose.model method, whereas PHPStorm marks it as unresolved as soon as you connect Node.js plugin.
Surprisingly, it manages to resolve the method if you turn the plugin off, but leave the core modules connected, but then it cannot be used for debugging. And this happens to quite a few methods out there.
All this goes for PHPStorm 8.0.1, maybe in later releases this annoying bug would be fixed.
Look at this method to see which fields are supported. You will find for LocalDateTime
:
•NANO_OF_SECOND
•NANO_OF_DAY
•MICRO_OF_SECOND
•MICRO_OF_DAY
•MILLI_OF_SECOND
•MILLI_OF_DAY
•SECOND_OF_MINUTE
•SECOND_OF_DAY
•MINUTE_OF_HOUR
•MINUTE_OF_DAY
•HOUR_OF_AMPM
•CLOCK_HOUR_OF_AMPM
•HOUR_OF_DAY
•CLOCK_HOUR_OF_DAY
•AMPM_OF_DAY
•DAY_OF_WEEK
•ALIGNED_DAY_OF_WEEK_IN_MONTH
•ALIGNED_DAY_OF_WEEK_IN_YEAR
•DAY_OF_MONTH
•DAY_OF_YEAR
•EPOCH_DAY
•ALIGNED_WEEK_OF_MONTH
•ALIGNED_WEEK_OF_YEAR
•MONTH_OF_YEAR
•PROLEPTIC_MONTH
•YEAR_OF_ERA
•YEAR
•ERA
The field INSTANT_SECONDS is - of course - not supported because a LocalDateTime
cannot refer to any absolute (global) timestamp. But what is helpful is the field EPOCH_DAY which counts the elapsed days since 1970-01-01. Similar thoughts are valid for the type LocalDate
(with even less supported fields).
If you intend to get the non-existing millis-since-unix-epoch field you also need the timezone for converting from a local to a global type. This conversion can be done much simpler, see other SO-posts.
Coming back to your question and the numbers in your code:
The result 1605 is correct
=> (2014 - 1970) * 365 + 11 (leap days) + 31 (in january 2014) + 3 (in february 2014)
The result 71461 is also correct => 19 * 3600 + 51 * 60 + 1
16105L * 86400 + 71461 = 1391543461 seconds since 1970-01-01T00:00:00 (attention, no timezone) Then you can subtract the timezone offset (watch out for possible multiplication by 1000 if in milliseconds).
UPDATE after given timezone info:
local time = 1391543461 secs
offset = 3600 secs (Europe/Oslo, winter time in february)
utc = 1391543461 - 3600 = 1391539861
As JSR-310-code with two equivalent approaches:
long secondsSinceUnixEpoch1 =
LocalDateTime.of(2014, 2, 4, 19, 51, 1).atZone(ZoneId.of("Europe/Oslo")).toEpochSecond();
long secondsSinceUnixEpoch2 =
LocalDate
.of(2014, 2, 4)
.atTime(19, 51, 1)
.atZone(ZoneId.of("Europe/Oslo"))
.toEpochSecond();
You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py
in the same directory.
Try this:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);
Note that you can also tell logback to periodically scan your config file like this:
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:
You cannot use AppSettings static object for this. Try this
string appPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location);
string configFile = System.IO.Path.Combine(appPath, "App.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["YourThing"].Value = "New Value";
config.Save();
If you want to fully copy properties of an object in a different instance, you may want to use this technique:
Serialize it to JSON and then de-serialize it back to Object.
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
One of the possible implementations:
File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();
when used with the XML content:
<credentials>
<user>testusr</user>
<password>testpwd</password>
</credentials>
results in "testusr"
and "testpwd"
getting assigned to the usr
and pwd
references above.
^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$
should reflect what people usually think of as a well formed decimal number.
The digits before the decimal point can be either a single digit, in which case it can be from 0 to 9, or more than one digits, in which case it cannot start with a 0.
If there are any digits present before the decimal sign, then the decimal and the digits following it are optional. Otherwise, a decimal has to be present followed by at least one digit. Note that multiple trailing 0's are allowed after the decimal point.
grep -E '^[+-]?(([1-9][0-9]*)?[0-9](\.[0-9]*)?|\.[0-9]+)$'
correctly matches the following:
9
0
10
10.
0.
0.0
0.100
0.10
0.01
10.0
10.10
.0
.1
.00
.100
.001
as well as their signed equivalents, whereas it rejects the following:
.
00
01
00.0
01.3
and their signed equivalents, as well as the empty string.
This is Objective-C version of dadachi's Answer :
- (void)didMoveToParentViewController:(UIViewController *)parent{
if (parent == NULL) {
NSLog(@"Back Pressed");
}
}
Maybe this is what you need...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* LogToFile class
* This class is intended to be use with the default logging class of java
* It save the log in an XML file and display a friendly message to the user
* @author Ibrabel <[email protected]>
*/
public class LogToFile {
protected static final Logger logger=Logger.getLogger("MYLOG");
/**
* log Method
* enable to log all exceptions to a file and display user message on demand
* @param ex
* @param level
* @param msg
*/
public static void log(Exception ex, String level, String msg){
FileHandler fh = null;
try {
fh = new FileHandler("log.xml",true);
logger.addHandler(fh);
switch (level) {
case "severe":
logger.log(Level.SEVERE, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Error", JOptionPane.ERROR_MESSAGE);
break;
case "warning":
logger.log(Level.WARNING, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Warning", JOptionPane.WARNING_MESSAGE);
break;
case "info":
logger.log(Level.INFO, msg, ex);
if(!msg.equals(""))
JOptionPane.showMessageDialog(null,msg,
"Info", JOptionPane.INFORMATION_MESSAGE);
break;
case "config":
logger.log(Level.CONFIG, msg, ex);
break;
case "fine":
logger.log(Level.FINE, msg, ex);
break;
case "finer":
logger.log(Level.FINER, msg, ex);
break;
case "finest":
logger.log(Level.FINEST, msg, ex);
break;
default:
logger.log(Level.CONFIG, msg, ex);
break;
}
} catch (IOException | SecurityException ex1) {
logger.log(Level.SEVERE, null, ex1);
} finally{
if(fh!=null)fh.close();
}
}
public static void main(String[] args) {
/*
Create simple frame for the example
*/
JFrame myFrame = new JFrame();
myFrame.setTitle("LogToFileExample");
myFrame.setSize(300, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
JPanel pan = new JPanel();
JButton severe = new JButton("severe");
pan.add(severe);
JButton warning = new JButton("warning");
pan.add(warning);
JButton info = new JButton("info");
pan.add(info);
/*
Create an exception on click to use the LogToFile class
*/
severe.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"severe","You can't divide anything by zero");
}
}
});
warning.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"warning","You can't divide anything by zero");
}
}
});
info.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae) {
int j = 20, i = 0;
try {
System.out.println(j/i);
} catch (ArithmeticException ex) {
log(ex,"info","You can't divide anything by zero");
}
}
});
/*
Add the JPanel to the JFrame and set the JFrame visible
*/
myFrame.setContentPane(pan);
myFrame.setVisible(true);
}
}
Here's another answer that has an option to append decimal ONLY IF decimal was not zero.
/**
* Example: (isDecimalRequired = true)
* d = 12345
* returns 12,345.00
*
* d = 12345.12345
* returns 12,345.12
*
* ==================================================
* Example: (isDecimalRequired = false)
* d = 12345
* returns 12,345 (notice that there's no decimal since it's zero)
*
* d = 12345.12345
* returns 12,345.12
*
* @param d float to format
* @param zeroCount number decimal places
* @param isDecimalRequired true if it will put decimal even zero,
* false will remove the last decimal(s) if zero.
*/
fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
val zeros = StringBuilder()
for (i in 0 until zeroCount) {
zeros.append("0")
}
var pattern = "#,##0"
if (zeros.isNotEmpty()) {
pattern += ".$zeros"
}
val numberFormat = DecimalFormat(pattern)
var formattedNumber = if (d != null) numberFormat.format(d) else "0"
if (!isDecimalRequired) {
for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
val number = formattedNumber[i - 1]
if (number == '0' || number == '.') {
formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
} else {
break
}
}
}
return formattedNumber
}
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
Here is a little lib to load javascript and CSS files dynamically:
https://github.com/todotresde/javascript-loader
I guess is usefull to load css and js files in order and dynamically.
Support to extend to load any lib you want, and not just the main file, you can use it to load custom files.
I.E.:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="scripts/javascript-loader.js" type="text/javascript" charset="utf-8" ></script>
<script type="text/javascript">
$(function() {
registerLib("threejs", test);
function test(){
console.log(THREE);
}
registerLib("tinymce", draw);
function draw(){
tinymce.init({selector:'textarea'});
}
});
</script>
</head>
<body>
<textarea>Your content here.</textarea>
</body>
You can also load the content with cURL, if file_get_contents insn't enabled on your server.
Example:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$items = simplexml_load_string($output);
PHP sends headers automatically if set up to use internal encoding:
ini_set('default_charset', 'utf-8');
I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...
For example in order to change it's background to yellow:
$("#"+String(this.id)).css("background-color","yellow");
With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');
Disabling all other options in authentication tab of iis except windows authentication resolved my issue. Please check..
Steps:
Please check this and let me know the feedback. It worked for me. hope it will work for you also..
In addition to above points, it would be good to know that:
This works for me.
select * from tablename
order by cast(columnname as int) asc
$session_data = array('username' =>"shashikant");
$this->session->set_userdata('logged_in', $session_data);
$this->session->unset_userdata('logged_in');
something like this ??
pretty-json
https://github.com/warfares/pretty-json
live sample:
myApp.directive("clickme",function(){
return function(scope,element,attrs){
element.bind("mousedown",function(){
<<call the Controller function>>
scope.loadEditfrm(attrs.edtbtn);
});
};
});
this will act as onclick events on the attribute clickme
Try using os.system
:
os.system("script2.py 1")
execfile
is different because it is designed to run a sequence of Python statements in the current execution context. That's why sys.argv
didn't change for you.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
Have you tried an approach like on this link? I'm not sure if createValueBinding()
is still available but code like this should be accessible from a plain old Servlet. This does require to bean to already exist.
http://www.coderanch.com/t/211706/JSF/java/access-managed-bean-JSF-from
FacesContext context = FacesContext.getCurrentInstance();
Application app = context.getApplication();
// May be deprecated
ValueBinding binding = app.createValueBinding("#{" + expr + "}");
Object value = binding.getValue(context);
You created the UIButton
is added the ViewController
, The following instance method to change UIFont
, tintColor
and TextColor
of the UIButton
Objective-C
buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
buttonName.tintColor = [UIColor purpleColor];
[buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
Swift
buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
Swift3
buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)
As in Accepted post, the problem solved with updating gradle to 4.4.1.
My Problem solved this way.
On click it can be done using below code
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').slideToggle(500);
});
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose
You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.
What that means? You must be knowing by now that the following assignment is valid:
Object[] arr = new String[10];
Basically, an Object[]
is a super type of String[]
, because Object
is a super type of String
. This is not true with generics. So, the following declaration is not valid, and won't compile:
List<Object> list = new ArrayList<String>(); // Will not compile.
Reason being, generics are invariant.
Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String>
has a static type of List<String>
but a dynamic type of List
.
However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:
Object[] arr = new String[10];
arr[0] = new Integer(10);
will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.
Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.
Consider the code as below:
public <T> T[] getArray(int size) {
T[] arr = new T[size]; // Suppose this was allowed for the time being.
return arr;
}
Since the type of T
is not known at runtime, the array created is actually an Object[]
. So the above method at runtime will look like:
public Object[] getArray(int size) {
Object[] arr = new Object[size];
return arr;
}
Now, suppose you call this method as:
Integer[] arr = getArray(10);
Here's the problem. You have just assigned an Object[]
to a reference of Integer[]
. The above code will compile fine, but will fail at runtime.
That is why generic array creation is forbidden.
new Object[10]
to E[]
works?Now your last doubt, why the below code works:
E[] elements = (E[]) new Object[10];
The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:
public <T> T[] getArray(int size) {
T[] arr = (T[])new Object[size];
return arr;
}
and you call invoke it like this:
String[] arr = getArray(10);
this will fail at runtime with a ClassCastException. So, no this way will not work always.
List<String>[]
?The issue is the same. Due to type erasure, a List<String>[]
is nothing but a List[]
. So, had the creation of such arrays allowed, let's see what could happen:
List<String>[] strlistarr = new List<String>[10]; // Won't compile. but just consider it
Object[] objarr = strlistarr; // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.
Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[]
and List<Integer>[]
are compiled to List[]
at runtime.
Yes. The reason being, a List<?>
is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.
List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>(); // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine
Both the above case is fine, because List<?>
is super type of all the instantiation of the generic type List<E>
. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[]
.
So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new
operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null
(Ignoring the unbounded types).
E[]
?Yes, you can create the array using Array#newInstance()
method:
public <E> E[] getArray(Class<E> clazz, int size) {
@SuppressWarnings("unchecked")
E[] arr = (E[]) Array.newInstance(clazz, size);
return arr;
}
Typecast is needed because that method returns an Object
. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.
create or replace procedure point_triangle
AS
BEGIN
FOR thisteam in (select FIRSTNAME,LASTNAME,SUM(PTS) from PLAYERREGULARSEASON where TEAM = 'IND' group by FIRSTNAME, LASTNAME order by SUM(PTS) DESC)
LOOP
dbms_output.put_line(thisteam.FIRSTNAME|| ' ' || thisteam.LASTNAME || ':' || thisteam.PTS);
END LOOP;
END;
/
Receiving a status 429 is not an error, it is the other server "kindly" asking you to please stop spamming requests. Obviously, your rate of requests has been too high and the server is not willing to accept this.
You should not seek to "dodge" this, or even try to circumvent server security settings by trying to spoof your IP, you should simply respect the server's answer by not sending too many requests.
If everything is set up properly, you will also have received a "Retry-after" header along with the 429 response. This header specifies the number of seconds you should wait before making another call. The proper way to deal with this "problem" is to read this header and to sleep your process for that many seconds.
You can find more information on status 429 here: http://tools.ietf.org/html/rfc6585#page-3
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
After close examining, not 300k lines but there are around 3-4 CSS properties that you need to override:
.navbar-collapse.collapse {
display: block!important;
}
.navbar-nav>li, .navbar-nav {
float: left !important;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px !important;
}
.navbar-right {
float: right!important;
}
And with this your menu won't collapse.
EXPLANATION
The four CSS properties do the respective:
The default .collapse
property in bootstrap hides the right-side of the menu for tablets(landscape) and phones and instead a toggle button is displayed to hide/show it. Thus this property overrides the default and persistently shows those elements.
For the right-side menu to appear on the same line along with the left-side, we need the left-side to be floating left.
This property is present by default in bootstrap but not on tablet(portrait) to phone resolution. You can skip this one, it's likely to not affect your overall navbar.
This keeps the right-side menu to the right while the inner elements (li
) will follow the property 2. So we have left-side float left and right-side float right which brings them into one line.
I'm sure you are using a old version. You must use the last version available at master branch:
Download the code from github into the node_modules directory
var moduleName = require("<name of directory>")
that should do it.
if the module has dependancies and has a package.json, open the module and enter npm install.
Hope this helps
Maybe it is not what you are looking for, but I had a similar problem and i solved it including JSON 2 to my application:
https://github.com/douglascrockford/JSON-js
Other browsers natively implements JSON but IE < 8 (also IE 8 compatibility mode) does not, that's why you need to include it.
Here is a related question: JSON on IE6 (IE7)
UPDATE
the JSON parser has been updated so you should use the new one: http://bestiejs.github.io/json3/
Keepin' it simple:
// Find the index of the first element in array
// meeting specified condition.
//
var findIndex = function(arr, cond) {
var i, x;
for (i in arr) {
x = arr[i];
if (cond(x)) return parseInt(i);
}
};
var idIsTwo = function(x) { return x.id == 2 }
var tv = [ {id: 1}, {id: 2} ]
var i = findIndex(tv, idIsTwo) // 1
Or, for non-haters, the CoffeeScript variant:
findIndex = (arr, cond) ->
for i, x of arr
return parseInt(i) if cond(x)
The above answer by pl_rock is correct, the only thing I would add is to expect the ARG inside the Dockerfile if not you won't have access to it. So if you are doing
docker build -t essearch/ess-elasticsearch:1.7.6 --build-arg number_of_shards=5 --build-arg number_of_replicas=2 --no-cache .
Then inside the Dockerfile you should add
ARG number_of_replicas
ARG number_of_shards
I was running into this problem, so I hope I help someone (myself) in the future.
It might me a little late and a little lazy and a little boring or a little intrusive or a little like "back of, bigmouth", but...
Each and any solution I've read so far would be like "let's get to sleep and look what happened, tomorrow".
setInterval(callback, time) would wait time long and then call the callback, WHILE blocking the runtime. The current implementation of "setInterval" is far from being thread-save, not even to mind concurrency.
While the sparse solutions mentioned look like, guess what, C# (laughs), they still don't work like in C#/.NET. They still work like in C.
JavaScript currently does NOT provide an architecture to accomplish real multi-threading. The best approach would be TypeScript, but still this lacks so much of a real solution that it... hurts. JavaScript, and jQuery, and AJAX, and jNode, and even TypeScript are just a bunch of Wannabes relying on the goods and bads of the moods of the implementors. Fact. Full stop.
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...
Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle
class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.
The IDisposable
interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.
Note that if you have a finalizer then you should also implement the IDisposable
interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.
See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable
.
The proper test is:
if (capital != null && capital.length < 1) {
This ensures that capital
is always non null, when you perform the length check.
Also, as the comments suggest, capital
is null
because you never initialize it.
These are present by default as rownames
when you create a data.frame
.
R> df = data.frame('a' = rnorm(10), 'b' = runif(10), 'c' = letters[1:10])
R> df
a b c
1 0.3336944 0.39746731 a
2 -0.2334404 0.12242856 b
3 1.4886706 0.07984085 c
4 -1.4853724 0.83163342 d
5 0.7291344 0.10981827 e
6 0.1786753 0.47401690 f
7 -0.9173701 0.73992239 g
8 0.7805941 0.91925413 h
9 0.2469860 0.87979229 i
10 1.2810961 0.53289335 j
and you can access them via the rownames
command.
R> rownames(df)
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
if you need them as numbers, simply coerce to numeric by adding as.numeric
, as in as.numeric(rownames(df))
.
You don't need to add them, as if you know what you are looking for (say item df$c == 'i'
, you can use the which command:
R> which(df$c =='i')
[1] 9
or if you don't know the column
R> which(df == 'i', arr.ind=T)
row col
[1,] 9 3
you may access the element using df[9, 'c']
, or df$c[9]
.
If you wanted to add them you could use df$rownumber <- as.numeric(rownames(df))
, though this may be less robust than df$rownumber <- 1:nrow(df)
as there are cases when you might have assigned to rownames
so they will no longer be the default index numbers (the which command will continue to return index numbers even if you do assign to rownames
).
To use getSingleResult on a TypedQuery you can use
query.setFirstResult(0);
query.setMaxResults(1);
result = query.getSingleResult();
Did you read https://software.intel.com/en-us/blogs/2014/03/14/troubleshooting-intel-haxm?
It says "Make sure "Hyper-V", a Windows feature, is not installed/enabled on your system. Hyper-V captures the VT virtualization capability of the CPU, and HAXM and Hyper-V cannot run at the same time. Read this blog: Creating a "no hypervisor" boot entry." https://blogs.msdn.microsoft.com/virtual_pc_guy/2008/04/14/creating-a-no-hypervisor-boot-entry/
I've created the boot entry that disables HyperV and it's working
You can't pass a parameter in a @selector().
It looks like you're trying to implement a callback. The best way to do that would be something like this:
[object setCallbackObject:self withSelector:@selector(myMethod:)];
Then in your object's setCallbackObject:withSelector: method: you can call your callback method.
-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
[anObject performSelector:selector];
}
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
timeleft--;_x000D_
document.getElementById("countdowntimer").textContent = timeleft;_x000D_
if(timeleft <= 0)_x000D_
clearInterval(downloadTimer);_x000D_
},1000);_x000D_
</script>
_x000D_
Use grep -n
to get the line number of a match.
I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:
sed -n '10,$ { /regex/ { =; p; } }' file
To get only the line numbers, you could use
grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'
Or you could simply use sed:
sed -n '/regex/=' file
Combining the two sed commands, you get:
sed -n '10,$ { /regex/= }' file
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
How about:
let myString = "12345.00";_x000D_
console.log(myString.substring(0, myString.length - 1));
_x000D_
Let me try to state the different viable modes of passing pointers around to objects whose memory is managed by an instance of the std::unique_ptr
class template; it also applies to the the older std::auto_ptr
class template (which I believe allows all uses that unique pointer does, but for which in addition modifiable lvalues will be accepted where rvalues are expected, without having to invoke std::move
), and to some extent also to std::shared_ptr
.
As a concrete example for the discussion I will consider the following simple list type
struct node;
typedef std::unique_ptr<node> list;
struct node { int entry; list next; }
Instances of such list (which cannot be allowed to share parts with other instances or be circular) are entirely owned by whoever holds the initial list
pointer. If client code knows that the list it stores will never be empty, it may also choose to store the first node
directly rather than a list
.
No destructor for node
needs to be defined: since the destructors for its fields are automatically called, the whole list will be recursively deleted by the smart pointer destructor once the lifetime of initial pointer or node ends.
This recursive type gives the occasion to discuss some cases that are less visible in the case of a smart pointer to plain data. Also the functions themselves occasionally provide (recursively) an example of client code as well. The typedef for list
is of course biased towards unique_ptr
, but the definition could be changed to use auto_ptr
or shared_ptr
instead without much need to change to what is said below (notably concerning exception safety being assured without the need to write destructors).
If your function is not concerned with ownership, this is the preferred method: don't make it take a smart pointer at all. In this case your function does not need to worry who owns the object pointed to, or by what means that ownership is managed, so passing a raw pointer is both perfectly safe, and the most flexible form, since regardless of ownership a client can always produce a raw pointer (either by calling the get
method or from the address-of operator &
).
For instance the function to compute the length of such list, should not be give a list
argument, but a raw pointer:
size_t length(const node* p)
{ size_t l=0; for ( ; p!=nullptr; p=p->next.get()) ++l; return l; }
A client that holds a variable list head
can call this function as length(head.get())
,
while a client that has chosen instead to store a node n
representing a non-empty list can call length(&n)
.
If the pointer is guaranteed to be non null (which is not the case here since lists may be empty) one might prefer to pass a reference rather than a pointer. It might be a pointer/reference to non-const
if the function needs to update the contents of the node(s), without adding or removing any of them (the latter would involve ownership).
An interesting case that falls in the mode 0 category is making a (deep) copy of the list; while a function doing this must of course transfer ownership of the copy it creates, it is not concerned with the ownership of the list it is copying. So it could be defined as follows:
list copy(const node* p)
{ return list( p==nullptr ? nullptr : new node{p->entry,copy(p->next.get())} ); }
This code merits a close look, both for the question as to why it compiles at all (the result of the recursive call to copy
in the initialiser list binds to the rvalue reference argument in the move constructor of unique_ptr<node>
, a.k.a. list
, when initialising the next
field of the generated node
), and for the question as to why it is exception-safe (if during the recursive allocation process memory runs out and some call of new
throws std::bad_alloc
, then at that time a pointer to the partly constructed list is held anonymously in a temporary of type list
created for the initialiser list, and its destructor will clean up that partial list). By the way one should resist the temptation to replace (as I initially did) the second nullptr
by p
, which after all is known to be null at that point: one cannot construct a smart pointer from a (raw) pointer to constant, even when it is known to be null.
A function that takes a smart pointer value as argument takes possession of the object pointed to right away: the smart pointer that the caller held (whether in a named variable or an anonymous temporary) is copied into the argument value at function entrance and the caller's pointer has become null (in the case of a temporary the copy might have been elided, but in any case the caller has lost access to the pointed to object). I would like to call this mode call by cash: caller pays up front for the service called, and can have no illusions about ownership after the call. To make this clear, the language rules require the caller to wrap the argument in std::move
if the smart pointer is held in a variable (technically, if the argument is an lvalue); in this case (but not for mode 3 below) this function does what its name suggests, namely move the value from the variable to a temporary, leaving the variable null.
For cases where the called function unconditionally takes ownership of (pilfers) the pointed-to object, this mode used with std::unique_ptr
or std::auto_ptr
is a good way of passing a pointer together with its ownership, which avoids any risk of memory leaks. Nonetheless I think that there are only very few situations where mode 3 below is not to be preferred (ever so slightly) over mode 1. For this reason I shall provide no usage examples of this mode. (But see the reversed
example of mode 3 below, where it is remarked that mode 1 would do at least as well.) If the function takes more arguments than just this pointer, it may happen that there is in addition a technical reason to avoid mode 1 (with std::unique_ptr
or std::auto_ptr
): since an actual move operation takes place while passing a pointer variable p
by the expression std::move(p)
, it cannot be assumed that p
holds a useful value while evaluating the other arguments (the order of evaluation being unspecified), which could lead to subtle errors; by contrast, using mode 3 assures that no move from p
takes place before the function call, so other arguments can safely access a value through p
.
When used with std::shared_ptr
, this mode is interesting in that with a single function definition it allows the caller to choose whether to keep a sharing copy of the pointer for itself while creating a new sharing copy to be used by the function (this happens when an lvalue argument is provided; the copy constructor for shared pointers used at the call increases the reference count), or to just give the function a copy of the pointer without retaining one or touching the reference count (this happens when a rvalue argument is provided, possibly an lvalue wrapped in a call of std::move
). For instance
void f(std::shared_ptr<X> x) // call by shared cash
{ container.insert(std::move(x)); } // store shared pointer in container
void client()
{ std::shared_ptr<X> p = std::make_shared<X>(args);
f(p); // lvalue argument; store pointer in container but keep a copy
f(std::make_shared<X>(args)); // prvalue argument; fresh pointer is just stored away
f(std::move(p)); // xvalue argument; p is transferred to container and left null
}
The same could be achieved by separately defining void f(const std::shared_ptr<X>& x)
(for the lvalue case) and void f(std::shared_ptr<X>&& x)
(for the rvalue case), with function bodies differing only in that the first version invokes copy semantics (using copy construction/assignment when using x
) but the second version move semantics (writing std::move(x)
instead, as in the example code). So for shared pointers, mode 1 can be useful to avoid some code duplication.
Here the function just requires having a modifiable reference to the smart pointer, but gives no indication of what it will do with it. I would like to call this method call by card: caller ensures payment by giving a credit card number. The reference can be used to take ownership of the pointed-to object, but it does not have to. This mode requires providing a modifiable lvalue argument, corresponding to the fact that the desired effect of the function may include leaving a useful value in the argument variable. A caller with an rvalue expression that it wishes to pass to such a function would be forced to store it in a named variable to be able to make the call, since the language only provides implicit conversion to a constant lvalue reference (referring to a temporary) from an rvalue. (Unlike the opposite situation handled by std::move
, a cast from Y&&
to Y&
, with Y
the smart pointer type, is not possible; nonetheless this conversion could be obtained by a simple template function if really desired; see https://stackoverflow.com/a/24868376/1436796). For the case where the called function intends to unconditionally take ownership of the object, stealing from the argument, the obligation to provide an lvalue argument is giving the wrong signal: the variable will have no useful value after the call. Therefore mode 3, which gives identical possibilities inside our function but asks callers to provide an rvalue, should be preferred for such usage.
However there is a valid use case for mode 2, namely functions that may modify the pointer, or the object pointed to in a way that involves ownership. For instance, a function that prefixes a node to a list
provides an example of such use:
void prepend (int x, list& l) { l = list( new node{ x, std::move(l)} ); }
Clearly it would be undesirable here to force callers to use std::move
, since their smart pointer still owns a well defined and non-empty list after the call, though a different one than before.
Again it is interesting to observe what happens if the prepend
call fails for lack of free memory. Then the new
call will throw std::bad_alloc
; at this point in time, since no node
could be allocated, it is certain that the passed rvalue reference (mode 3) from std::move(l)
cannot yet have been pilfered, as that would be done to construct the next
field of the node
that failed to be allocated. So the original smart pointer l
still holds the original list when the error is thrown; that list will either be properly destroyed by the smart pointer destructor, or in case l
should survive thanks to a sufficiently early catch
clause, it will still hold the original list.
That was a constructive example; with a wink to this question one can also give the more destructive example of removing the first node containing a given value, if any:
void remove_first(int x, list& l)
{ list* p = &l;
while ((*p).get()!=nullptr and (*p)->entry!=x)
p = &(*p)->next;
if ((*p).get()!=nullptr)
(*p).reset((*p)->next.release()); // or equivalent: *p = std::move((*p)->next);
}
Again the correctness is quite subtle here. Notably, in the final statement the pointer (*p)->next
held inside the node to be removed is unlinked (by release
, which returns the pointer but makes the original null) before reset
(implicitly) destroys that node (when it destroys the old value held by p
), ensuring that one and only one node is destroyed at that time. (In the alternative form mentioned in the comment, this timing would be left to the internals of the implementation of the move-assignment operator of the std::unique_ptr
instance list
; the standard says 20.7.1.2.3;2 that this operator should act "as if by calling reset(u.release())
", whence the timing should be safe here too.)
Note that prepend
and remove_first
cannot be called by clients who store a local node
variable for an always non-empty list, and rightly so since the implementations given could not work for such cases.
This is the preferred mode to use when simply taking ownership of the pointer. I would like to call this method call by check: caller must accept relinquishing ownership, as if providing cash, by signing the check, but the actual withdrawal is postponed until the called function actually pilfers the pointer (exactly as it would when using mode 2). The "signing of the check" concretely means callers have to wrap an argument in std::move
(as in mode 1) if it is an lvalue (if it is an rvalue, the "giving up ownership" part is obvious and requires no separate code).
Note that technically mode 3 behaves exactly as mode 2, so the called function does not have to assume ownership; however I would insist that if there is any uncertainty about ownership transfer (in normal usage), mode 2 should be preferred to mode 3, so that using mode 3 is implicitly a signal to callers that they are giving up ownership. One might retort that only mode 1 argument passing really signals forced loss of ownership to callers. But if a client has any doubts about intentions of the called function, she is supposed to know the specifications of the function being called, which should remove any doubt.
It is surprisingly difficult to find a typical example involving our list
type that uses mode 3 argument passing. Moving a list b
to the end of another list a
is a typical example; however a
(which survives and holds the result of the operation) is better passed using mode 2:
void append (list& a, list&& b)
{ list* p=&a;
while ((*p).get()!=nullptr) // find end of list a
p=&(*p)->next;
*p = std::move(b); // attach b; the variable b relinquishes ownership here
}
A pure example of mode 3 argument passing is the following that takes a list (and its ownership), and returns a list containing the identical nodes in reverse order.
list reversed (list&& l) noexcept // pilfering reversal of list
{ list p(l.release()); // move list into temporary for traversal
list result(nullptr);
while (p.get()!=nullptr)
{ // permute: result --> p->next --> p --> (cycle to result)
result.swap(p->next);
result.swap(p);
}
return result;
}
This function might be called as in l = reversed(std::move(l));
to reverse the list into itself, but the reversed list can also be used differently.
Here the argument is immediately moved to a local variable for efficiency (one could have used the parameter l
directly in the place of p
, but then accessing it each time would involve an extra level of indirection); hence the difference with mode 1 argument passing is minimal. In fact using that mode, the argument could have served directly as local variable, thus avoiding that initial move; this is just an instance of the general principle that if an argument passed by reference only serves to initialise a local variable, one might just as well pass it by value instead and use the parameter as local variable.
Using mode 3 appears to be advocated by the standard, as witnessed by the fact that all provided library functions that transfer ownership of smart pointers using mode 3. A particular convincing case in point is the constructor std::shared_ptr<T>(auto_ptr<T>&& p)
. That constructor used (in std::tr1
) to take a modifiable lvalue reference (just like the auto_ptr<T>&
copy constructor), and could therefore be called with an auto_ptr<T>
lvalue p
as in std::shared_ptr<T> q(p)
, after which p
has been reset to null. Due to the change from mode 2 to 3 in argument passing, this old code must now be rewritten to std::shared_ptr<T> q(std::move(p))
and will then continue to work. I understand that the committee did not like the mode 2 here, but they had the option of changing to mode 1, by defining std::shared_ptr<T>(auto_ptr<T> p)
instead, they could have ensured that old code works without modification, because (unlike unique-pointers) auto-pointers can be silently dereferenced to a value (the pointer object itself being reset to null in the process). Apparently the committee so much preferred advocating mode 3 over mode 1, that they chose to actively break existing code rather than to use mode 1 even for an already deprecated usage.
Mode 1 is perfectly usable in many cases, and might be preferred over mode 3 in cases where assuming ownership would otherwise takes the form of moving the smart pointer to a local variable as in the reversed
example above. However, I can see two reasons to prefer mode 3 in the more general case:
It is slightly more efficient to pass a reference than to create a temporary and nix the old pointer (handling cash is somewhat laborious); in some scenarios the pointer may be passed several times unchanged to another function before it is actually pilfered. Such passing will generally require writing std::move
(unless mode 2 is used), but note that this is just a cast that does not actually do anything (in particular no dereferencing), so it has zero cost attached.
Should it be conceivable that anything throws an exception between the start of the function call and the point where it (or some contained call) actually moves the pointed-to object into another data structure (and this exception is not already caught inside the function itself), then when using mode 1, the object referred to by the smart pointer will be destroyed before a catch
clause can handle the exception (because the function parameter was destructed during stack unwinding), but not so when using mode 3. The latter gives the caller has the option to recover the data of the object in such cases (by catching the exception). Note that mode 1 here does not cause a memory leak, but may lead to an unrecoverable loss of data for the program, which might be undesirable as well.
To conclude a word about returning a smart pointer, presumably pointing to an object created for use by the caller. This is not really a case comparable with passing pointers into functions, but for completeness I would like to insist that in such cases always return by value (and don't use std::move
in the return
statement). Nobody wants to get a reference to a pointer that probably has just been nixed.
Bitbucket supports a REST API you can use to programmatically create Bitbucket repositories.
Documentation and cURL sample available here: https://confluence.atlassian.com/bitbucket/repository-resource-423626331.html#repositoryResource-POSTanewrepository
$ curl -X POST -v -u username:password -H "Content-Type: application/json" \
https://api.bitbucket.org/2.0/repositories/teamsinspace/new-repository4 \
-d '{"scm": "git", "is_private": "true", "fork_policy": "no_public_forks" }'
Under Windows, curl is available from the Git Bash shell.
Using this method you could easily create a script to import many repos from a local git server to Bitbucket.
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
forEach: If you want to perform an action on the elements of an Array and it is same as you use for loop. The result of this method does not give us an output buy just loop through the elements.
map: If you want to perform an action on the elements of an array and also you want to store the output of your action into an Array. This is similar to for loop within a function that returns the result after each iteration.
Hope this helps.
the core functions are getBytes(String charset)
and new String(byte[] data)
. you can use these functions to do UTF-8 decoding.
UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String()
is the byte array, which calling is equal to new String(bytes, "UTF-8")
Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.
The decoding sentence should be
String decoded = new String(encoded.getBytes("ISO-8859-1"));
One crucial thing to remember for those working with a Console application to host the WCF service is that the Web.config file in the WCF project is completely ignored. If your system.serviceModel
configuration is there, then you need to move that section of config to the App.config of your Console project.
This is in addition to the answers concerning ensuring the namespace is specified in the right places.
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
Sometimes it happens because of the version change like store 2012 db on 2008, so how to check it?
RESTORE VERIFYONLY FROM DISK = N'd:\yourbackup.bak'
if it gives error like:
Msg 3241, Level 16, State 13, Line 2 The media family on device 'd:\alibaba.bak' is incorrectly formed. SQL Server cannot process this media family. Msg 3013, Level 16, State 1, Line 2 VERIFY DATABASE is terminating abnormally.
Check it further:
RESTORE HEADERONLY FROM DISK = N'd:\yourbackup.bak'
BackupName is "* INCOMPLETE *", Position is "1", other fields are "NULL".
Means either your backup is corrupt or taken from newer version.
NOTE: Using set_fact
as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.
Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.
Use set_fact
before your task to set facts which seem interchangeable with variables:
- name: Set Apache URL
set_fact:
apache_url: 'http://example.com/apache'
- name: Download Apache
shell: wget {{ apache_url }}
See http://docs.ansible.com/set_fact_module.html for the official word.
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
The simplest approach is to use ExecutorService.invokeAll()
which does what you want in a one-liner. In your parlance, you'll need to modify or wrap ComputeDTask
to implement Callable<>
, which can give you quite a bit more flexibility. Probably in your app there is a meaningful implementation of Callable.call()
, but here's a way to wrap it if not using Executors.callable()
.
ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> todo = new ArrayList<Callable<Object>>(singleTable.size());
for (DataTable singleTable: uniquePhrases) {
todo.add(Executors.callable(new ComputeDTask(singleTable)));
}
List<Future<Object>> answers = es.invokeAll(todo);
As others have pointed out, you could use the timeout version of invokeAll()
if appropriate. In this example, answers
is going to contain a bunch of Future
s which will return nulls (see definition of Executors.callable()
. Probably what you want to do is a slight refactoring so you can get a useful answer back, or a reference to the underlying ComputeDTask
, but I can't tell from your example.
If it isn't clear, note that invokeAll()
will not return until all the tasks are completed. (i.e., all the Future
s in your answers
collection will report .isDone()
if asked.) This avoids all the manual shutdown, awaitTermination, etc... and allows you to reuse this ExecutorService
neatly for multiple cycles, if desired.
There are a few related questions on SO:
None of these are strictly on-point for your question, but they do provide a bit of color about how folks think Executor
/ExecutorService
ought to be used.
I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.
//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
"ln": {c.ln},
"ip": {c.ip},
"ua": {c.ua}})
//okay, moving on...
if err != nil {
//handle postform error
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
//handle read response error
}
fmt.Printf("%s\n", string(body))
Same as jkp's answer, but here's the full command:
git reset --hard a0d3fe6
where a0d3fe6 is found by doing
git reflog
and looking at the point at which you want to undo to.
Xcode 11.2.1, December 2019
Apple gives you crash log in .txt format , which is unsymbolicated
**
With the device connected
**
We will be able to see symbolicated crash logs over there
Please see the link for more details on Symbolicating Crash logs
getElementByID
is exactly that - get an element by id.
Maybe you want to give those elements a circle
class and getElementsByClassName
\b\d+,
\b------->word boundary
\d+------>one or digit
,-------->containing commas,
Eg:
sddsgg 70,000 sdsfdsf fdgfdg70,00
sfsfsd 5,44,4343 5.7788,44 555
It will match:
70,
5,
44,
,44
using System.Linq;
...
double total = myList.Sum(item => item.Amount);
HTML :
<div id="myDiv">
<form id="myForm">
</form>
</div>
jQuery :
var chbx='<input type="checkbox" id="Mumbai" name="Mumbai" value="Mumbai" />Mumbai<br /> <input type="checkbox" id=" Delhi" name=" Delhi" value=" Delhi" /> Delhi<br/><input type="checkbox" id=" Bangalore" name=" Bangalore" value=" Bangalore"/>Bangalore<br />';
$("#myDiv form#myForm").html(chbx);
//to insert dynamically created form
$("#myDiv").html("<form id='dynamicForm'>" +chbx + "'</form>");
Simple Answer: NO
Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.
By personal experience, I would recommed this:
lower_case_table_names
is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
The issue you are encountering is a documented feature of get_or_create
.
When using keyword arguments other than "defaults" the return value of get_or_create
is an instance. That's why it is showing you the parens in the return value.
you could use customer.source = Source.objects.get_or_create(name="Website")[0]
to get the correct value.
Here is a link for the documentation: http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs
.extend()
is added by many third-party libraries to make it easy to create objects from other objects. See http://api.jquery.com/jQuery.extend/ or http://www.prototypejs.org/api/object/extend for some examples.
.prototype
refers to the "template" (if you want to call it that) of an object, so by adding methods to an object's prototype (you see this a lot in libraries to add to String, Date, Math, or even Function) those methods are added to every new instance of that object.
You might would like to try img tag instead of setting 'list-style-image' property. Setting width and height using css will actually crop the image. But if you use img tag, the image will be re-sized to value of width and height.
Ok I have managed to solve this using a selector. See code below:
main_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="horizontal"
android:background="@drawable/main_header_selector">
</LinearLayout>
main_header_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#FFFF0000"
android:endColor="#FF00FF00"
android:type="linear" />
</shape>
</item>
</selector>
Hopefully this helps someone who has the same problem.
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html
`${number}`.replace(/^(\d)$/, '0$1');
Regex is the best.
Remember that running the command
git config --global core.excludesfile '~/.gitignore'
will just set up the global file, but will NOT create it.
For Windows check your Users directory for the .gitconfig
file, and edit it to your preferences. In my case It's like that:
[core]
excludesfile = c:/Users/myuser/Dropbox/Apps/Git/.gitignore
In order to get the refresh_token
you need to include access_type=offline
in the OAuth request URL. When a user authenticates for the first time you will get back a non-nil refresh_token
as well as an access_token
that expires.
If you have a situation where a user might re-authenticate an account you already have an authentication token for (like @SsjCosty mentions above), you need to get back information from Google on which account the token is for. To do that, add profile
to your scopes. Using the OAuth2 Ruby gem, your final request might look something like this:
client = OAuth2::Client.new(
ENV["GOOGLE_CLIENT_ID"],
ENV["GOOGLE_CLIENT_SECRET"],
authorize_url: "https://accounts.google.com/o/oauth2/auth",
token_url: "https://accounts.google.com/o/oauth2/token"
)
# Configure authorization url
client.authorize_url(
scope: "https://www.googleapis.com/auth/analytics.readonly profile",
redirect_uri: callback_url,
access_type: "offline",
prompt: "select_account"
)
Note the scope has two space-delimited entries, one for read-only access to Google Analytics, and the other is just profile
, which is an OpenID Connect standard.
This will result in Google providing an additional attribute called id_token
in the get_token
response. To get information out of the id_token, check out this page in the Google docs. There are a handful of Google-provided libraries that will validate and “decode” this for you (I used the Ruby google-id-token gem). Once you get it parsed, the sub
parameter is effectively the unique Google account ID.
Worth noting, if you change the scope, you'll get back a refresh token again for users that have already authenticated with the original scope. This is useful if, say, you have a bunch of users already and don't want to make them all un-auth the app in Google.
Oh, and one final note: you don't need prompt=select_account
, but it's useful if you have a situation where your users might want to authenticate with more than one Google account (i.e., you're not using this for sign-in / authentication).
Keep in mind that you're able to repeat the last used command with @:
, so that's all you'd need to repeat are those two character.
Or you could save the string w !python
into one of the registers (like "a
for example) and then hit :<C-R>a<CR>
to insert the contents of register a
into the commandline and run it.
Or you can do what I do and map <leader>z
to :!python %<CR>
to run the current file.
There is a workaround by capturing clicks on document.body
and then checking event target.
document.body.addEventListener( 'click', function ( event ) {
if( event.srcElement.id == 'btnSubmit' ) {
someFunc();
};
} );
The simplest way to get images, videos, etc onto the simulator is to drag and drop them from your computer onto the simulator. This will cause the Simulator to open the Photos app and start populating the library.
If you want a scriptable method, read on.
Note - while this is valid, and works, I think Koen's solution below is now a better one, since it does not require rebooting the simulator.
Identify your simulator by going to xCode->Devices, selecting your simulator, and checking the Identifier value. Or you can ensure the simulator is running and run the following to get the device ID xcrun simctl list | grep Booted
Go to
~/Library/Developer/CoreSimulator/Devices/[Simulator Identifier]/data/Media/DCIM/100APPLE
and add IMG_nnnn.THM and IMG_nnnn.JPG. You will then need to reset your simulator (Hardware->Reboot) to allow it to notice the new changes. It doesn't matter if they are not JPEGs - they can both be PNGs, but it appears that both of them must be present for it to work. You may need to create DCIM if it doesn't already exist, and in that case you should start nnnn from 0001. The JPG files are the fullsize version, while the THM files are the thumbnail, and are 75x75 pixels in size. I wrote a script to do this, but there's a better documented one over here(-link no longer work).
You can also add photos from safari in the simulator, by Tapping and Holding on the image. If you drag an image (or any other file, like a PDF) to the simulator, it will immediately open Safari and display the image, so this is quite an easy way of getting images to it.
There is big difference between dot (".")
and text()
:-
The dot (".")
in XPath
is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element
, attribute
, or text node
) or an atomic value (such as a string
, number
, or boolean
). While text()
refers to match only element text
which is in string
form.
The dot (".")
notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath
function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath
text() function.
For an example :-
<a href="something.html">
<img src="filename.gif">
link
</a>
Here if you want to find anchor a
element by using text link, you need to use dot (".")
. Because if you use //a[contains(.,'link')]
it finds the anchor a
element but if you use //a[contains(text(),'link')]
the text()
function does not seem to find it.
Hope it will help you..:)
You can't have HTML code inside the options, they can only contain text, but you can apply the class to the option instead:
<option selected="selected" class="grey_color">select one option</option>
Demo: http://jsfiddle.net/Guffa/hUpAB/9/
Note:
html
and head
tags in the HTML code in jsfiddle.This works for me. I'm sorry if I cannot remember the source. It is probably from a man page.
#include <ftw.h>
int AnalizeDirectoryElement (const char *fpath,
const struct stat *sb,
int tflag,
struct FTW *ftwbuf) {
if (tflag == FTW_F) {
std::string strFileName(fpath);
DoSomethingWith(strFileName);
}
return 0;
}
void WalkDirectoryTree (const char * pchFileName) {
int nFlags = 0;
if (nftw(pchFileName, AnalizeDirectoryElement, 20, nFlags) == -1) {
perror("nftw");
}
}
int main() {
WalkDirectoryTree("some_dir/");
}
Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:
$objPHPExcel = new PHPExcel();
$objPHPExcel->getDefaultStyle()
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
And it works flawlessly. Thank you, Mark Baker.
I found xunit-viewer
, which has deprecated junit-viewer
mentioned by @daniel-kristof-kiss.
It is very simple, automatically recursively collects all relevant files in ANT Junit XML format and creates a single html-file with filtering and other sweet features.
I use it to upload test results from Travis builds as Travis has no other support for collecting standard formatted test results output.
_JAVA_OPTIONS="-Xmx3G" mvn clean install
Here's an example of how to solve the same problem without having to map the fields manually:
from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.attributes import InstrumentedAttribute
engine = create_engine('postgres://postgres@localhost:5432/database')
session = sessionmaker()
session.configure(bind=engine)
Base = declarative_base()
class Media(Base):
__tablename__ = 'media'
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
slug = Column(String, nullable=False)
type = Column(String, nullable=False)
def update(self):
s = session()
mapped_values = {}
for item in Media.__dict__.iteritems():
field_name = item[0]
field_type = item[1]
is_column = isinstance(field_type, InstrumentedAttribute)
if is_column:
mapped_values[field_name] = getattr(self, field_name)
s.query(Media).filter(Media.id == self.id).update(mapped_values)
s.commit()
So to update a Media instance, you can do something like this:
media = Media(id=123, title="Titular Line", slug="titular-line", type="movie")
media.update()
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
Here you go. It's a little messy but it works.
$(function () {
var companyList = $("#CompanyList").autocomplete({
change: function() {
alert('changed');
}
});
companyList.autocomplete('option','change').call(companyList);
});
This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.
On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it
error instead when making a request to a local URL that is not served, eg: localhost:5000
. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:
[Errno 99] Cannot assign requested address
(if called from within the container), or[Errno 0] Error
(if called from outside of the container).You can reproduce this error and the behaviour described above as follows:
Start a dummy container (note: this will pull the python image if not found locally):
docker run --name serv1 -p 5000:5000 -dit python
Then for [Errno 0] Error
enter a Python console on host, while for [Errno 99] Cannot assign requested address
access a Python console on the container by calling:
docker exec -it -u 0 serv1 python
And then in either case call:
import urllib.request
urllib.request.urlopen('https://localhost:5000')
I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it
rather than trying to fix their cause - although please advise if that's a bad idea.
I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address
point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl
conflicts, docker network issues, TIME_WAIT
being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.
To directly login to a remote mysql console, use the below command:
mysql -u {username} -p'{password}' \
-h {remote server ip or name} -P {port} \
-D {DB name}
For example
mysql -u root -p'root' \
-h 127.0.0.1 -P 3306 \
-D local
no space after -p as specified in the documentation
It will take you to the mysql console directly by switching to the mentioned database.
The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified
.
Therefore it may be better to do the following:
DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
The myDate.Kind
property is readonly, so it cannot be changed after the constructor is called.
You have a typo in your xml; it should be:
android:textColor="@color/text_color"
that's "@color" without the 's'.
Java 8 introduced CompletableFuture available in package java.util.concurrent.CompletableFuture, can be used to make a asynch call :
CompletableFuture.runAsync(() -> {
// method call or code to be asynch.
});
Given the FAQ, sharing a project file seems have to have advantages and is even recommended practice for Java projects (personally, I would not do that).
Maybe some of the following work for you:
For swift 2.0+. This code works fine to me.
extension UIColor {
/// UIColor(hexString: "#cc0000")
internal convenience init?(hexString:String) {
guard hexString.characters[hexString.startIndex] == Character("#") else {
return nil
}
guard hexString.characters.count == "#000000".characters.count else {
return nil
}
let digits = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))
guard Int(digits,radix:16) != nil else{
return nil
}
let red = digits.substringToIndex(digits.startIndex.advancedBy(2))
let green = digits.substringWithRange(Range<String.Index>(start: digits.startIndex.advancedBy(2),
end: digits.startIndex.advancedBy(4)))
let blue = digits.substringWithRange(Range<String.Index>(start:digits.startIndex.advancedBy(4),
end:digits.startIndex.advancedBy(6)))
let redf = CGFloat(Double(Int(red, radix:16)!) / 255.0)
let greenf = CGFloat(Double(Int(green, radix:16)!) / 255.0)
let bluef = CGFloat(Double(Int(blue, radix:16)!) / 255.0)
self.init(red: redf, green: greenf, blue: bluef, alpha: CGFloat(1.0))
}
}
This code includes string format checking. e.g.
let aColor = UIColor(hexString: "#dadada")!
let failed = UIColor(hexString: "123zzzz")
And as far as I know, my code is of no disadvantage for its maintaining the semantic of failible condition and returning an optional value. And this should be the best answer.
Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net
if you want to upgrade pip by proxy, can use (for example in Windows):
python -m pip --proxy http://proxy_user:proxy_password@proxy_hostname:proxy_port insta
ll --upgrade pip
"%.2f"
does not return a clean float. It returns a string representing this float with two decimals.
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
returns:
['0.30', '0.50', '0.20']
Also, don't call your variable list
. This is a reserved word for list creation. Use some other name, for example my_list
.
If you want to obtain [0.30, 0.5, 0.20]
(or at least the floats that are the closest possible), you can try this:
my_rounded_list = [ round(elem, 2) for elem in my_list ]
returns:
[0.29999999999999999, 0.5, 0.20000000000000001]
You can just split your string like that using this regular expression
String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/>
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+");
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jArray = jsonObj.getJSONArray("data");
int length = jArray.length();
for(int i=0; i<length; i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String id = jObj.optString("id");
String name=jObj.optString("name");
JSONArray ingredientArray = jObj.getJSONArray("Ingredients");
int size = ingredientArray.length();
ArrayList<String> Ingredients = new ArrayList<>();
for(int j=0; j<size; j++)
{
JSONObject json = ja.getJSONObject(j);
Ingredients.add(json.optString("name"));
}
}
From the Active Record docs:
$this->db->where_in();
Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
I ran into an issue with Andy Earnshaw's answer because I had factored this function out to a separate class within my application, "HelperFunctions", which meant the recursive call to objectToArray() failed.
I overcame this by specifying the class name within the array_map call like so:
public function objectToArray($object) {
if (!is_object($object) && !is_array($object))
return $object;
return array_map(array("HelperFunctions", "objectToArray"), (array) $object);
}
I would have written this in the comments but I don't have enough reputation yet.
use content
in iframe with JS:
document.getElementById('id_iframe').contentWindow.document.write('content');
For those who want to do this in Node.js (running scripts on the server-side) another option is to use require
and module.exports
. Here is a short example on how to create a module and export it for use elsewhere:
file1.js
const print = (string) => {
console.log(string);
};
exports.print = print;
file2.js
const file1 = require('./file1');
function printOne() {
file1.print("one");
};
Why not combine the onclick method with the <a>
element inside the <td>
for backup for non-JS? Seems to work great.
<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>
There's a facility to have a separate style sheet for print, using
<link type="text/css" rel="stylesheet" media="print" href="print.css">
I don't know if it does what you want though.
Here's how I did it at school. I forgot why it is not a good idea.
EDIT:
@Darius Bacon: cites a "Beautiful Code" book which contains an explanation why the belowed code is not a good idea.
#!/usr/bin/env python
from __future__ import division
epsilon = 1e-6
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
class LineSegment:
"""
>>> ls = LineSegment(Point(0,0), Point(2,4))
>>> Point(1, 2) in ls
True
>>> Point(.5, 1) in ls
True
>>> Point(.5, 1.1) in ls
False
>>> Point(-1, -2) in ls
False
>>> Point(.1, 0.20000001) in ls
True
>>> Point(.1, 0.2001) in ls
False
>>> ls = LineSegment(Point(1, 1), Point(3, 5))
>>> Point(2, 3) in ls
True
>>> Point(1.5, 2) in ls
True
>>> Point(0, -1) in ls
False
>>> ls = LineSegment(Point(1, 2), Point(1, 10))
>>> Point(1, 6) in ls
True
>>> Point(1, 1) in ls
False
>>> Point(2, 6) in ls
False
>>> ls = LineSegment(Point(-1, 10), Point(5, 10))
>>> Point(3, 10) in ls
True
>>> Point(6, 10) in ls
False
>>> Point(5, 10) in ls
True
>>> Point(3, 11) in ls
False
"""
def __init__(self, a, b):
if a.x > b.x:
a, b = b, a
(self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None
def __contains__(self, c):
return (self.x0 <= c.x <= self.x1 and
min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
(not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))
def y(self, x):
return self.slope * (x - self.x0) + self.y0
if __name__ == '__main__':
import doctest
doctest.testmod()
Install the readr
package, then use library(readr)
.