dynamic_cast should be what you are looking for.
EDIT:
DerivedType m_derivedType = m_baseType; // gives same error
The above appears to be trying to invoke the assignment operator, which is probably not defined on type DerivedType and accepting a type of BaseType.
DerivedType * m_derivedType = (DerivedType*) & m_baseType; // gives same error
You are on the right path here but the usage of the dynamic_cast will attempt to safely cast to the supplied type and if it fails, a NULL will be returned.
Going on memory here, try this (but note the cast will return NULL as you are casting from a base type to a derived type):
DerivedType * m_derivedType = dynamic_cast<DerivedType*>(&m_baseType);
If m_baseType was a pointer and actually pointed to a type of DerivedType, then the dynamic_cast should work.
Hope this helps!
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
There is the onload
function, that could be called when the script has loaded successfully:
function addScript( src, callback ) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
s.onload=callback;
document.body.appendChild( s );
}
on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
The amount of "neurons", or "cells", or whatever the layer has inside it.
It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:
Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.
Ex: a shape (30,4,10)
means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.
What flows between layers are tensors. Tensors can be seen as matrices, with shapes.
In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.
Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3)
. Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).
Each type of layer requires the input with a certain number of dimensions:
Dense
layers require inputs as (batch_size, input_size)
(batch_size, optional,...,optional, input_size)
channels_last
: (batch_size, imageside1, imageside2, channels)
channels_first
: (batch_size, channels, imageside1, imageside2)
(batch_size, sequence_length, features)
Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.
All the other shapes are calculated automatically based on the units and particularities of each layer.
Given the input shape, all other shapes are results of layers calculations.
The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).
Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)
Let's show what happens with "Dense" layers, which is the type shown in your graph.
A dense layer has an output shape of (batch_size,units)
. So, yes, units, the property of the layer, also defines the output shape.
(batch_size,4)
. (batch_size,4)
. (batch_size,1)
. Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.
In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.
In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.
Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3)
.
Since the input shape is the only one you need to define, Keras will demand it in the first layer.
But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:
input_shape = (50,50,3)
#regardless of how many images I have, each image has this shape
Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3)
or batch_shape=(30,50,50,3)
. This limits your training possibilities to this unique batch size, so it should be used only when really required.
Either way you choose, tensors in the model will have the batch dimension.
So, even if you used input_shape=(50,50,3)
, when keras sends you messages, or when you print the model summary, it will show (None,50,50,3)
.
The first dimension is the batch size, it's None
because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None
)
Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.
input_shape=(50,50,3)
(30,50,50,3)
(None,50,50,3)
or (30,50,50,3)
, depending on what type of message it sends you. And in the end, what is dim
?
If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim
as a scalar number.
So, in your model, where your input layer has 3 elements, you can use any of these two:
input_shape=(3,)
-- The comma is necessary when you have only one dimension input_dim = 3
But when dealing directly with the tensors, often dim
will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.
Keras has two ways of doing it, Sequential
models, or the functional API Model
. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.
PS: here I ignored other aspects, such as activation functions.
With the Sequential model:
from keras.models import Sequential
from keras.layers import *
model = Sequential()
#start from the first hidden layer, since the input is not actually a layer
#but inform the shape of the input, with 3 elements.
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input
#further layers:
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer
With the functional API Model:
from keras.models import Model
from keras.layers import *
#Start defining the input tensor:
inpTensor = Input((3,))
#create the layers and pass them the input tensor to get the output tensor:
hidden1Out = Dense(units=4)(inpTensor)
hidden2Out = Dense(units=4)(hidden1Out)
finalOut = Dense(units=1)(hidden2Out)
#define the model's start and end points
model = Model(inpTensor,finalOut)
Shapes of the tensors
Remember you ignore batch sizes when defining layers:
(None,3)
(None,4)
(None,4)
(None,1)
Use Apache commons beanutils:
static void copyProperties(Object dest, Object orig)
-Copy property values from the origin bean to the destination bean for all cases where the property names are the same.
import React, { Component } from 'react';
class Result extends Component {
render() {
if(this.props.resultsfood.status=='found'){
var foodlist = this.props.resultsfood.items.map(name=>{
return (
<div className="row" key={name.id} >
<div className="list-group">
<a href="#" className="list-group-item list-group-item-action disabled">
<span className="badge badge-info"><h6> {name.item}</h6></span>
<span className="badge badge-danger"><h6> Rs.{name.price}/=</h6></span>
</a>
<a href="#" className="list-group-item list-group-item-action disabled">
<div className="alert alert-dismissible alert-secondary">
<strong>{name.description}</strong>
</div>
</a>
<div className="form-group">
<label className="col-form-label col-form-label-sm" htmlFor="inputSmall">Quantitiy</label>
<input className="form-control form-control-sm" placeholder="unit/kg" type="text" ref="qty"/>
<div> <button type="button" className="btn btn-success"
onClick={()=>{this.props.savelist(name.item,name.price);
this.props.pricelist(name.price);
this.props.quntylist(this.refs.qty.value);
}
}>ADD Cart</button>
</div>
<br/>
</div>
</div>
</div>
)
})
}
return (
<ul>
{foodlist}
</ul>
)
}
}
export default Result;
You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.
I'll be up-front about my preference for natural keys - use them where possible, as they'll make your life of database administration a lot easier. I established a standard in our company that all tables have the following columns:
SUSER_SNAME()
in T-SQL))Row ID has a unique key on it per table, and in any case is auto-generated per row (and permissions prevent anyone editing it), and is reasonably guaranteed to be unique across all tables and databases. If any ORM systems need a single ID key, this is the one to use.
Meanwhile, the actual PK is, if possible, a natural key. My internal rules are something like:
EventId, AttendeeId
)So ideally you end up with a natural, human-readable and memorable PK, and an ORM-friendly one-ID-per-table GUID.
Caveat: the databases I maintain tend to the 100,000s of records rather than millions or billions, so if you have experience of larger systems which contraindicates my advice, feel free to ignore me!
Works in all modern browsers
.rotate{
animation: loading 3s linear infinite;
@keyframes loading {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
}
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
DECORATORS: to dynamically change the behaviour of DOM elements
@HostBinding: Dynamic binding custom logic to Host element
@HostBinding('class.active')
activeClass = false;
@HostListen: To Listen to events on Host element
@HostListener('click')
activeFunction(){
this.activeClass = !this.activeClass;
}
Host Element:
<button type='button' class="btn btn-primary btn-sm" appHost>Host</button>
Best option is to use the '?' argument for the method. This way DBMS_MVIEW will choose the best way to refresh, so it'll do the fastest refresh it can for you. , and won't fail if you try something like method=>'f' when you actually need a complete refresh. :-)
from the SQL*Plus prompt:
EXEC DBMS_MVIEW.REFRESH('my_schema.my_mview', method => '?');
I'm finding that Tomcat can't seem to find classes defined in other projects, maybe even in the main project. It's failing on the filter definition which is the first definition in web.xml. If I add the project and its dependencies to the server's launch configuration then I just move on to a new error, all of which seems to point to it not setting up the project properly.
Our setup is quite complex. We have multiple components as projects in Eclipse with separate output projects. We have a separate webapp directory which contains the static HTML and images, as well as our WEB-INF.
Eclipse is "Europa Winter release". Tomcat is 6.0.18. I tried version 2.4 and 2.5 of the "Dynamic Web Module" facet.
Thanks for any help!
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
It is simple. Use trim-redux package and write like this in componentDidMount
or other place and kill it in componentWillUnmount
.
componentDidMount() {
this.tm = setTimeout(function() {
setStore({ age: 20 });
}, 3000);
}
componentWillUnmount() {
clearTimeout(this.tm);
}
if your column contain any value that you want to neglect. it will help you
## da is data frame & Ozone is column name
##for single column
mean(da$Ozone, na.rm = TRUE)
##for all columns
colMeans(x=da, na.rm = TRUE)
Try using:
if(NewType* v = dynamic_cast<NewType*>(old)) {
// old was safely casted to NewType
v->doSomething();
}
This requires your compiler to have rtti support enabled.
EDIT: I've had some good comments on this answer!
Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.
Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).
As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.
if(old->getType() == BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.
Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:
// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
Box* box = static_cast<Box*>(old);
// Do something box specific
}
In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain class and their instances The term metaclass simply means something used to create classes. In other words, it is the class of a class. The metaclass is used to create the class so like the object being an instance of a class, a class is an instance of a metaclass. In python classes are also considered objects.
<br /> works for me
So...
String body = String.Format(@"New user:
<br /> Name: {0}
<br /> Email: {1}
<br /> Phone: {2}", Name, Email, Phone);
Produces...
New user:
Name: Name
Email: Email
Phone: Phone
Why don't you try android:hint="hint" to provide the hint to the user..!!
The "hint" will automatically disappear when the user clicks on the edittextbox. its the proper and best solution.
To define intersection that correctly takes into account the cardinality of the elements use Counter
:
from collections import Counter
>>> c1 = [1, 2, 2, 3, 4, 4, 4]
>>> c2 = [1, 2, 4, 4, 4, 4, 5]
>>> list((Counter(c1) & Counter(c2)).elements())
[1, 2, 4, 4, 4]
I agree with John Saunders, this isn't really C# specific. However, to answer your question: you basically need to rewrite the file. There are two ways you can do this.
File.ReadAllLines
)List<string>
then remove the line)File.WriteAllLines
) - potentially convert the List<string>
into a string array again using ToArray
That means you have to know that you've got enough memory though. An alternative:
TextReader
/TextWriter
, e.g. with File.OpenText
and File.CreateText
)TextReader.ReadLine
) - if you don't want to delete it, write it to the output file (TextWriter.WriteLine
)using
statements for both, this will happen automatically)You can wrap the columns inside a div
<div class="row">
<div class="col-md-12>
<div class="col-xs-12 col-sm-4 panel" style="background-color: red">
some content
</div>
<div class="col-xs-6 col-sm-4 panel" style="background-color: yellow">
kittenz
<img src="http://placekitten.com/100/100">
</div>
<div class="col-xs-6 col-sm-4 panel" style="background-color: blue">
some more content
</div>
</div>
</div>
@Alex Martelli
's answer is great!
But it work only for one element at time (WHERE name = 'Joan'
)
If you take out the WHERE
clause, the query will return all the root rows together...
I changed a little bit for my situation, so it can show the entire tree for a table.
table definition:
CREATE TABLE [dbo].[mar_categories] (
[category] int IDENTITY(1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[level] int NOT NULL,
[action] int NOT NULL,
[parent] int NULL,
CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)
(level
is literally the level of a category 0: root, 1: first level after root, ...)
and the query:
WITH n(category, name, level, parent, concatenador) AS
(
SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
FROM mar_categories
WHERE parent is null
UNION ALL
SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
FROM mar_categories as m, n
WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc
(You don't need to concatenate the level
field, I did just to make more readable)
the answer for this query should be something like:
I hope it helps someone!
now, I'm wondering how to do this on MySQL... ^^
The exact answer to the question is: yes, you can use an arbitrary value for the boundary
parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII
(printable) characters.
If you are using one of multipart/*
content types, you are actually required to specify the boundary
parameter in the Content-Type
header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.
You probably also want to set the charset
parameter to UTF-8
in your Content-Type
header, unless you can be absolutely sure that only US-ASCII
charset will be used in the payload data.
A few relevant excerpts from the RFC2046:
4.1.2. Charset Parameter:
Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.
5.1. Multipart Media Type
As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.
The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.
Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.
The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.
Here is an example using an arbitrary boundary:
Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"
--another cool boundary
Content-Disposition: form-data; name="foo"
bar
--another cool boundary
Content-Disposition: form-data; name="baz"
quux
--another cool boundary--
Putting this in since it's 'yet another' approach, seems to be different from others already given.
returns -1
if x==0
, otherwise floor( log2(x))
(max result 31)
Reduce from 32 to 4 bit problem, then use a table. Perhaps inelegant, but pragmatic.
This is what I use when I don't want to use __builtin_clz
because of portability issues.
To make it more compact, one could instead use a loop to reduce, adding 4 to r each time, max 7 iterations. Or some hybrid, such as (for 64 bits): loop to reduce to 8, test to reduce to 4.
int log2floor( unsigned x ){
static const signed char wtab[16] = {-1,0,1,1, 2,2,2,2, 3,3,3,3,3,3,3,3};
int r = 0;
unsigned xk = x >> 16;
if( xk != 0 ){
r = 16;
x = xk;
}
// x is 0 .. 0xFFFF
xk = x >> 8;
if( xk != 0){
r += 8;
x = xk;
}
// x is 0 .. 0xFF
xk = x >> 4;
if( xk != 0){
r += 4;
x = xk;
}
// now x is 0..15; x=0 only if originally zero.
return r + wtab[x];
}
Yes, using NSSet is a sensible approach.
To add to Jim Puls' answer, here's an alternative approach to stripping duplicates while retaining order:
// Initialise a new, empty mutable array
NSMutableArray *unique = [NSMutableArray array];
for (id obj in originalArray) {
if (![unique containsObject:obj]) {
[unique addObject:obj];
}
}
It's essentially the same approach as Jim's but copies unique items to a fresh mutable array rather than deleting duplicates from the original. This makes it slightly more memory efficient in the case of a large array with lots of duplicates (no need to make a copy of the entire array), and is in my opinion a little more readable.
Note that in either case, checking to see if an item is already included in the target array (using containsObject:
in my example, or indexOfObject:inRange:
in Jim's) doesn't scale well for large arrays. Those checks run in O(N) time, meaning that if you double the size of the original array then each check will take twice as long to run. Since you're doing the check for each object in the array, you'll also be running more of those more expensive checks. The overall algorithm (both mine and Jim's) runs in O(N2) time, which gets expensive quickly as the original array grows.
To get that down to O(N) time you could use a NSMutableSet
to store a record of items already added to the new array, since NSSet lookups are O(1) rather than O(N). In other words, checking to see whether an element is a member of an NSSet takes the same time regardless of how many elements are in the set.
Code using this approach would look something like this:
NSMutableArray *unique = [NSMutableArray array];
NSMutableSet *seen = [NSMutableSet set];
for (id obj in originalArray) {
if (![seen containsObject:obj]) {
[unique addObject:obj];
[seen addObject:obj];
}
}
This still seems a little wasteful though; we're still generating a new array when the question made clear that the original array is mutable, so we should be able to de-dupe it in place and save some memory. Something like this:
NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;
while (i < [originalArray count]) {
id obj = [originalArray objectAtIndex:i];
if ([seen containsObject:obj]) {
[originalArray removeObjectAtIndex:i];
// NB: we *don't* increment i here; since
// we've removed the object previously at
// index i, [originalArray objectAtIndex:i]
// now points to the next object in the array.
} else {
[seen addObject:obj];
i++;
}
}
UPDATE: Yuri Niyazov pointed out that my last answer actually runs in O(N2) because removeObjectAtIndex:
probably runs in O(N) time.
(He says "probably" because we don't know for sure how it's implemented; but one possible implementation is that after deleting the object at index X the method then loops through every element from index X+1 to the last object in the array, moving them to the previous index. If that's the case then that is indeed O(N) performance.)
So, what to do? It depends on the situation. If you've got a large array and you're only expecting a small number of duplicates then the in-place de-duplication will work just fine and save you having to build up a duplicate array. If you've got an array where you're expecting lots of duplicates then building up a separate, de-duped array is probably the best approach. The take-away here is that big-O notation only describes the characteristics of an algorithm, it won't tell you definitively which is best for any given circumstance.
Quick answer: the FROM address must exactly match the account you are sending from, or you will get a error 5.7.1 Client does not have permissions to send as this sender.
My guess is that prevents email spoofing with your Office 365 account, otherwise you might be able to send as [email protected].
Another thing to try is in the authentication, fill in the third field with the domain, like
Dim smtpAuth = New System.Net.NetworkCredential(
"TheDude", "hunter2password", "MicrosoftOffice365Domain.com")
If that doesn't work, double check that you can log into the account at: https://portal.microsoftonline.com
Yet another thing to note is your Antivirus solution may be blocking programmatic access to ports 25 and 587 as a anti-spamming solution. Norton and McAfee may silently block access to these ports. Only enabling Mail and Socket debugging will allow you to notice it (see below).
One last thing to note, the Send method is Asynchronous. If you call
Disposeimmediately after you call send, your are more than likely closing your connection before the mail is sent. Have your smtpClient instance listen for the OnSendCompleted event, and call dispose from there. You must use SendAsync method instead, the Send method does not raise this event.
Detailed Answer: With Visual Studio (VB.NET or C# doesn't matter), I made a simple form with a button that created the Mail Message, similar to that above. Then I added this to the application.exe.config (in the bin/debug directory of my project). This enables the Output tab to have detailed debug info.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="System.Net" />
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net" />
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose" />
<add name="System.Net.Sockets" value="Verbose" />
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="System.Net.log"
/>
</sharedListeners>
<trace autoflush="true" />
</system.diagnostics>
</configuration>
Reason why you cannot use function pointers to call member functions is that ordinary function pointers are usually just the memory address of the function.
To call a member function, you need to know two things:
Ordinary function pointers cannot store both. C++ member function pointers are used to store a), which is why you need to specify the instance explicitly when calling a member function pointer.
Click event Bubbles, now what is meant by bubbling, a good point to starts is here.
you can use event.stopPropagation()
, if you don't want that event should propagate further.
Also a good link to refer on MDN
You need to have your function in the componentDidMount
lifecycle since this is the function that is called when the DOM has loaded.
Make use of refs
to access the DOM element
<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>
componentDidMount: function(){
var name = React.findDOMNode(this.refs.cpDev1).value;
this.someOtherFunction(name);
}
See this answer for more info on How to access the dom element in React
There is a step by step explanation (with pictures) available @ Restore DataBase
Click Start, select All Programs, click Microsoft SQL Server 2008 and select SQL Server Management Studio.
This will bring up the Connect to Server dialog box.
Ensure that the Server name YourServerName and that Authentication is set to Windows Authentication.
Click Connect.
On the right, right-click Databases and select Restore Database.
This will bring up the Restore Database window.
On the Restore Database screen, select the From Device radio button and click the "..." box.
This will bring up the Specify Backup screen.
On the Specify Backup screen, click Add.
This will bring up the Locate Backup File.
Select the DBBackup folder and chose your BackUp File(s).
On the Restore Database screen, under Select the backup sets to restore: place a check in the Restore box, next to your data and in the drop-down next to To database: select DbName.
You're done.
A pure Javascript example, using the services of https://geolocation-db.com They provide a JSON and JSONP-callback solution.
No jQuery required!
<!DOCTYPE html>
<html>
<head>
<title>Geo City Locator by geolocation-db.com</title>
</head>
<body>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<div>Postal: <span id="postal"></span></div>
<div>Latitude: <span id="latitude"></span></div>
<div>Longitude: <span id="longitude"></span></div>
<div>IP address: <span id="ipv4"></span></div>
</body>
<script>
var country = document.getElementById('country');
var state = document.getElementById('state');
var city = document.getElementById('city');
var postal = document.getElementById('postal');
var latitude = document.getElementById('latitude');
var longitude = document.getElementById('longitude');
var ip = document.getElementById('ipv4');
function callback(data)
{
country.innerHTML = data.country_name;
state.innerHTML = data.state;
city.innerHTML = data.city;
postal.innerHTML = data.postal;
latitude.innerHTML = data.latitude;
longitude.innerHTML = data.longitude;
ip.innerHTML = data.IPv4;
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://geoilocation-db.com/json/geoip.php?jsonp=callback';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(script, h);
</script>
</html>
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
I prefer to return the identity value as an output parameter. The result of the SP should indicate whether it succeeded or not. A value of 0 indicates the SP successfully completed, a non-zero value indicates an error. Also, if you ever need to make a change and return an additional value from the SP you don't need to make any changes other than adding an additional output parameter.
For Windows according to Microsoft docs
VBA functions treat the function name itself as a sort of variable. So instead of using a "return
" statement, you would just say:
test = 1
Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test
, and whatever the value is when you reach the end of the function will be the value returned.
None if this worked for me. First of all I had to look at my provider to see how they activate SSL in .htaccess
my provider gives
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:HTTPS} !on
RewriteRule (.*) https://%{SERVER_NAME}/$1 [QSA,L,R=301]
</IfModule>
But what took me days of research is I had to add to wp-config.php
the following lines as my provided site is behind a proxy :
/**
* Force le SSL
*/
define('FORCE_SSL_ADMIN', true);
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false) $_SERVER['HTTPS']='on';
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
In a similar scenario what worked for me was the following:
byte[] bytes = Convert.FromBase64String(Base64String);
ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
ImageTagId
is the ID of the ASP image tag.
You can use new Date().getTimezoneOffset()/60
for the timezone. There is also a toLocaleString()
method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
sort
sorts inplace so returns nothing:
In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a
Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)
So you have to call print a
again after the call to sort
.
Eg.:
In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)
[1 2 3 6 8]
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
The volatile
and transient
modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.
The transient
modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null
for a reference type, and zero or false
for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient
means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient
-ness. Or they may ignore it.
(Note that the JLS permits a static
field to be declared as transient
. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)
The volatile
modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long
or double
fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.
1 - But not to local variables or parameters.
I know this is already answered but in case you want something recursive and more generic and not relying on moment fromNow
you could use this function I created. Of course you can change its logic to adjust it to your needs to also support years and seconds.
var createdAt = moment('2019-05-13T14:23:00.607Z');
var expiresAt = moment('2019-05-14T14:23:00.563Z');
// You can also add years in the beginning of the array or seconds in its end
const UNITS = ["months", "weeks", "days", "hours", "minutes"]
function getValidFor (createdAt, expiresAt, unit = 'months') {
const validForUnit = expiresAt.diff(createdAt, unit);
// you could adjust the if to your needs
if (validForUnit > 1 || unit === "minutes") {
return [validForUnit, unit];
}
return getValidFor(createdAt, expiresAt, UNITS[UNITS.indexOf(unit) + 1]);
}
You can do it with PHP:
header("Refresh:0");
It refreshes your current page, and if you need to redirect it to another page, use following:
header("Refresh:0; url=page2.php");
I missed all the fun, all the good C++ answers have already been posted !
This is the weirdest thing I could come up with, I wouldn't bet it's legal C99 though :p
#include <stdio.h>
int i = 1;
int main(int argc, char *argv[printf("%d\n", i++)])
{
return (i <= 1000) && main(argc, argv);
}
Another one, with a little cheating :
#include <stdio.h>
#include <boost/preprocessor.hpp>
#define ECHO_COUNT(z, n, unused) n+1
#define FORMAT_STRING(z, n, unused) "%d\n"
int main()
{
printf(BOOST_PP_REPEAT(1000, FORMAT_STRING, ~), BOOST_PP_ENUM(LOOP_CNT, ECHO_COUNT, ~));
}
Last idea, same cheat :
#include <boost/preprocessor.hpp>
#include <iostream>
int main()
{
#define ECHO_COUNT(z, n, unused) BOOST_PP_STRINGIZE(BOOST_PP_INC(n))"\n"
std::cout << BOOST_PP_REPEAT(1000, ECHO_COUNT, ~) << std::endl;
}
A common property of Java Web-apps is that they usually use servlets which usually means the web server also runs Java. This contributes to the perceived complexity, IMHO. But you can build Java apps in the traditional Unix-style of "do one thing and do it well" without having performance suffer.
You can also use SCGI, it is a lot simpler than FastCGI. I'd try that first. But if it doesn't work out:
wget --quiet --recursive --no-parent --accept=java --no-directories --no-host-directories "http://www.fastcgi.com/devkit/java/"
mkdir -p com/fastcgi
mv *.java com/fastcgi
Now you need to apply a tiny patch to the devkit (replace operator ==
with <=
on line 175 or use this script to do it):
echo -e "175c\nif (count <= 0) {\n.\nw\nn\nq" | ed -s com/fastcgi/FCGIInputStream.java
TinyFCGI.java
(source below)javac **/*.java
(**
will probably only work in zsh
)java -DFCGI_PORT=9884 TinyFCGI
(leave it running in the background)Now set up e.g. Apache to use the server:
mod_proxy_fcgi
like this:
sudo a2enmod proxy_fcgi
/etc/apache2/conf-enabled/your_site.conf
with the content belowsudo apache2ctl restart
Now you can access the webapp at http://localhost/your_site
TinyFCGI.java
import com.fastcgi.FCGIInterface;
import java.io.*;
import static java.lang.System.out;
class TinyFCGI {
public static void main (String args[]) {
int count = 0;
FCGIInterface fcgiinterface = new FCGIInterface();
while(fcgiinterface.FCGIaccept() >= 0) {
count++;
out.println("Content-type: text/html\n\n");
out.println("<html>");
out.println(
"<head><TITLE>FastCGI-Hello Java stdio</TITLE></head>");
out.println("<body>");
out.println("<H3>FastCGI-HelloJava stdio</H3>");
out.println("request number " + count +
" running on host "
+ System.getProperty("SERVER_NAME"));
out.println("</body>");
out.println("</html>");
}
}
}
your_site.conf
<Location /your_site>
ProxyPass fcgi://localhost:9884/
</Location>
wrk
$ ./wrk -t1 -c100 -r10000 http://localhost/your_site
Making 10000 requests to http://localhost/your_site
1 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 3.58s 13.42s 1.06m 94.42%
Req/Sec 0.00 0.00 0.00 100.00%
10000 requests in 1.42m, 3.23MB read
Socket errors: connect 0, read 861, write 0, timeout 2763
Non-2xx or 3xx responses: 71
Requests/sec: 117.03
Transfer/sec: 38.70KB
ab
$ ab -n 10000 -c 100 localhost:8800/your_site
Concurrency Level: 100
Time taken for tests: 12.640 seconds
Complete requests: 10000
Failed requests: 0
Write errors: 0
Total transferred: 3180000 bytes
HTML transferred: 1640000 bytes
Requests per second: 791.11 [#/sec] (mean)
Time per request: 126.404 [ms] (mean)
Time per request: 1.264 [ms] (mean, across all concurrent requests)
Transfer rate: 245.68 [Kbytes/sec] received
siege
$ siege -r 10000 -c 100 "http://localhost:8800/your_site"
** SIEGE 2.70
** Preparing 100 concurrent users for battle.
The server is now under siege...^C
Lifting the server siege... done.
Transactions: 89547 hits
Availability: 100.00 %
Elapsed time: 447.93 secs
Data transferred: 11.97 MB
Response time: 0.00 secs
Transaction rate: 199.91 trans/sec
Throughput: 0.03 MB/sec
Concurrency: 0.56
Successful transactions: 89547
Failed transactions: 0
Longest transaction: 0.08
Shortest transaction: 0.00
foreach((array)$items as $item) {}
Apply this style to your TextBox and that's it (inspired from this article):
<Style x:Key="SelectableTextBlockLikeStyle" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Padding" Value="-2,0,0,0"/>
<!-- The Padding -2,0,0,0 is required because the TextBox
seems to have an inherent "Padding" of about 2 pixels.
Without the Padding property,
the text seems to be 2 pixels to the left
compared to a TextBlock
-->
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="False" />
<Condition Property="IsFocused" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<TextBlock Text="{TemplateBinding Text}"
FontSize="{TemplateBinding FontSize}"
FontStyle="{TemplateBinding FontStyle}"
FontFamily="{TemplateBinding FontFamily}"
FontWeight="{TemplateBinding FontWeight}"
TextWrapping="{TemplateBinding TextWrapping}"
Foreground="{DynamicResource NormalText}"
Padding="0,0,0,0"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</MultiTrigger>
</Style.Triggers>
</Style>
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
split doesn't work that way in groovy. you have to use tokenize...
See the docs:
Make the (LinearLayout) android:layout_width="match_parent"
and the TextView's android:layout_gravity="right"
They need to be percent-encoded:
> encodeURIComponent('&')
"%26"
So in your case, the URL would look like:
http://www.mysite.com?candy_name=M%26M
/**
* in_array function variant that performs case-insensitive comparison when needle is a string.
*
* @param mixed $needle
* @param array $haystack
* @param bool $strict
*
* @return bool
*/
function in_arrayi($needle, array $haystack, bool $strict = false): bool
{
if (is_string($needle)) {
$needle = strtolower($needle);
foreach ($haystack as $value) {
if (is_string($value)) {
if (strtolower($value) === $needle) {
return true;
}
}
}
return false;
}
return in_array($needle, $haystack, $strict);
}
/**
* in_array function variant that performs case-insensitive comparison when needle is a string.
* Multibyte version.
*
* @param mixed $needle
* @param array $haystack
* @param bool $strict
* @param string|null $encoding
*
* @return bool
*/
function mb_in_arrayi($needle, array $haystack, bool $strict = false, ?string $encoding = null): bool
{
if (null === $encoding) {
$encoding = mb_internal_encoding();
}
if (is_string($needle)) {
$needle = mb_strtolower($needle, $encoding);
foreach ($haystack as $value) {
if (is_string($value)) {
if (mb_strtolower($value, $encoding) === $needle) {
return true;
}
}
}
return false;
}
return in_array($needle, $haystack, $strict);
}
Unless you have a specific reason to do raw ado.net I would have a look at using an ORM (object relational mapper) like nHibernate or LINQ to SQL. That way you can query the database and retrieve objects to work with which are strongly typed and easier to work with IMHO.
Try making your constructor private like this:
private Foo newClass = new Foo();
I believe this should work for all browsers:
var event;
if (typeof (Event) === 'function') {
event = new Event('resize');
} else { /*IE*/
event = document.createEvent('Event');
event.initEvent('resize', true, true);
}
window.dispatchEvent(event);
PDOStatement->execute()
returns true on success. There is also PDOStatement->errorCode()
which you can check for errors.
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
You can iterate DefaultView
as the following code by Indexer
:
DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow oRow = dt.DefaultView[i].Row;
// Do your stuff with oRow
// ...
}
UPDATE ANDROID 10 AND HIGHER
Start an activity from service (foreground or background) is no longer allowed.
There are still some restrictions that can be seen in the documentation
https://developer.android.com/guide/components/activities/background-starts
Using a loop -
public static boolean containsDigit(final String aString)
{
if (aString != null && !aString.isEmpty())
{
for (char c : aString.toCharArray())
{
if (Character.isDigit(c))
{
return true;
}
}
}
return false;
}
Using a stream -
public static boolean containsDigit(final String aString)
{
return aString != null && !aString.isEmpty() &&
aString.chars().anyMatch(Character::isDigit);
}
Why don't you examine System.getProperty("os.arch")
value in your code?
If you're using Qt Jambi, this should work:
QApplication.closeAllWindows();
(WHEN .wsdl is referring to .xsd/schemas using import) If you're using the WMB Tooklit (v8.0.0.4 WMB) then you can find .xsd using following steps :
Create library (optional) > Right Click , New Message Model File > Select SOAP XML > Choose Option 'I already have WSDL for my data' > 'Select file outside workspace' > 'Select the WSDL bindings to Import' (if there are multiple) > Finish.
This will give you the .xsd and .wsdl files in your Workspace (Application Perspective).
This Worked for me ! For Angular 2 , Call child component method in parent component
Parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child';
@Component({
selector: 'parent-app',
template: `<child-cmp></child-cmp>`
})
export class parentComponent implements OnInit{
@ViewChild(ChildComponent ) child: ChildComponent ;
ngOnInit() {
this.child.ChildTestCmp(); }
}
Child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'child-cmp',
template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> `
})
export class ChildComponent {
test: string;
ChildTestCmp()
{
this.test = "I am child component!";
}
}
I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.
Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.
Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.
An example is included in the code below.
//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
public XOBJ<T> Obj = null;
public XOUT(T value)
{
Obj = new XOBJ<T>(value);
}
public XOUT()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(this);
}
public XREF<T> Ref()
{
return(Obj.Ref());
}
};
//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************
public class XREF<T>
{
public XOBJ<T> Obj = null;
public XREF(T value)
{
Obj = new XOBJ<T>(value);
}
public XREF()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(Obj.Out());
}
public XREF<T> Ref()
{
return(this);
}
};
//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
*
* @author jsimms
*/
/*
XOBJ is the base object that houses the value. XREF and XOUT are classes that
internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
the object to be used as XREF or XOUT parameter; This is important, because
objects of these types are interchangeable.
See Method:
XXX.Ref()
XXX.Out()
The below example shows how to use XOBJ, XREF, and XOUT;
//
// Reference parameter example
//
void AddToTotal(int a, XREF<Integer> Total)
{
Total.Obj.Value += a;
}
//
// out parameter example
//
void Add(int a, int b, XOUT<Integer> ParmOut)
{
ParmOut.Obj.Value = a+b;
}
//
// XOBJ example
//
int XObjTest()
{
XOBJ<Integer> Total = new XOBJ<>(0);
Add(1, 2, Total.Out()); // Example of using out parameter
AddToTotal(1,Total.Ref()); // Example of using ref parameter
return(Total.Value);
}
*/
public class XOBJ<T> {
public T Value;
public XOBJ() {
}
public XOBJ(T value) {
this.Value = value;
}
//
// Method: Ref()
// Purpose: returns a Reference Parameter object using the XOBJ value
//
public XREF<T> Ref()
{
XREF<T> ref = new XREF<T>();
ref.Obj = this;
return(ref);
}
//
// Method: Out()
// Purpose: returns an Out Parameter Object using the XOBJ value
//
public XOUT<T> Out()
{
XOUT<T> out = new XOUT<T>();
out.Obj = this;
return(out);
}
//
// Method get()
// Purpose: returns the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public T get() {
return Value;
}
//
// Method get()
// Purpose: sets the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public void set(T anotherValue) {
Value = anotherValue;
}
@Override
public String toString() {
return Value.toString();
}
@Override
public boolean equals(Object obj) {
return Value.equals(obj);
}
@Override
public int hashCode() {
return Value.hashCode();
}
}
This one worked for me:
sudo mv /usr/bin/php /usr/bin/~php
sudo ln -s /Application/XAMPP/xamppfiles/bin/php /usb/bin/php
For SQL server 2012 or above use EOMONTH to get the last date of month
SQL query to display end date of current month
DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate) AS CurrentMonthED
SQL query to display end date of Next month
DECLARE @currentDate DATE = GETDATE()
SELECT EOMONTH (@currentDate, 1 ) AS NextMonthED
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).
I've gotten around this with
mystr = ' '.join(
["Why, hello there",
"wonderful stackoverflow people!"])
in the past. It's not perfect, but it works nicely for very long strings that need to not have line breaks in them.
htmlStr
is string then You need to Date
and Time
variables to string
while (reader.Read())
{
DateTime Date = reader.GetDateTime(0);
DateTime Time = reader.GetDateTime(1);
htmlStr += "<tr><td>" + Date.ToString() + "</td><td>" +
Time.ToString() + "</td></tr>";
}
For a String constant you have no choice other than escaping via backslash.
Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.
If you use "hg remove b"
against a file with "A" status, which means it has been added but not commited, Mercurial will respond:
not removing b: file has been marked for add (use forget to undo)
This response is a very clear explication of the difference between remove and forget.
My understanding is that "hg forget"
is for undoing an added but not committed file so that it is not tracked by version control; while "hg remove"
is for taking out a committed file from version control.
This thread has a example for using hg remove
against files of 7 different types of status.
I think you will have fewer problems if you declared a Property that implements INotifyPropertyChanged, then databind IsChecked
, SelectedIndex
(using IValueConverter) and Fill
(using IValueConverter) to it instead of using the Checked Event to toggle SelectedIndex
and Fill
.
This is a late answer but hope this might help.
Scenario 1: You visited the site for first time and did not touch any field. The state of form is
ng-untouched and ng-pristine
Scenario 2: You are currently entering the values in a particular field in the form. Then the state is
ng-untouched and ng-dirty
Scenario 3: You are done with entering the values in the field and moved to next field
ng-touched and ng-dirty
Scenario 4: Say a form has a phone number field . You have entered the number but you have actually entered 9 digits but there are 10 digits required for a phone number.Then the state is ng-invalid
In short:
ng-untouched:When the form field has not been visited yet
ng-touched: When the form field is visited AND the field has lost focus
ng-pristine: The form field value is not changed
ng-dirty: The form field value is changed
ng-valid : When all validations of form fields are successful
ng-invalid: When all validations of form fields are not successful
Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.
Option 1: Create a new thread rather than trying to restart.
Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.
Edit based on comment:
To "kill" the thread you can do something like the following.
yourThread.setIsTerminating(true); // tell the thread to stop
yourThread.join(); // wait for the thread to stop
' is the escape character. So your string should be:
This is Ashok''s Pen
If you are using some front-end code, you need to do a string replace before sending the data to the stored procedure.
For example, in C# you can do
value = value.Replace("'", "''");
and then pass value to the stored procedure.
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary
So my example becomes:
d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)
A word of caution:
In my experience, omitting the href
attribute causes problems for accessibility as the keyboard navigation will ignore it and never give it focus like it will when href is present. Manually including your element in the tabindex is a way around that.
iOS users also expect autocapitalization: In a standard text field, the first letter of a sentence in a case-sensitive language is automatically capitalized.
You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed, so providing them is a competitive advantage.
Apple document is saying there is no API available for this feature and some other expected feature in a customkeyboard. so you need to find out your own logic to implement this.
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
I think the following will achieve what you are after
function func( orig, target ) {
var i = orig.length, j = 0, total = 0, change, newVals = [], next, factor1, factor2, len = orig.length, marginOfErrors = [];
// map original values to new array
while( i-- ) {
total += newVals[i] = Math.round( orig[i] );
}
change = total < target ? 1 : -1;
while( total !== target ) {
// Iterate through values and select the one that once changed will introduce
// the least margin of error in terms of itself. e.g. Incrementing 10 by 1
// would mean an error of 10% in relation to the value itself.
for( i = 0; i < len; i++ ) {
next = i === len - 1 ? 0 : i + 1;
factor2 = errorFactor( orig[next], newVals[next] + change );
factor1 = errorFactor( orig[i], newVals[i] + change );
if( factor1 > factor2 ) {
j = next;
}
}
newVals[j] += change;
total += change;
}
for( i = 0; i < len; i++ ) { marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i]; }
// Math.round() causes some problems as it is difficult to know at the beginning
// whether numbers should have been rounded up or down to reduce total margin of error.
// This section of code increments and decrements values by 1 to find the number
// combination with least margin of error.
for( i = 0; i < len; i++ ) {
for( j = 0; j < len; j++ ) {
if( j === i ) continue;
var roundUpFactor = errorFactor( orig[i], newVals[i] + 1) + errorFactor( orig[j], newVals[j] - 1 );
var roundDownFactor = errorFactor( orig[i], newVals[i] - 1) + errorFactor( orig[j], newVals[j] + 1 );
var sumMargin = marginOfErrors[i] + marginOfErrors[j];
if( roundUpFactor < sumMargin) {
newVals[i] = newVals[i] + 1;
newVals[j] = newVals[j] - 1;
marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
}
if( roundDownFactor < sumMargin ) {
newVals[i] = newVals[i] - 1;
newVals[j] = newVals[j] + 1;
marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
}
}
}
function errorFactor( oldNum, newNum ) {
return Math.abs( oldNum - newNum ) / oldNum;
}
return newVals;
}
func([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100); // => [16, 16, 17, 17, 17, 17]
func([33.333, 33.333, 33.333], 100); // => [34, 33, 33]
func([33.3, 33.3, 33.3, 0.1], 100); // => [34, 33, 33, 0]
func([13.25, 47.25, 11.25, 28.25], 100 ); // => [13, 48, 11, 28]
func( [25.5, 25.5, 25.5, 23.5], 100 ); // => [25, 25, 26, 24]
One last thing, I ran the function using the numbers originally given in the question to compare to the desired output
func([13.626332, 47.989636, 9.596008, 28.788024], 100); // => [48, 29, 13, 10]
This was different to what the question wanted => [ 48, 29, 14, 9]. I couldn't understand this until I looked at the total margin of error
-------------------------------------------------
| original | question | % diff | mine | % diff |
-------------------------------------------------
| 13.626332 | 14 | 2.74% | 13 | 4.5% |
| 47.989636 | 48 | 0.02% | 48 | 0.02% |
| 9.596008 | 9 | 6.2% | 10 | 4.2% |
| 28.788024 | 29 | 0.7% | 29 | 0.7% |
-------------------------------------------------
| Totals | 100 | 9.66% | 100 | 9.43% |
-------------------------------------------------
Essentially, the result from my function actually introduces the least amount of error.
Fiddle here
You can export a certificate using Firefox, this site has instructions. Then you use keytool to add the certificate.
If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr
function, like this
>>> chr(65)
'A'
similarly if you have 97,
>>> chr(97)
'a'
EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord
and the result has to be converted using unichr
instead of chr
.
>>> print unichr(ord(u'\u0B85'))
?
>>> print unichr(1 + ord(u'\u0B85'))
?
NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf
From CSS
video {
position: fixed; right: 0; bottom: 0;
min-width: 100%; min-height: 100%;
width: auto; height: auto; z-index: -100;
background: url(polina.jpg) no-repeat;
background-size: cover;
}
From the documentation:
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased
It really depends on your particular requirements, there's no "rule of thumb" for specifying an initial load factor.
Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.
Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.
I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.
Grinn solution is great.
However it doesn't work for me when there are parent folder relative references in the url.
i.e. url('../../images/car.png')
So, I slightly changed the Include
method in order to resolve the paths for each regex match, allowing relative paths and also to optionally embed the images in the css.
I also changed the IF DEBUG to check BundleTable.EnableOptimizations
instead of HttpContext.Current.IsDebuggingEnabled
.
public new Bundle Include(params string[] virtualPaths)
{
if (!BundleTable.EnableOptimizations)
{
// Debugging. Bundling will not occur so act normal and no one gets hurt.
base.Include(virtualPaths.ToArray());
return this;
}
var bundlePaths = new List<string>();
var server = HttpContext.Current.Server;
var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
foreach (var path in virtualPaths)
{
var contents = File.ReadAllText(server.MapPath(path));
var matches = pattern.Matches(contents);
// Ignore the file if no matches
if (matches.Count == 0)
{
bundlePaths.Add(path);
continue;
}
var bundlePath = (System.IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
var bundleFilePath = string.Format("{0}{1}.bundle{2}",
bundlePath,
System.IO.Path.GetFileNameWithoutExtension(path),
System.IO.Path.GetExtension(path));
// Transform the url (works with relative path to parent folder "../")
contents = pattern.Replace(contents, m =>
{
var relativeUrl = m.Groups[2].Value;
var urlReplace = GetUrlReplace(bundleUrlPath, relativeUrl, server);
return string.Format("url({0}{1}{0})", m.Groups[1].Value, urlReplace);
});
File.WriteAllText(server.MapPath(bundleFilePath), contents);
bundlePaths.Add(bundleFilePath);
}
base.Include(bundlePaths.ToArray());
return this;
}
private string GetUrlReplace(string bundleUrlPath, string relativeUrl, HttpServerUtility server)
{
// Return the absolute uri
Uri baseUri = new Uri("http://dummy.org");
var absoluteUrl = new Uri(new Uri(baseUri, bundleUrlPath), relativeUrl).AbsolutePath;
var localPath = server.MapPath(absoluteUrl);
if (IsEmbedEnabled && File.Exists(localPath))
{
var fi = new FileInfo(localPath);
if (fi.Length < 0x4000)
{
// Embed the image in uri
string contentType = GetContentType(fi.Extension);
if (null != contentType)
{
var base64 = Convert.ToBase64String(File.ReadAllBytes(localPath));
// Return the serialized image
return string.Format("data:{0};base64,{1}", contentType, base64);
}
}
}
// Return the absolute uri
return absoluteUrl;
}
Hope it helps, regards.
CSS 'fixed' solution (like Facebook does):
body_temp = $("<div class='body_temp' />")
.append($('body').contents())
.css('position', 'fixed')
.css('top', "-" + scrolltop + 'px')
.width($(window).width())
.appendTo('body');
to toggle to normal state:
var scrolltop = Math.abs($('.body_temp').position().top);
$('body').append($('.body_temp').contents()).scrollTop(scrolltop);
I would use Bootstrap's grid to achieve the desired result. The class="img-responsive" works nicely. Something like:
<div class="container-fluid">
<div class="row">
<div class="col-md-3"><img src="./pictures/placeholder.jpg" class="img-responsive" alt="Some picture" width="410" height="307"></div>
<div class="col-md-9"><h1>Heading</h1><p>Your Information.</p></div>
</div>
</div>
This will get you the most expensive car for the user:
SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
However, this statement makes me think that you want all of the cars prices sorted, descending:
So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?
So you could try this:
SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC
Try this way:
<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
select
helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options
.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
You're using the argument as a reference but actually it's a pointer. Change vector<int>*
to vector<int>&
. And you should really set search4
to something before using it.
You can also use vector::insert.
std::vector<int> v;
int a[5] = {2, 5, 8, 11, 14};
v.insert(v.end(), a, a+5);
Edit:
Of course, in real-world programming you should use:
v.insert(v.end(), a, a+(sizeof(a)/sizeof(a[0]))); // C++03
v.insert(v.end(), std::begin(a), std::end(a)); // C++11
Install new version of Dev c++. It works fine in Windows 8. It also supports 64 bit version.
Download link is http://sourceforge.net/projects/orwelldevcpp/ .
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
This is not a bug. Xcode assists can assist you. Select the target, to the left in the project Navigator. Click on "Validate settings" at the bottom of the settings. Xcode will check the settings and removes duplicates if possible.
Let me give an example for Including express module with require & import
-require
var express = require('express');
-import
import * as express from 'express';
So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,
var app = express();
So we use 'require' with 'CommonJS' and 'import' with 'ES6'.
For more info on 'require' & 'import', read through below links.
require - Requiring modules in Node.js: Everything you need to know
import - An Update on ES6 Modules in Node.js
my best solution to get the first is
df['my_column'].value_counts().sort_values(ascending=False).argmax()
If you use Robert Harder's Base64 utility, then you can do:
InputStream is = new Base64.InputStream(cph);
Or with sun's JRE, you can do:
InputStream is = new
com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream(cph)
However don't rely on that class continuing to be a part of the JRE, or even continuing to do what it seems to do today. Sun say not to use it.
There are other Stack Overflow questions about Base64 decoding, such as this one.
The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.
public class MinMaxValueOfArray {
public static void main(String[] args) {
int[] A = {2, 4, 3, 5, 5};
Arrays.sort(A);
int min = A[0];
int max = A[A.length -1];
System.out.println("Min Value = " + min);
System.out.println("Max Value = " + max);
}
}
this is the code for set method
public void setAge(int age){
this.age = age;
}
This is basically Muhammad Saqib's answer except two diffs:
1: Adds width and height function parameters.
2: This is a small nuance which can be ignored... Saying 'As Bitmap', instead of 'As Image'. 'As Image' does work just fine. I just prefer to match Return
types. See Image VS Bitmap Class.
Public Shared Function ResizeImage(ByVal InputBitmap As Bitmap, width As Integer, height As Integer) As Bitmap
Return New Bitmap(InputImage, New Size(width, height))
End Function
Ex.
Dim someimage As New Bitmap("C:\somefile")
someimage = ResizeImage(someimage,800,600)
exit() should always be called with an integer value and non-zero values are used as error codes.
See also: Use of exit() function
Use this code:
QFile inputFile(fileName);
if (inputFile.open(QIODevice::ReadOnly))
{
QTextStream in(&inputFile);
while (!in.atEnd())
{
QString line = in.readLine();
...
}
inputFile.close();
}
Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Regular expression:
\b[0-9]
Testing $?
is an anti-pattern.
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
Do a query:
SELECT * FROM v$session s;
Find your user and do the next query (with appropriate parameters):
ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>';
If your settings file is in a web app, they will be in teh web.config file (right below your project. If they are in any other type of project, they will be in the app.config file (also below your project).
Edit
As is pointed out in the comments: your design time application settings are in an app.config file for applications other than web applications. When you build, the app.config file is copied to the output directory, and will be named yourexename.exe.config. At runtime, only the file named yourexename.exe.config will be read.
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
If you don't want to think about having to call functions each time, you can create a Class that handles conversion for you.
class Decimal {
constructor(value = 0, scale = 4) {
this.intervalValue = value;
this.scale = scale;
}
get value() {
return this.intervalValue;
}
set value(value) {
this.intervalValue = Decimal.toDecimal(value, this.scale);
}
static toDecimal(val, scale) {
const factor = 10 ** scale;
return Math.round(val * factor) / factor;
}
}
Usage:
const d = new Decimal(0, 4);
d.value = 0.1 + 0.2; // 0.3
d.value = 0.3 - 0.2; // 0.1
d.value = 0.1 + 0.2 - 0.3; // 0
d.value = 5.551115123125783e-17; // 0
d.value = 1 / 9; // 0.1111
Of course, when dealing with Decimal there are caveats:
d.value = 1/3 + 1/3 + 1/3; // 1
d.value -= 1/3; // 0.6667
d.value -= 1/3; // 0.3334
d.value -= 1/3; // 0.0001
You'd ideally want to use a high scale (like 12), and then convert it down when you need to present it or store it somewhere. Personally, I did experiment with creating a UInt8Array and trying to create a precision value (much like the SQL Decimal type), but since Javascript doesn't let you overload operators, it just gets a bit tedious not being able to use basic math operators (+
, -
, /
, *
) and using functions instead like add()
, substract()
, mult()
. For my needs, it's not worth it.
But if you do need that level of precision and are willing to endure the use of functions for math, then I recommend the decimal.js library.
I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of utf-8
I think it's possible for database columns to have a different character set in MySQL. Here's the SQL QUERY I used:
ALTER TABLE database.table MODIFY COLUMN col VARCHAR(255)
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;
Windows Presentation Foundation 4.5 Cookbook by Pavel Yosifovich on page 155 in the section on "Using the common dialog boxes" says:
"What about folder selection (instead of files)? The WPF OpenFileDialog does not support that. One solution is to use Windows Forms' FolderBrowseDialog class. Another good solution is to use the Windows API Code Pack described shortly."
I downloaded the API Code Pack from Windows® API Code Pack for Microsoft® .NET Framework Windows API Code Pack: Where is it?, then added references to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll to my WPF 4.5 project.
Example:
using Microsoft.WindowsAPICodePack.Dialogs;
var dlg = new CommonOpenFileDialog();
dlg.Title = "My Title";
dlg.IsFolderPicker = true;
dlg.InitialDirectory = currentDirectory;
dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.DefaultDirectory = currentDirectory;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = false;
dlg.ShowPlacesList = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
var folder = dlg.FileName;
// Do something with selected folder string
}
readline is for string.. just use read
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
I had the same problem as Marko and come across a solution like this:
/*Create a Table*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Create a Stored Procedure*/
CREATE PROCEDURE GetGrandTotal
AS
/*Delete the 'tableGrandTotal' table for another usage of the stored procedure*/
DROP TABLE tableGrandTotal
/*Create a new Table which will include just one column*/
CREATE TABLE tableGrandTotal
(
columnGrandtotal int
)
/*Insert the query which returns subtotal for each orderitem row into tableGrandTotal*/
INSERT INTO tableGrandTotal
SELECT oi.Quantity * p.Price AS columnGrandTotal
FROM OrderItem oi
JOIN Product p ON oi.Id = p.Id
/*And return the sum of columnGrandTotal from the newly created table*/
SELECT SUM(columnGrandTotal) as [Grand Total]
FROM tableGrandTotal
And just simply use the GetGrandTotal Stored Procedure to retrieve the Grand Total :)
EXEC GetGrandTotal
I found another solution. Create qt.conf in the app folder as such:
[Paths]
Prefix = .
And then copy the plugins folder into the app folder and it works for me.
If there are are no duplicate elements or you don't care about them, then you can use the Set class:
a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false
Behind the scenes this uses
all? { |o| set.include?(o) }
I used the below method to migrate my GIT Stash to GitLab by maintaining all branches and commit history.
Clone the old repository to local.
git clone --bare <STASH-URL>
Create an empty repository in GitLab.
git push --mirror <GitLab-URL>
I think the answer to this is relevant too:
Summary: Windows 2012 Scheduled Tasks do not see the correct environment variables, including PATH
, for the account which the task is set to run as. But you can test for this, and if it is happening, and once you understand what is happening, you can work around it.
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
First create a temp table :
Step 1:
create table #tblOm_Temp (
Name varchar(100),
Age Int ,
RollNumber bigint
)
**Step 2: ** Insert Some value in Temp table .
insert into #tblom_temp values('Om Pandey',102,1347)
Step 3: Declare a table Variable to hold temp table data.
declare @tblOm_Variable table(
Name Varchar(100),
Age int,
RollNumber bigint
)
Step 4: select value from temp table and insert into table variable.
insert into @tblOm_Variable select * from #tblom_temp
Finally value is inserted from a temp table to Table variable
Step 5: Can Check inserted value in table variable.
select * from @tblOm_Variable
I read an embedded resource text file use:
/// <summary>
/// Converts to generic list a byte array
/// </summary>
/// <param name="content">byte array (embedded resource)</param>
/// <returns>generic list of strings</returns>
private List<string> GetLines(byte[] content)
{
string s = Encoding.Default.GetString(content, 0, content.Length - 1);
return new List<string>(s.Split(new[] { Environment.NewLine }, StringSplitOptions.None));
}
Sample:
var template = GetLines(Properties.Resources.LasTemplate /* resource name */);
template.ForEach(ln =>
{
Debug.WriteLine(ln);
});
There is supposedly a way to do it now with Ctrl + Alt + Click
but I use this extension because it has a bunch of other nice features that I use: https://marketplace.visualstudio.com/items?itemName=thomaswelen.SelectNextOccurrence
Enclose <img>
in <a>
tag.
<a href="http://www.google.com.pk"><img src="smiley.gif"></a>
it will open link on same tab, and if you want to open link on new tab then use target="_blank"
<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>
Using LINQ you can do it like this:
var table_enum = table
// Convert to IEnumerable<string>
.OfType<string>()
// Create anonymous type where Index1 and Index2
// reflect the indices of the 2-dim. array
.Select((_string, _index) => new {
Index1 = (_index / 2),
Index2 = (_index % 2), // ? I added this only for completeness
Value = _string
})
// Group by Index1, which generates IEnmurable<string> for all Index1 values
.GroupBy(v => v.Index1)
// Convert all Groups of anonymous type to String-Arrays
.Select(group => group.Select(v => v.Value).ToArray());
// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
// …
}
This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.
An image of how to in Android Studio 1.5.1.
Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
On an informal note, you can also call non-static member functions on temporaries:
MyClass().printInformation();
(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))
If you are using "table as", then specify it to delete.
In the example i delete all table_1 rows which are do not exists in table_2.
DELETE t1 FROM `table_1` t1 LEFT JOIN `table_2` t2 ON t1.`id` = t2.`id` WHERE t2.`id` IS NULL
Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:
Code:
from random import seed
from random import choice
seed(2)
numbers = [i for i in range(100)]
print(numbers)
for _ in range(50):
selection = choice(numbers)
print(selection)
Bear in mind, I've only experimented with MongoDB...
From what I've read, DynamoDB has come a long way in terms of features. It used to be a super-basic key-value store with extremely limited storage and querying capabilities. It has since grown, now supporting bigger document sizes + JSON support and global secondary indices. The gap between what DynamoDB and MongoDB offers in terms of features grows smaller with every month. The new features of DynamoDB are expanded on here.
Much of the MongoDB vs. DynamoDB comparisons are out of date due to the recent addition of DynamoDB features. However, this post offers some other convincing points to choose DynamoDB, namely that it's simple, low maintenance, and often low cost. Another discussion here of database choices was interesting to read, though slightly old.
My takeaway: if you're doing serious database queries or working in languages not supported by DynamoDB, use MongoDB. Otherwise, stick with DynamoDB.
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
YurkamTim is right. It needs only a modification:
After function($) you need a pointer to the external variable by "use(&$searchedValue)" and then you can access the external variable. Also you can modify it.
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use (&$searchedValue) {
return $e->id == $searchedValue;
}
);
You guys should also make sure that when you override onLayout
you HAVE to call super.onLayout
with all of the properties, or the view will not be inflated!
Here's the explanation I use in teaching Python classes:
An ITERABLE is:
for x in iterable: ...
oriter()
that will return an ITERATOR: iter(obj)
or__iter__
that returns a fresh ITERATOR,
or it may have a __getitem__
method suitable for indexed lookup.An ITERATOR is an object:
__next__
method that:
StopIteration
__iter__
method that returns self
).Notes:
__next__
method in Python 3 is spelt next
in Python 2, andnext()
calls that method on the object passed to it.For example:
>>> s = 'cat' # s is an ITERABLE
# s is a str object that is immutable
# s has no state
# s has a __getitem__() method
>>> t = iter(s) # t is an ITERATOR
# t has state (it starts by pointing at the "c"
# t has a next() method and an __iter__() method
>>> next(t) # the next() function returns the next value and advances the state
'c'
>>> next(t) # the next() function returns the next value and advances
'a'
>>> next(t) # the next() function returns the next value and advances
't'
>>> next(t) # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration
>>> iter(t) is t # the iterator is self-iterable
Late to the party:
Below is a solution that also deals with y < 0
as best as it can.
intmax_t
for maximum range. There is no provision for answers that do not fit in intmax_t
. powjii(0, 0) --> 1
which is a common result for this case.pow(0,negative)
, another undefined result, returns INTMAX_MAX
intmax_t powjii(int x, int y) {
if (y < 0) {
switch (x) {
case 0:
return INTMAX_MAX;
case 1:
return 1;
case -1:
return y % 2 ? -1 : 1;
}
return 0;
}
intmax_t z = 1;
intmax_t base = x;
for (;;) {
if (y % 2) {
z *= base;
}
y /= 2;
if (y == 0) {
break;
}
base *= base;
}
return z;
}
This code uses a forever loop for(;;)
to avoid the final base *= base
common in other looped solutions. That multiplication is 1) not needed and 2) could be int*int
overflow which is UB.
You can also use matches with regular expression like this:
boolean bool = List.matches("(?i).*SOME STRING HERE.*")
git checkout -b new-branch-name
git push remote-name new-branch-name :old-branch-name
You may have to manually switch to new-branch-name
before deleting old-branch-name
int roundUp (int numToRound, int multiple)
{
return multiple * ((numToRound + multiple - 1) / multiple);
}
although:
would suggest using unsigned integers instead, which has defined overflow behaviour.
You'll get an exception is multiple == 0, but it isn't a well-defined problem in that case anyway.
Older versions of IE do not support FormData ( Full browser support list for FormData is here: https://developer.mozilla.org/en-US/docs/Web/API/FormData).
Either you can use a jquery plugin (For ex, http://malsup.com/jquery/form/#code-samples ) or, you can use IFrame based solution to post multipart form data through ajax: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
ls -tQ | tail -n+4 | xargs rm
List filenames by modification time, quoting each filename. Exclude first 3 (3 most recent). Remove remaining.
EDIT after helpful comment from mklement0 (thanks!): corrected -n+3 argument, and note this will not work as expected if filenames contain newlines and/or the directory contains subdirectories.
You cannot instantiate an abstract class or interface. You must inherit it, if its an abstract class, or implement it if it's an interface. e.g.
...
private class User : IUser
{
...
}
User u = new User();
Adding in the following code works.
The problem is iPhones dont raise click events. They raise "touch" events. Thanks very much apple. Why couldn't they just keep it standard like everyone else? Anyway thanks Nico for the tip.
Credit to: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript
$(document).ready(function () {
init();
$(document).click(function (e) {
fire(e);
});
});
function fire(e) { alert('hi'); }
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type = "mousemove"; break;
case "touchend": type = "mouseup"; break;
default: return;
}
//initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init()
{
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
}
If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;
If the data is a local variable or a heap-allocated zone, clear it with memset
like:
memset(&m, 0, sizeof(myStruct));
Current compilers (e.g. recent versions of gcc
) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).
You could perhaps code myStruct m = {};
or myStruct m = {0};
(even if the first member of myStruct
is not a scalar).
My feeling is that using memset
for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).
<?php
error_reporting(0);
$change="";
$abc="";
define ("MAX_SIZE","4000");
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["file"]["name"];
$uploadedfile = $_FILES['file']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
$change='<div class="msgdiv">Unknown Image extension </div> ';
$errors=1;
}
else
{
$size=filesize($_FILES['file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
$change='<div class="msgdiv">You have exceeded the size limit!</div> ';
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
echo $scr;
list($width,$height)=getimagesize($uploadedfile);
$newwidth=45;
$newheight=45;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=90;
$newheight1=90;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
$tmp2=imagecreatetruecolor($width,$height);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);
imagecopyresampled($tmp2,$src,0,0,0,0,$width,$height,$width,$height);
$filename = "images/1-". $_FILES['file']['name']=time();
$filename1 = "images/2-". $_FILES['file']['name']=time();
$filename2 = "images/3-". $_FILES['file']['name']=time();
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagejpeg($tmp2,$filename2,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}
}
if(isset($_POST['Submit']) && !$errors)
{
// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' <div class="msgdiv">Image Uploaded Successfully!</div>';
}
?>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>picture demo</title>
<link href=".css" media="screen, projection" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery_002.js"></script>
<script type="text/javascript" src="js/displaymsg.js"></script>
<script type="text/javascript" src="js/ajaxdelete.js"></script>
<style type="text/css">
.help
{
font-size:11px; color:#006600;
}
body {
color: #000000;
background-color:#999999 ;
background:#999999 url(<?php echo $user_row['img_src']; ?>) fixed repeat top left;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
}
.msgdiv{
width:759px;
padding-top:8px;
padding-bottom:8px;
background-color: #fff;
font-weight:bold;
font-size:18px;-moz-border-radius: 6px;-webkit-border-radius: 6px;
}
#container{width:763px;margin:0 auto;padding:3px 0;text-align:left;position:relative; -moz-border-radius: 6px;-webkit-border-radius: 6px; background-color:#FFFFFF }
</style>
</head><body>
<div align="center" id="err">
<?php echo $change; ?> </div>
<div id="space"></div>
<div id="container" >
<div id="con">
<table width="502" cellpadding="0" cellspacing="0" id="main">
<tbody>
<tr>
<td width="500" height="238" valign="top" id="main_right">
<div id="posts">
<img src="<?php// echo $filename; ?>" /> <img src="<?php// echo $filename1; ?>" />
<form method="post" action="" enctype="multipart/form-data" name="form1">
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
<tr><Td style="height:25px"> </Td></tr>
<tr>
<td width="150"><div align="right" class="titles">Picture
: </div></td>
<td width="350" align="left">
<div align="left">
<input size="25" name="file" type="file" style="font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10pt" class="box"/>
</div></td>
</tr>
<tr><Td></Td>
<Td valign="top" height="35px" class="help">Image maximum size <b>4000 </b>kb</span></Td>
</tr>
<tr><Td></Td><Td valign="top" height="35px"><input type="submit" id="mybut" value=" Upload " name="Submit"/></Td></tr>
<tr>
<td width="200"> </td>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200" align="center"><div align="left"></div></td>
<td width="100"> </td>
</tr>
</table></td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body></html>
To resolve this issue, you have to delete the .snap file located in the directory:
<workspace-directory>\.metadata\.plugins\org.eclipse.core.resources
.
After deleting this file, you could start Eclipse with no problem.
Client need to send base64 to server.
And above answer described code is work perfectly:
$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
Thanks
your log files shows it is stopping on error "0x8004C000"
From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):
Setup Status
Block
Restart not required
0x80044000 [-2147205120]
Restart required
0x8004C000 [-2147172352]
Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).
Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":
class AddColumnToWidgets < ActiveRecord::Migration
def change
add_column :widgets, :colour, :string, default: 'red'
end
end
This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.
For MAC or Linux:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--kiosk");
driver = new ChromeDriver(chromeOptions);
For Windows:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);
I ran into this problem with templated classes. Here's a more general solution I had to use:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// Friend means operator<< can use private variables
// It needs to be declared as a template, but T is taken
template <class U>
friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}
// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
obj.toString(os);
return os;
}
Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.
The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(
Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.
This works too:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// For some reason this requires using T, and not U as above
friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
{
obj.toString(os);
return os;
}
}
I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.
Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.
As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.
After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext
.
So, my logic follows below:
Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing
.
Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume
)
Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail
(which is also a product ID) along with some other values.
The possible productIds are provided here.
To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext
and try to see if any name has a prefix o365
, if it finds it then its O365. If it does not, then its Office 2019.
Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.
Hope this will help whoever's interest.
Since multi-window mode is available now, your app may not have statusbar on top.
Following solution handle all the cases automatically for you.
android:fitsSystemWindows="true"
or programatically
findViewById(R.id.your_root_view).setFitsSystemWindows(true);
you may also get root view by
findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)
For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177
The main problem you may find with changing overflow to auto
or hidden
is that everything can become scrollable with the middle mouse buttom and a user can mess up the entire site layout.
I ran into the exact same issue. After compiling without the -fexceptions
build flag, the file compiled with no issue
@sedit was on the right path, but it's a bit awkward to define a variable.
The way to do this in bash is to put a dollar sign in front of your single quoted string.
$ echo -e '1\n2\n3'
1
2
3
$ echo -e '1\n2\n3' | sed 's/.*/\t&/g'
t1
t2
t3
$ echo -e '1\n2\n3' | sed $'s/.*/\t&/g'
1
2
3
If your string needs to include variable expansion, you can put quoted strings together like so:
$ timestamp=$(date +%s)
$ echo -e '1\n2\n3' | sed "s/.*/$timestamp"$'\t&/g'
1491237958 1
1491237958 2
1491237958 3
In bash $'string'
causes "ANSI-C expansion". And that is what most of us expect when we use things like \t
, \r
, \n
, etc. From: https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html#ANSI_002dC-Quoting
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded...
The expanded result is single-quoted, as if the dollar sign had not been present.
I personally think most efforts to avoid bash are silly because avoiding bashisms does NOT* make your code portable. (Your code will be less brittle if you shebang it to bash -eu
than if you try to avoid bash and use sh
[unless you are an absolute POSIX ninja].) But rather than have a religious argument about that, I'll just give you the BEST* answer.
$ echo -e '1\n2\n3' | sed "s/.*/$(printf '\t')&/g"
1
2
3
* BEST answer? Yes, because one example of what most anti-bash shell scripters would do wrong in their code is use echo '\t'
as in @robrecord's answer. That will work for GNU echo, but not BSD echo. That is explained by The Open Group at http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html#tag_20_37_16 And this is an example of why trying to avoid bashisms usually fail.
function getOnemonthBefore($date){
$day = intval(date("t", strtotime("$date")));//get the last day of the month
$month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
return $month_date;
}
The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.
NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.
Version 5.5 of PHP will have built-in support for BCrypt, the functions password_hash()
and password_verify()
. Actually these are just wrappers around the function crypt()
, and shall make it easier to use it correctly. It takes care of the generation of a safe random salt, and provides good default values.
The easiest way to use this functions will be:
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This code will hash the password with BCrypt (algorithm 2y
), generates a random salt from the OS random source, and uses the default cost parameter (at the moment this is 10). The second line checks, if the user entered password matches an already stored hash-value.
Should you want to change the cost parameter, you can do it like this, increasing the cost parameter by 1, doubles the needed time to calculate the hash value:
$hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));
In contrast to the "cost"
parameter, it is best to omit the "salt"
parameter, because the function already does its best to create a cryptographically safe salt.
For PHP version 5.3.7 and later, there exists a compatibility pack, from the same author that made the password_hash()
function. For PHP versions before 5.3.7 there is no support for crypt()
with 2y
, the unicode safe BCrypt algorithm. One could replace it instead with 2a
, which is the best alternative for earlier PHP versions.
Follow these steps to change an app's name in Django:
views.py
, urls.py
, 'manage.py' , and settings.py
files.django_content_type
with the following command: UPDATE django_content_type SET app_label='<NewAppName>' WHERE app_label='<OldAppName>'
ALTER TABLE <oldAppName>_modelName RENAME TO <newAppName>_modelName
. For mysql too I think it is the same (as mentioned by @null_radix)django_migrations
table to avoid having your previous migrations re-run: UPDATE django_migrations SET app='<NewAppName>' WHERE app='<OldAppName>'
. Note: there is some debate (in comments) if this step is required for Django 1.8+; If someone knows for sure please update here.models.py
's Meta Class has app_name
listed, make sure to rename that too (mentioned by @will).static
or templates
folders inside your app, you'll also need to rename those. For example, rename old_app/static/old_app
to new_app/static/new_app
.models
, you'll need to change django_content_type.name
entry in DB. For postgreSQL use UPDATE django_content_type SET name='<newModelName>' where name='<oldModelName>' AND app_label='<OldAppName>'
Meta point (If using virtualenv): Worth noting, if you are renaming the directory that contains your virtualenv, there will likely be several files in your env that contain an absolute path and will also need to be updated. If you are getting errors such as ImportError: No module named ...
this might be the culprit. (thanks to @danyamachine for providing this).
Other references: you might also want to refer the below links for a more complete picture
The sqlite3 .import command won't work for ordinary csv data because it treats any comma as a delimiter even in a quoted string.
This includes trying to re-import a csv file that was created by the shell:
Create table T (F1 integer, F2 varchar);
Insert into T values (1, 'Hey!');
Insert into T values (2, 'Hey, You!');
.mode csv
.output test.csv
select * from T;
Contents of test.csv:
1,Hey!
2,"Hey, You!"
delete from T;
.import test.csv T
Error: test.csv line 2: expected 2 columns of data but found 3
It seems we must transform the csv into a list of Insert statements, or perhaps a different delimiter will work.
Over at SuperUser I saw a suggestion to use LogParser to deal with csv files, I'm going to look into that.
Are the classes imported? Try pressing CTRL
+ SHIFT
+ O
to resolve the imports. If this does not work you need to include the application servers runtime libraries.
Remove below code
s.send("Hello server!")
because your sending s.send("Hello server!")
to server, so your output file is somewhat more in size.
You can try element[0].scrollTop, in my opinion this solution is faster.
Here you have bigger example - http://cvmlrobotics.blogspot.de/2013/03/angularjs-get-element-offset-position.html
you can try binding property whit route
in your component.ts
user:any = 'linkABC'
;
in your component.html
<a target="_blank" href="yourtab/{{user}}">new tab </a>
It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
In addition to Andrew's and Max's solutions, using iframe.focus() resulted in printing parent frame instead of printing only child iframe in IE8. Changing that line fixed it:
function printIframe(id)
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printPage();
return false;
}
From http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas_take_2:
Note: If the paste operation back to Excel doesn't work correctly, chances are that you've used Excel's Text-to-Columns feature recently, and Excel is trying to be helpful by remembering how you last parsed your data. You need to fire up the Convert Text to Columns Wizard. Choose the Delimited option and click Next. Clear all of the Delimiter option checkmarks except Tab.
Or, from http://spreadsheetpage.com/index.php/tip/making_an_exact_copy_of_a_range_of_formulas/:
If you're a VBA programmer, you can simply execute the following code:
With Sheets("Sheet1")
.Range("A11:D20").Formula = .Range("A1:D10").Formula
End With
you don't have the "google-collections" library on your classpath.
There are a number of ways to add libraries to your classpath, so please provide more info regarding how you are executing your program.
if from the command line, you can add libraries to the classpath via
java -classpath path/lib.jar ...
Best answer is just removeAttribute
element.removeAttribute("disabled");
Just found this answer from another link,
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
Just add those below line in pom.xml file on the top of <modelversion>
tag:
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
Maybe this will help... this was used in the full size jQuery calendar click event (http://arshaw.com/fullcalendar/)... but it can be used more generally to deal with fancybox being launched by jQuery.
eventClick: function(calEvent, jsEvent, view) {
jQuery("body").after('<a id="link_'+calEvent.url+'" style="display: hidden;" href="http://thisweekinblackness.com/wp-content/uploads/2009/01/steve-urkel.jpg">Steve</a>');
jQuery('#link_'+calEvent.url).fancybox();
jQuery('#link_'+calEvent.url).click();
jQuery('#link_'+calEvent.url).remove();
return false;
}
You cannot exactly get a list of commands started with nohup
but you can see them along with your other processes by using the command ps x
. Commands started with nohup
will have a question mark in the TTY column.
On Fedora I do locate ~/.ssh
which tells me keys are at
/root/.ssh
/root/.ssh/authorized_keys
Use the fromkeys
function to initialize a dictionary with any default value. In your case, you will initialize with None
since you don't have a default value in mind.
empty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dict
as:
empty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None
, you can do:
default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
There are two ways of installing the Git plugin in Eclipse
Both methods may need you to restart Eclipse in the middle. For the step by step guide on installing and configuring Git plugin in Eclipse, you can also refer to Install and configure git plugin in Eclipse
For some strange reason, you can use the += operator to add shorts.
short answer = 0;
short firstNo = 1;
short secondNo = 2;
answer += firstNo;
answer += secondNo;
For those who like to work close to the metal, here is a command that will clear out the unwanted soot, without needing any special tools or scripts:
adb logcat "eglCodecCommon:S"
Easy... Using two copies of same image with different scale on the sprite's sheet. Set the Coords and size on the app's logic.
this.myService.getConfig().subscribe(
(res) => console.log(res),
(err) => console.log(err),
() => console.log('done!')
);
You can emulate it like this:
countDownLatch = {
count: 0,
check: function() {
this.count--;
if (this.count == 0) this.calculate();
},
calculate: function() {...}
};
then each async call does this:
countDownLatch.count++;
while in each asynch call back at the end of the method you add this line:
countDownLatch.check();
In other words, you emulate a count-down-latch functionality.
push is a native javascript method. You could use it like this:
var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]
My solution
ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS%
shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd
:
@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f
And then execute like this:
GetNumberOfCores.cmd
echo %NumberOfCores%
The script will set a environment variable named %NumberOfCores%
and it will contain the number of processors.
For others who may need this, here's an answer.
Use adb shell dumpsys alarm
You can know the alarm has been set and when are they going to alarmed and interval. Also how many times this alarm has been invoked.
You can also use inspect.getdoc
. It cleans up the __doc__
by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.
As a complement to the answer of @martin-r one should note that it is possible to use the sum/difference formula for arcus tangens.
angle = atan2(vec2.y, vec2.x) - atan2(vec1.y, vec1.x);
angle = -atan2(vec1.x * vec2.y - vec1.y * vec2.x, dot(vec1, vec2))
where dot = vec1.x * vec2.x + vec1.y * vec2.y
I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.
add true in the second param.
Directory.Delete(path, true);
It will remove all.
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}