If you just want to pause/stop animation smoothly
self.yourView.layer.speed = 0;
As Ben said, you'll need to work with the UIView's
layer, using a CATransform3D
to perform the layer's
rotation
. The trick to get perspective working, as described here, is to directly access one of the matrix cells
of the CATransform3D
(m34). Matrix math has never been my thing, so I can't explain exactly why this works, but it does. You'll need to set this value to a negative fraction for your initial transform, then apply your layer rotation transforms to that. You should also be able to do the following:
Objective-C
UIView *myView = [[self subviews] objectAtIndex:0];
CALayer *layer = myView.layer;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = 1.0 / -500;
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0f * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
layer.transform = rotationAndPerspectiveTransform;
Swift 5.0
if let myView = self.subviews.first {
let layer = myView.layer
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 45.0 * .pi / 180.0, 0.0, 1.0, 0.0)
layer.transform = rotationAndPerspectiveTransform
}
which rebuilds the layer transform from scratch for each rotation.
A full example of this (with code) can be found here, where I've implemented touch-based rotation and scaling on a couple of CALayers
, based on an example by Bill Dudney. The newest version of the program, at the very bottom of the page, implements this kind of perspective operation. The code should be reasonably simple to read.
The sublayerTransform
you refer to in your response is a transform that is applied to the sublayers of your UIView's
CALayer
. If you don't have any sublayers, don't worry about it. I use the sublayerTransform in my example simply because there are two CALayers
contained within the one layer that I'm rotating.
I have been using the latter for a lot of nice lightweight animations. You can use it crossfade two views, or fade one in in front of another, or fade it out. You can shoot a view over another like a banner, you can make a view stretch or shrink... I'm getting a lot of mileage out of beginAnimation
/commitAnimations
.
Don't think that all you can do is:
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myview cache:YES];
Here is a sample:
[UIView beginAnimations:nil context:NULL]; {
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelegate:self];
if (movingViewIn) {
// after the animation is over, call afterAnimationProceedWithGame
// to start the game
[UIView setAnimationDidStopSelector:@selector(afterAnimationProceedWithGame)];
// [UIView setAnimationRepeatCount:5.0]; // don't forget you can repeat an animation
// [UIView setAnimationDelay:0.50];
// [UIView setAnimationRepeatAutoreverses:YES];
gameView.alpha = 1.0;
topGameView.alpha = 1.0;
viewrect1.origin.y = selfrect.size.height - (viewrect1.size.height);
viewrect2.origin.y = -20;
topGameView.alpha = 1.0;
}
else {
// call putBackStatusBar after animation to restore the state after this animation
[UIView setAnimationDidStopSelector:@selector(putBackStatusBar)];
gameView.alpha = 0.0;
topGameView.alpha = 0.0;
}
[gameView setFrame:viewrect1];
[topGameView setFrame:viewrect2];
} [UIView commitAnimations];
As you can see, you can play with alpha, frames, and even sizes of a view. Play around. You may be surprised with its capabilities.
This was working for me:
[UIView animateWithDuration:1.0
animations:^
{
self.imageView.transform = CGAffineTransformMakeRotation(M_PI);
self.imageView.transform = CGAffineTransformMakeRotation(0);
}];
Try something like this:
#include <signal.h>
pid_t child_pid = -1 ; //Global
void kill_child(int sig)
{
kill(child_pid,SIGKILL);
}
int main(int argc, char *argv[])
{
signal(SIGALRM,(void (*)(int))kill_child);
child_pid = fork();
if (child_pid > 0) {
/*PARENT*/
alarm(30);
/*
* Do parent's tasks here.
*/
wait(NULL);
}
else if (child_pid == 0){
/*CHILD*/
/*
* Do child's tasks here.
*/
}
}
Besides all of above,I have two ideas.
You can add an element that imitates the palceholder.Then using javascript control the element showing and hiding.
But it is so complex,the other one is using the brother's selector of css.Just like this:
.placeholder { position: absolute; font-size: 14px; left: 40px; top: 11px; line-height: 1; pointer-events: none; }_x000D_
.send-message input:focus + .placeholder { display: none; }
_x000D_
23333,I have a poor English.Hope solve your problem.
Actually more sane sources are provided by http://suckless.org look at their sbase
repository:
git clone git://git.suckless.org/sbase
They are clearer, smarter, simpler and suckless, eg ls.c
has just 369 LOC
After that it will be easier to understand more complicated GNU code.
I used easyengine to set up my vultr cloud based server.
I found my bash file at /etc/bash.bashrc
.
So source /etc/bash.bashrc
did the trick for me!
update
When setting up a bare server (ubuntu 16.04), you can use the above info, when you have not yet set up a username, and are logging in via root.
It's best to create a user (with sudo privledges), and login as this username instead.
This will create a directory for your settings, including .profile and .bashrc files.
https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/
Now, you will edit and (and "source") the ~/.bashrc
file.
On my server, this was located at /home/your_username/.bashrc
(where your_username
is actually the new username you created above, and now login with)
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
I had a slightly different problem. The credential problem was for the underlying user running the application, not the user trying to login. One way to test this is to go to IIS Management -> Sites -> Your Site -> Basic Settings -> Test Settings.
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
Edit: Unfortunately, as of PHP 8.0, the answer is not "No, not anymore". This RFC was not accepted as I hoped, proposing to change T_PAAMAYIM_NEKUDOTAYIM
to T_DOUBLE_COLON
; but it was declined.
Note: I keep this answer for historical purposes. Actually, because of the creation of the RFC and the votes ratio at some point, I created this answer. Also, I keep this for hoping it to be accepted in the near future.
I found the default JS date formatting didn't work.
So I used toLocaleString
with options
const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);
to get: DD/MM/YYYY format
See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))
We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.
When the user selects an option, we can push the value of that onto the current route with:
history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});
pathname
can be the current path. In your case params
would look something like:
{
selectedOption: 5
}
Then at the top level of the React tree, React Router will update the props
of that component with a prop of location.search
which is the encoded value we set earlier, so there will be something in componentWillReceiveProps
like:
params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});
Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.
React Router: https://github.com/reactjs/react-router
History: https://github.com/ReactTraining/history
The query string library: https://github.com/ljharb/qs
exec sp_lock
This query should give you existing locks.
exec sp_who SPID -- will give you some info
Having spids, you could check activity monitor(processes tab) to find out what processes are locking the tables ("details" for more info and "kill process" to kill it).
You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..
Your question "what are they" is already answered above.
As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:
_isnan(), _isfinite(), and _fpclass()
On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
This example I find self-explanatory. Notice how await waits for the result and so you miss the Promise being returned.
cryA = crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
Promise {<pending>}
cryB = await crypto.subtle.generateKey({name:'ECDH', namedCurve:'P-384'}, true, ["deriveKey", "deriveBits"])
{publicKey: CryptoKey, privateKey: CryptoKey}
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
I suggest you use a HiddenField inside template field use FindControl to find this field.
ie:
ASPX
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind
protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gv1 = (GridView)sender;
GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];
//get hidden field value and not directly from the GridviewRow, as that will be null or empty!
HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
if (hf1 != null)
{
..
}
}
First create table without auto_increment,
CREATE TABLE `members`(
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL
PRIMARY KEY (memberid)
) ENGINE = MYISAM;
after set id as index,
ALTER TABLE `members` ADD INDEX(`id`);
after set id as auto_increment,
ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
Or
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL,
PRIMARY KEY (`memberid`),
KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
If it's your root module just add it to PYTHONPATH
(PyCharm usually does that)
export PYTHONPATH=$PYTHONPATH:<root module path>
for Docker:
ENV PYTHONPATH="${PYTHONPATH}:<root module path in container>"
You can do it in two different ways.
Option 1: The -eq
operator
>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False
Option 2: The .Equals()
method of the string
object. Because strings in PowerShell are .Net System.String
objects, any method of that object can be called directly.
>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method
List of System.String
methods follows.
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
Solved by adding
@XmlSchema(
namespace = "http://www.example.com/a",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = {
@XmlNs(prefix="ns1", namespaceURI="http://www.example.com/a")
}
)
package authenticator.beans.login;
import javax.xml.bind.annotation.*;
in package-info.java
Took help of jaxb-namespaces-missing : Answer provided by Blaise Doughan
Use this:
myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';
Or, if you are using jQuery:
$(myFunction).extend({
bookName:'mybook',
bookdesc: 'new'
});
The push
method is wrong because it belongs to the Array.prototype
object.
To create a named object, try this:
var myObj = function(){
this.property = 'foo';
this.bar = function(){
}
}
myObj.prototype.objProp = true;
var newObj = new myObj();
try the below command, it should work
- shell: ls -1 /some/dir
register: contents
- file: path=/some/dir/{{ item }} state=absent
with_items: {{ contents.stdout_lines }}
JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.
I use this approach when populating dropdown lists in my KnockoutJS model. E.g.
var desktopGrpViewModel = {
availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);
...
<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true"
data-bind="options: availableComputeOffering,
optionsText: 'Name',
optionsValue: 'Id',
value: desktopGrpComputeOfferingSelect,
optionsCaption: 'Choose...'">
</select>
Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.
I had issue with the solutions mentioned above as specifying the string key would give me javax.el.PropertyNotFoundException. The code shown below worked for me. In this I used status to count the index of for each loop and displayed the value of index I am interested on
<c:forEach items="${requestScope.key}" var="map" varStatus="status" >
<c:if test="${status.index eq 1}">
<option><c:out value=${map.value}/></option>
</c:if>
</c:forEach>
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc
by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
.
to my /home/xy/.bashrc
file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH
variable, by run -> edit Configuration.
I think this could work:
select * from tbl where statusid = isnull(@statusid,statusid)
Note that if you're not doing math, there's nothing wrong with asserting exact floating point values. For instance:
public interface Foo {
double getDefaultValue();
}
public class FooImpl implements Foo {
public double getDefaultValue() { return Double.MIN_VALUE; }
}
In this case, you want to make sure it's really MIN_VALUE
, not zero or -MIN_VALUE
or MIN_NORMAL
or some other very small value. You can say
double defaultValue = new FooImpl().getDefaultValue();
assertEquals(Double.MIN_VALUE, defaultValue);
but this will get you a deprecation warning. To avoid that, you can call assertEquals(Object, Object)
instead:
// really you just need one cast because of autoboxing, but let's be clear
assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
And, if you really want to look clever:
assertEquals(
Double.doubleToLongBits(Double.MIN_VALUE),
Double.doubleToLongBits(defaultValue)
);
Or you can just use Hamcrest fluent-style assertions:
// equivalent to assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
assertThat(defaultValue, is(Double.MIN_VALUE));
If the value you're checking does come from doing some math, though, use the epsilon.
I achieved this with the code below.
First, you flex the container which makes the input and the icon be on the same line. Aligning items makes them be on the same level.
Then, make the input take up 100% of the width regardless. Give the icon absolute positioning which allows it to overlap with the input.
Then add right padding to the input so the text typed in doesn't get to the icon. And finally use the right
css property to give the icon some space from the edge of the input.
Note: The Icon
tag could be a real icon if you are working with ReactJs or a placeholder for any other way you work with icons in your project.
.inputContainer {
display: flex;
align-items: center;
position: relative;
}
.input {
width: 100%;
padding-right: 40px;
}
.inputIcon {
position: absolute;
right: 10px;
}
_x000D_
<div class="inputContainer">
<input class="input" />
<Icon class="inputIcon" />
</div>
_x000D_
You can try c#
public string ProcessMyDataItem(object myValue)
{
if (myValue == null)
{
return "0 %"";
}
else
{
if(Convert.ToInt32(myValue) < 50)
return "0";
else
return myValue.ToString() + "%";
}
}
asp
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: normal">
Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
</div>
This is how we do it:
private static void OverrideDefaultFont(string defaultFontNameToOverride, string customFontFileNameInAssets, AssetManager assets)
{
//Load custom Font from File
Typeface customFontTypeface = Typeface.CreateFromAsset(assets, customFontFileNameInAssets);
//Get Fontface.Default Field by reflection
Class typeFaceClass = Class.ForName("android.graphics.Typeface");
Field defaultFontTypefaceField = typeFaceClass.GetField(defaultFontNameToOverride);
defaultFontTypefaceField.Accessible = true;
defaultFontTypefaceField.Set(null, customFontTypeface);
}
Try to use this command :
date | cut -d " " -f2-4 | tr " " "-"
The output would be like: 21-Feb-2021
ok, how about this one-liner
const raw = {
item1: { key: 'sdfd', value: 'sdfd' },
item2: { key: 'sdfd', value: 'sdfd' },
item3: { key: 'sdfd', value: 'sdfd' }
};
const filteredKeys = ['item1', 'item3'];
const filtered = Object.assign({}, ...filteredKeys.map(key=> ({[key]:raw[key]})));
now include bootstrap 4:
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css');
and code should be like this:
<div class="row">
<div class="col-lg-6 col-md-6" style="border:solid 1px red">elements 1</div>
<div class="col-lg-6 col-md-6" style="border:solid 1px red">
<div class="pull-lg-right pull-xl-right">
elements 2
</div>
</div>
</div>
If you are using a string resource xml file (supports HTML tags), it can be done using<b> </b>
, <i> </i>
and <u> </u>
.
<resources>
<string name="your_string_here">
This is an <u>underline</u>.
</string>
</resources>
If you want to underline something from code use:
TextView tv = (TextView) view.findViewById(R.id.tv);
SpannableString content = new SpannableString("Content");
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
tv.setText(content);
Hope this helps
I had the same problem. I tried to create a table in mysql and got the same error. I restarted mysql server and ran the command and was able to create/migrate table after restating.
My fix for this was my child table needed to be populated before the parent table.
I had two tables: UserDetails and Login linked by an email address. I therefore had to insert into the UserDetails first before inserting into the Login table:
insert into UserDetails (Email, Name, Telephone, Department) values ('Email', 'Name', 'number', 'IT');
Then:
insert into Login (UserID, UserType, Email, Username, Password) VALUES (001, 'SYS-USR-ADMIN', 'Email', 'Name', 'Password')
Here's a simple wrapper for steven's answer. This function doesn't do repeated runs/averaging, just saves you from having to repeat the timing code everywhere :)
'''function which prints the wall time it takes to execute the given command'''
def time_func(func, *args): #*args can take 0 or more
import time
start_time = time.time()
func(*args)
end_time = time.time()
print("it took this long to run: {}".format(end_time-start_time))
You can also try dropping the index column if it is not needed to compare:
print(df1.reset_index(drop=True) == df2.reset_index(drop=True))
I have used this same technique in a unit test like so:
from pandas.util.testing import assert_frame_equal
assert_frame_equal(actual.reset_index(drop=True), expected.reset_index(drop=True))
To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).
At startup, we do:
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
And set the desired timezone to the DateFormat:
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))
[Vue warn]: Property or method "changeSetting" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <MainTable>)
The error is occurring because the changeSetting
method is being referenced in the MainTable
component here:
"<button @click='changeSetting(index)'> Info </button>" +
However the changeSetting
method is not defined in the MainTable
component. It is being defined in the root component here:
var app = new Vue({
el: "#settings",
data: data,
methods: {
changeSetting: function(index) {
data.settingsSelected = data.settings[index];
}
}
});
What needs to be remembered is that properties and methods can only be referenced in the scope where they are defined.
Everything in the parent template is compiled in parent scope; everything in the child template is compiled in child scope.
You can read more about component compilation scope in Vue's documentation.
So far there has been a lot of talk about defining things in the correct scope so the fix is just to move the changeSetting
definition into the MainTable
component?
It seems that simple but here's what I recommend.
You'd probably want your MainTable
component to be a dumb/presentational component. (Here is something to read if you don't know what it is but a tl;dr is that the component is just responsible for rendering something – no logic). The smart/container element is responsible for the logic – in the example given in your question the root component would be the smart/container component. With this architecture you can use Vue's parent-child communication methods for the components to interact. You pass down the data for MainTable
via props and emit user actions from MainTable
to its parent via events. It might look something like this:
Vue.component('main-table', {
template: "<ul>" +
"<li v-for='(set, index) in settings'>" +
"{{index}}) " +
"{{set.title}}" +
"<button @click='changeSetting(index)'> Info </button>" +
"</li>" +
"</ul>",
props: ['settings'],
methods: {
changeSetting(value) {
this.$emit('change', value);
},
},
});
var app = new Vue({
el: '#settings',
template: '<main-table :settings="data.settings" @change="changeSetting"></main-table>',
data: data,
methods: {
changeSetting(value) {
// Handle changeSetting
},
},
}),
The above should be enough to give you a good idea of what to do and kickstart resolving your issue.
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
$location won't help you with external URLs, use the $window service instead:
$window.location.href = 'http://www.google.com';
Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.
in linux os such as Debian or Ubutu you can simply try this ways, for first time remove phpmyadmin with --purge parameter:
sudo apt-get remove --purge phpmyadmin
then install again
sudo apt-get install phpmyadmin
thats work fine :)
If anyone is interested, there is a jquery plugin called: jquery.matchHeight.js
https://github.com/liabru/jquery-match-height
matchHeight makes the height of all selected elements exactly equal. It handles many edge cases that cause similar plugins to fail.
For a row of cards, I use:
<div class="row match-height">
Then enable site-wide:
$('.row.match-height').each(function() {
$(this).find('.card').not('.card .card').matchHeight(); // Not .card .card prevents collapsible cards from taking height
});
Red-Black trees:
\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):
$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
You can use the --detach-keys
option when you run docker attach
to override the default CTRL+P, CTRL + Q sequence (that doesn't always work).
For example, when you run docker attach --detach-keys="ctrl-a" test
and you press CTRL+A you will exit the container, without killing it.
Other examples:
docker attach --detach-keys="ctrl-a,x" test
- press CTRL+A
and then X
to exitdocker attach --detach-keys="a,b,c" test
- press A
, then B
, then C
to exitExtract from the official documentation:
If you want, you can configure an override the Docker key sequence for detach. This is useful if the Docker default sequence conflicts with key sequence you use for other applications. There are two ways to define your own detach key sequence, as a per-container override or as a configuration property on your entire configuration.
To override the sequence for an individual container, use the --detach-keys="<sequence>"
flag with the docker attach command. The format of the <sequence>
is either a letter [a-Z]
, or the ctrl-
combined with any of the following:
These a
, ctrl-a
, X
, or ctrl-\\
values are all examples of valid key sequences. To configure a different configuration default key sequence for all containers, see Configuration file section.
Note: This works since docker version 1.10+ (at the time of this answer, the current version is 18.03)
This checks if the array is empty
if (!empty($result) {
// do stuf if array is not empty
} else {
// do stuf if array is empty
}
This checks if the array is null or not
if (is_null($result) {
// do stuf if array is null
} else {
// do stuf if array is not null
}
I'm assuming you have fromPath (an absolute path for a folder), and toPath (an absolute path for a folder/file), and your're looking for a path that with represent the file/folder in toPath as a relative path from fromPath (your current working directory is fromPath) then something like this should work:
public static String getRelativePath(String fromPath, String toPath) {
// This weirdness is because a separator of '/' messes with String.split()
String regexCharacter = File.separator;
if (File.separatorChar == '\\') {
regexCharacter = "\\\\";
}
String[] fromSplit = fromPath.split(regexCharacter);
String[] toSplit = toPath.split(regexCharacter);
// Find the common path
int common = 0;
while (fromSplit[common].equals(toSplit[common])) {
common++;
}
StringBuffer result = new StringBuffer(".");
// Work your way up the FROM path to common ground
for (int i = common; i < fromSplit.length; i++) {
result.append(File.separatorChar).append("..");
}
// Work your way down the TO path
for (int i = common; i < toSplit.length; i++) {
result.append(File.separatorChar).append(toSplit[i]);
}
return result.toString();
}
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
- Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew()
but the animation displayed properly when I switched to Task.Run()
.
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.
SELECT ISNUMERIC('2.81104e+006')
returns 1
.
SELECT convert(decimal(15,2), '2.81104e+006')
returns
error: Error converting data type varchar to numeric.
And
SELECT try_convert(decimal(15,2), '2.81104e+006')
returns NULL
.
SELECT convert(float, '2.81104e+006')
returns the correct value 2811040
.
Use
git clone --depth=1 --branch=master git://someserver/somerepo dirformynewrepo
rm -rf ./dirformynewrepo/.git
dirformynewrepo
not a Git repository any more.Try the arithmetic-expression version of for
:
max=10
for (( i=2; i <= $max; ++i ))
do
echo "$i"
done
This is available in most versions of bash, and should be Bourne shell (sh) compatible also.
Here is my code without using any other data structure like set or hashmap
for (int i = 0; i < Models.size(); i++){
for (int j = i + 1; j < Models.size(); j++) {
if (Models.get(i).getName().equals(Models.get(j).getName())) {
Models.remove(j);
j--;
}
}
}
This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.
"If path2 contains an absolute path, this method returns path2."
Here's the actual Combine method from the .NET source. You can see that it calls CombineNoChecks, which then calls IsPathRooted on path2 and returns that path if so:
public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().
Nunit doesnt work well with mixed-mode projects in C++ so I had to drop it
I have modified the Coop's answer. Please check the example FIDDLE Here's my edits:
$(window).scroll(function(){
if ($(window).scrollTop() >= 330) {
$('.sticky-header').addClass('fixed');
}
else {
$('.sticky-header').removeClass('fixed');
}
});
You could use a regex to find out if the String contains a number. Take a look at the matches()
method.
This is a method reference in Java 8. The oracle documentation is here.
As stated in the documentation...
The method reference Person::compareByAge is a reference to a static method.
The following is an example of a reference to an instance method of a particular object:
class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
The method reference myComparisonProvider::compareByName invokes the method compareByName that is part of the object myComparisonProvider. The JRE infers the method type arguments, which in this case are (Person, Person).
I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like
$redis->set('persons', $persons)
Later I decided to change to "hSet" method, and I tried it this way
foreach($persons as $person){
$redis->hSet('persons', $person->id, $person);
}
Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with
del persons
It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.
Since nobody has mentioned this..
If all you want is an array of values, an easier alternative would be to use the .map()
method. Just remember to call .get()
to convert the jQuery object to an array:
var names = $('.parent input:checked').map(function () {
return this.name;
}).get();
console.log(names);
var names = $('.parent input:checked').map(function () {_x000D_
return this.name;_x000D_
}).get();_x000D_
_x000D_
console.log(names);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
Pure JavaScript:
var elements = document.querySelectorAll('.parent input:checked');
var names = Array.prototype.map.call(elements, function(el, i) {
return el.name;
});
console.log(names);
var elements = document.querySelectorAll('.parent input:checked');_x000D_
var names = Array.prototype.map.call(elements, function(el, i){_x000D_
return el.name;_x000D_
});_x000D_
_x000D_
console.log(names);
_x000D_
<div class="parent">_x000D_
<input type="checkbox" name="name1" />_x000D_
<input type="checkbox" name="name2" />_x000D_
<input type="checkbox" name="name3" checked="checked" />_x000D_
<input type="checkbox" name="name4" checked="checked" />_x000D_
<input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
Use the "contents" function:
$('#some-id').contents().find('html').html("some-html")
Relevant fiddle: http://jsfiddle.net/fDFca/
Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules.
It includes lots of cool tools to work with http and has the advantage that you can use it with wsgi in different environments (cgi, fcgi, apache/mod_wsgi or with a plain simple python server for debugging).
I have added a distribution to the Python Package Index which makes the match_hostname()
function from the Python 3.2 ssl
package available on previous versions of Python.
http://pypi.python.org/pypi/backports.ssl_match_hostname/
You can install it with:
pip install backports.ssl_match_hostname
Or you can make it a dependency listed in your project's setup.py
. Either way, it can be used like this:
from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
...
Assuming you also want to strip whitespace at beginning and end of each line, you can map the string strip function to the list returned by readlines:
map(str.strip, open('filename').readlines())
You need to surround $file = readdir($handle)
with parentheses.
Here you go:
$log_directory = 'your_dir_name_here';
$results_array = array();
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
//Notice the parentheses I added:
while(($file = readdir($handle)) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
//Output findings
foreach($results_array as $value)
{
echo $value . '<br />';
}
If you know some unix you could try the following:
Notes: $ means the command prompt
Say you have a file my_data.txt with content as such:
$ cat my_data.txt
This is a data file
with all of my data in it.
Then using the os
module you can use the usual sed
commands
import os
# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"
# Execute the command
os.system(command)
If you aren't aware of sed, check it out, it is extremely useful.
I also faced problem like this and i set this.
@XmlRootElement(name="yourRootElementName")
@XmlAccessorType(XmlAccessType.FIELD)
This will work 100%
You can create a reusable Range pattern class :
public class Range<T> where T : IComparable
{
readonly T min;
readonly T max;
public Range(T min, T max)
{
this.min = min;
this.max = max;
}
public bool IsOverlapped(Range<T> other)
{
return Min.CompareTo(other.Max) < 0 && other.Min.CompareTo(Max) < 0;
}
public T Min { get { return min; } }
public T Max { get { return max; } }
}
You can add all methods you need to merge ranges, get intersections and so on...
Use a slice, not an arrray. Just create it using
reg := []string {"a","b","c"}
An alternative would have been to convert your array to a slice when joining :
fmt.Println(strings.Join(reg[:],","))
Read the Go blog about the differences between slices and arrays.
GitHub Pages now uses kramdown as its markdown engine so you can use the following syntax:
Here is an inline ![smiley](smiley.png){:height="36px" width="36px"}.
http://kramdown.gettalong.org/syntax.html#images
I haven't tested it on GitHub wiki though.
You could just have <hr style="border-top: dotted 1px;" />
. That should work.
Just a thought, but you may check the influence of a ulimit -v
option.
That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.
Yes, it can throw an exception and you can declare that in the signature of the constructor too as shown in the example below:
public class ConstructorTest
{
public ConstructorTest() throws InterruptedException
{
System.out.println("Preparing object....");
Thread.sleep(1000);
System.out.println("Object ready");
}
public static void main(String ... args)
{
try
{
ConstructorTest test = new ConstructorTest();
}
catch (InterruptedException e)
{
System.out.println("Got interrupted...");
}
}
}
>>>
will always put a 0 in the left most bit, while >>
will put a 1 or a 0 depending on what the sign of it is.
PLEASE NOTE: THE ANSWER BELOW IS HORRIBLY OUTDATED, AND MIGHT NOT BE ENTIRELY CORRECT ANYMORE.
You can program in C/C++ using the Android NDK. You'll have to wrap your c++ codebase in a static library and load that through a Java wrapper & JNI.
The standard NDK does not support RTTI and a lot of the functionality of standard c++ is also not available such as std::string, etc. To solve this you can recompile the NDK. Dmitry Moskalchuk supplies a modified version of the NDK that supports this at http://www.crystax.net/android/ndk-r3.php. This modified version works on all Android phones that run on an ARM processor.
Depending on the kind of application you should decide to use Java or C/C++. I'd use C/C++ for anything that requires above average computational power and games -- Java for the rest.
Just pick one language and write the majority of your application in that language; JNI calls can decrease your performance by a lot. Java isn't that hard though -- if you know how to program in C/C++. The advantage of Java is that the application can run on any device running Android, where as NDK applications depend on the architecture it was compiled for.
http://php.net/manual/en/function.strpos.php I think you are wondiner if 'some text' exists in the string right?
if(strpos( $a , 'some text' ) !== false)
For Sublime Text Editor
Indentation Error generally occurs when the code contains a mix of both tabs and spaces for indentation. I have got a very nice solution to correct it, just open your code in a sublime text editor and find 'Tab Size'
in the bottom right corner of Sublime Text Editor and click it. Now select either
'Convert Indentation to Spaces'
OR
'Convert Indentation to Tabs'
Your code will work in either case.
Additionally, if you want Sublime text to do it automatically for you for every code you can update the Preference settings as below:-
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
user6779899's answer is neat and more generic However, based on the request by Imad El Hitti, a light weight solution is proposed here. This can be used when a child component is tightly connected to one parent only.
Parent.component.ts
export class Notifier {
valueChanged: (data: number) => void = (d: number) => { };
}
export class Parent {
notifyObj = new Notifier();
tellChild(newValue: number) {
this.notifyObj.valueChanged(newValue); // inform child
}
}
Parent.component.html
<my-child-comp [notify]="notifyObj"></my-child-comp>
Child.component.ts
export class ChildComp implements OnInit{
@Input() notify = new Notifier(); // create object to satisfy typescript
ngOnInit(){
this.notify.valueChanged = (d: number) => {
console.log(`Parent has notified changes to ${d}`);
// do something with the new value
};
}
}
I also faced this issue and failed to figure out the reason for the same for sometimes. Later i found that auto import issue using IDE. That is imports of the program.
Basically i was using eclipse IDE. And I was importing a wrong class "org.junit.jupiter.api.Test"
into the program instead of required class "org.junit.Test".
Hence check your imports before running any programs.
According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:
For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.
- Parse the URL, and let fragid be the <fragment> component of the URL.
- If fragid is the empty string, then the indicated part of the document is the top of the document.
- If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
- If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
- Otherwise, there is no indicated part of the document.
So, it will look for id="foo"
, and then will follow to name="foo"
Edit: As pointed out by @hsivonen, in HTML5 the a
element has no name attribute. However, the above rules still apply to other named elements.
It's a time zone change on December 31st in Shanghai.
See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possible instant for that local date/time - hence the difference.
Just another episode in the often weird and wonderful world of time zones.
EDIT: Stop press! History changes...
The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of TZDB. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.
I only noticed this because I'm collecting questions like this in Noda Time, in the form of unit tests... The test has now been changed, but it just goes to show - not even historical data is safe.
EDIT: History has changed again...
In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between t
and t+1
is 344 seconds, if you see what I mean).
EDIT: To answer a question around a transition at 1900... it looks like the Java timezone implementation treats all time zones as simply being in their standard time for any instant before the start of 1900 UTC:
import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws Exception {
long startOf1900Utc = -2208988800000L;
for (String id : TimeZone.getAvailableIDs()) {
TimeZone zone = TimeZone.getTimeZone(id);
if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
System.out.println(id);
}
}
}
}
The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a "fixed" standard time (which is what getRawOffset
assumes to be a valid concept) so other libraries needn't introduce this artificial transition.
JAVA_OPTS
is environment variable used by tomcat in its startup/shutdown script to configure params.
You can set it in linux by
export JAVA_OPTS="-Djava.awt.headless=true"
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'
Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U)
print Result.groups()
Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.
I'm a beginner too and I faced that issue a couple of times myself.
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
$(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width>height && width>maxWidth)
{
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
}
else if(height>width && height>maxHeight)
{
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
}
});
});
Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.
In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.
During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.
So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.
The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.
In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.
Now I come to your other question about Naive Bayes.
To demonstrate the concept of Naïve Bayes Classification, consider the example given below:
As indicated, the objects can be classified as either GREEN
or RED
. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.
Since there are twice as many GREEN
objects as RED
, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership GREEN
rather than RED
. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of GREEN
and RED
objects, and often used to predict outcomes before they actually happen.
Thus, we can write:
Prior Probability of GREEN
: number of GREEN objects / total number of objects
Prior Probability of RED
: number of RED objects / total number of objects
Since there is a total of 60
objects, 40
of which are GREEN
and 20 RED
, our prior probabilities for class membership are:
Prior Probability for GREEN
: 40 / 60
Prior Probability for RED
: 20 / 60
Having formulated our prior probability, we are now ready to classify a new object (WHITE
circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more GREEN
(or RED
) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:
From the illustration above, it is clear that Likelihood of X
given GREEN
is smaller than Likelihood of X
given RED
, since the circle encompasses 1
GREEN
object and 3
RED
ones. Thus:
Although the prior probabilities indicate that X
may belong to GREEN
(given that there are twice as many GREEN
compared to RED
) the likelihood indicates otherwise; that the class membership of X
is RED
(given that there are more RED
objects in the vicinity of X
than GREEN
). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).
Finally, we classify X as RED
since its class membership achieves the largest posterior probability.
This is plain Javascript and has nothing to do with the jQuery library.
You simply escape the apostrophe with a backslash:
theAnchorText = 'I\'m home';
Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:
theAnchorText = "I'm home";
You can use tomcat plugin with gradle. For more information, you here.
apply plugin: 'tomcat'
dependencies {
classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:1.2.4'
}
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
[tomcatRun, tomcatRunWar, tomcatStop]*.stopPort = 8090
[tomcatRun, tomcatRunWar, tomcatStop]*.stopKey = 'stfu'
tomcatRunWar.contextPath = "/$rootProject.name"
tomcatRunWar.ajpPort = 8000
if (checkBeforeRun.toBoolean()) {
tomcatRunWar { dependsOn += ['check'] }
}
Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.
For chrome, no-cache is used to reload the page on a re-visit, but it still caches it if you go back in history (back button). To reload the page for history-back as well, use no-store. IE needs must-revalidate to work in all occasions.
So just to be sure to avoid all bugs and misinterpretations I always use
Cache-Control: no-store, no-cache, must-revalidate
if I want to make sure it reloads.
It is pretty simple, leave the images on the server and send the PHP + CSS to them...
$to = '[email protected]';
$subject = 'Website Change Reqest';
$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: [email protected]\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
$message = '<p><strong>This is strong text</strong> while this is not.</p>';
mail($to, $subject, $message, $headers);
It is this line that tells the mailer and the recipient that the email contains (hopefully) well formed HTML that it will need to interpret:
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
Here is the link I got the info.. (link...)
You will need security though...
HTTP_HOST
is the target host sent by the client. It can be manipulated freely by the user. It's no problem to send a request to your site asking for a HTTP_HOST
value of www.stackoverflow.com
.
SERVER_NAME
comes from the server's VirtualHost
definition and is therefore considered more reliable. It can, however, also be manipulated from outside under certain conditions related to how your web server is set up: See this This SO question that deals with the security aspects of both variations.
You shouldn't rely on either to be safe. That said, what to use really depends on what you want to do. If you want to determine which domain your script is running on, you can safely use HTTP_HOST
as long as invalid values coming from a malicious user can't break anything.
You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.
The following would work.
<td colspan="2" class="cell">
<asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>
</td>
In your CSS file:
.cell
{
text-align:left;
}
.righttextbox
{
float:right;
}
A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]
plt.close('all')
# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)
# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)
plt.show()
Even if the following proposal should not be considered as a final solution you can achieve the goal by doing something like this:
SET SESSION group_concat_max_len = 1000000;
SET @search = 'Text_To_Search';
DROP table IF EXISTS table1;
CREATE TEMPORARY TABLE table1 AS
(SELECT
CONCAT('SELECT \'',TABLE_NAME,'\' as \'table_name\',\'',COLUMN_NAME,'\' as \'column_name\',CONVERT(count(*),char) as \'matches\' FROM `',
TABLE_NAME,'` where `',COLUMN_NAME,'` like \'%',@search,'%\' UNION ') as 'query'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db_name' limit 1000000);
set @query = (SELECT GROUP_CONCAT(t1.`query` SEPARATOR '') as 'final_query' from table1 t1 limit 1);
set @query = (SELECT SUBSTRING(@query, 1, length(@query) - 7));
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Please remember that:
Options: group_concat_max_len and limit 1000000 not always are needed, it will depends of your server/IDE configuration. Just in case I added them.
After executing this you will get a 3 column response: [table_name], [column_name], [matches]
Column 'matches' is the number of occurrences in the given table/column.
This query is very fast.
DISCLAIMER: It would be useful only for personal use, in other words please don't use it in a production system, because it is sensitive to SQL Injection attacks given that the search parameter is concatenated with other strings. If you want to create a prod. ready function, then you will need to create a store procedure with a LOOP.
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
There is another route of failure, besides the version of Java you are running: You could be running out of Heap/RAM
If you had a once working version of SQLDeveloper, and you are starting to see the screenshot referenced in the original post, then you can try to adjust the amount of space SQLDeveloper requests when starting up.
Edit the file:
/ide/bin/ide.conf
Edit the line that specifies the max ram to use: AddVMOption -Xmx, reducing the size. For example I changed my file to have the following lines, which solved the issue.
#AddVMOption -Xmx640M # Original Value
AddVMOption -Xmx256M # New Value
moment.js has some really nice convenience methods to manipulate date objects
The .subtract method, allows you to subtract a certain amount of time units from a date, by providing the amount and a timeunit string.
var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...
There are several ways. I personally use the following ones:
extracting single value:
String user_Id =
given().
when().
then().
extract().
path("user_id");
work with the entire response when you need more than one:
Response response =
given().
when().
then().
extract().
response();
String userId = response.path("user_id");
extract one using the JsonPath to get the right type:
long userId =
given().
when().
then().
extract().
jsonPath().getLong("user_id");
Last one is really useful when you want to match against the value and the type i.e.
assertThat(
when().
then().
extract().
jsonPath().getLong("user_id"), equalTo(USER_ID)
);
The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage
Summarising few basic Advantages & Disadvantages of using Static methods in Java:
Advantages:
Disadvantages:
In CMake you could use find_package
to find libraries you need. There usually is a FindBoost.cmake
along with your CMake installation.
As far as I remember, it will be installed to /usr/share/cmake/Modules/
along with other find-scripts for common libraries. You could just check the documentation in that file for more information about how it works.
An example out of my head:
FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
ADD_EXECUTABLE( anyExecutable myMain.cpp )
TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} )
I hope this code helps.
2020 TypeScript Answer:
Why:
https://0.30000000000000004.com
Library:
// TypeScript Type: Math Type
type MathType = 'Add' | 'Subtract' | 'Multiply' | 'Divide';
// Math Exact
export const mathExact = (mathType: MathType, numberOne:number , numberTwo: number) => {
// Decimal Places
let numberOneDecimalPlaces: number = 0;
let numberTwoDecimalPlaces: number = 0;
// Float: Number One
if (numberOne.toString().indexOf('.') !== -1) {
// Assign Decimal Places
numberOneDecimalPlaces = numberOne.toString().length - 1 - numberOne.toString().indexOf('.');
}
// Float: Number Two
if (numberTwo.toString().indexOf('.') !== -1) {
// Assign Decimal Places
numberTwoDecimalPlaces = numberTwo.toString().length - 1 - numberTwo.toString().indexOf('.');
}
// Decimal Places: Equal
if (numberOneDecimalPlaces === numberTwoDecimalPlaces) {
// Integers (Off By Decimal Places)
const numberOneInteger: number = numberOne * Math.pow(10, numberOneDecimalPlaces);
const numberTwoInteger: number = numberTwo * Math.pow(10, numberTwoDecimalPlaces);
// Math Type: Add
if (mathType === 'Add') {
// Integer Total
const integerTotal: number = numberOneInteger + numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces);
}
// Math Type: Subtract
else if (mathType === 'Subtract') {
// Integer Total
const integerTotal: number = numberOneInteger - numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces);
}
// Math Type: Multiply
else if (mathType === 'Multiply') {
// Integer Total
const integerTotal: number = numberOneInteger * numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces);
}
// Math Type: Divide
else if (mathType === 'Divide') {
return numberOneInteger / numberTwoInteger;
}
}
// Decimal Places: Number One Has More
else if (numberOneDecimalPlaces > numberTwoDecimalPlaces) {
// Integers (Off By Decimal Places)
const numberOneInteger: number = numberOne * Math.pow(10, numberOneDecimalPlaces);
const numberTwoInteger: number = numberTwo * Math.pow(10, numberOneDecimalPlaces);
// Math Type: Add
if (mathType === 'Add') {
// Integer Total
const integerTotal: number = numberOneInteger + numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces);
}
// Math Type: Subtract
else if (mathType === 'Subtract') {
// Integer Total
const integerTotal: number = numberOneInteger - numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces);
}
// Math Type: Multiply
else if (mathType === 'Multiply') {
// Integer Total
const integerTotal: number = numberOneInteger * numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces + (numberOneDecimalPlaces - numberTwoDecimalPlaces));
}
// Math Type: Divide
else if (mathType === 'Divide') {
return numberOneInteger / numberTwoInteger;
}
}
// Decimal Places: Number Two Has More
else if (numberOneDecimalPlaces < numberTwoDecimalPlaces) {
// Integers (Off By Decimal Places)
const numberOneInteger: number = numberOne * Math.pow(10, numberTwoDecimalPlaces);
const numberTwoInteger: number = numberTwo * Math.pow(10, numberTwoDecimalPlaces);
// Math Type: Add
if (mathType === 'Add') {
// Integer Total
const integerTotal: number = numberOneInteger + numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberTwoDecimalPlaces);
}
// Math Type: Subtract
else if (mathType === 'Subtract') {
// Integer Total
const integerTotal: number = numberOneInteger - numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberTwoDecimalPlaces);
}
// Math Type: Multiply
else if (mathType === 'Multiply') {
// Integer Total
const integerTotal: number = numberOneInteger * numberTwoInteger;
// Decimal Total (Convert Back X Amount Of Decimal Places)
return integerTotal / Math.pow(10, numberOneDecimalPlaces + numberTwoDecimalPlaces + (numberTwoDecimalPlaces - numberOneDecimalPlaces));
}
// Math Type: Divide
else if (mathType === 'Divide') {
return numberOneInteger / numberTwoInteger;
}
}
};
Add:
mathExact('Add', 1, 2); // 3
mathExact('Add', .1, .2); // .3
mathExact('Add', 1.123, .2); // 1.323
mathExact('Add', .02, 1.123); // 1.143
Subtract:
mathExact('Subtract', 1, 2): // -1
mathExact('Subtract', .1, .2); // -.1
mathExact('Subtract', 1.123, .2); // .923
mathExact('Subtract', .02, 1.123); // -1.103
Multiply:
mathExact('Multiply', 1, 2); // 2
mathExact('Multiply', .1, .2); // .02
mathExact('Multiply', 1.123, .2); // .2246
mathExact('Multiply', .02, 1.123); // .002246
Divide:
mathExact('Divide', 1, 2); // .5
mathExact('Divide', .1, .2); // .5
mathExact('Divide', 1.123, .2); // 5.615
mathExact('Divide', .02, 1.123); // .017809439002671415
I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).
Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example
>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
a b
0 1 4.0
1 2 NaN
2 3 6.0
3 5 4.0
>>> df.groupby(['b']).sum()
a
b
4.0 6
6.0 3
>>> df.astype(str).groupby(['b']).sum()
a
b
4.0 15
6.0 3
nan 2
which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.
Try adding a -
before the []
or [x]
. That's an -
followed by a blank space .
Below is an example from Github blog.
### Solar System Exploration, 1950s – 1960s
- [ ] Mercury
- [x] Venus
- [x] Earth (Orbit/Moon)
- [x] Mars
- [ ] Jupiter
- [ ] Saturn
- [ ] Uranus
- [ ] Neptune
- [ ] Comet Haley
It appears like below:
Here's how one could do the same in a table:
| Task | Time required | Assigned to | Current Status | Finished |
|----------------|---------------|---------------|----------------|-----------|
| Calendar Cache | > 5 hours | | in progress | - [x] ok?
| Object Cache | > 5 hours | | in progress | [x] item1<br/>[ ] item2
| Object Cache | > 5 hours | | in progress | <ul><li>- [x] item1</li><li>- [ ] item2</li></ul>
| Object Cache | > 5 hours | | in progress | <ul><li>[x] item1</li><li>[ ] item2</li></ul>
- [x] works
- [x] works too
Here's how it looks:
Adding another option, if jq is available:
export NAMES="{
\"Mary\":\"100\",
\"John\":\"200\",
\"Mary\":\"50\",
\"John\":\"300\",
\"Paul\":\"100\",
\"Paul\":\"400\",
\"David\":\"100\"
}"
export NAME=David
echo $NAMES | jq --arg v "$NAME" '.[$v]' | tr -d '"'
It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:
class Program
{
protected static Dictionary<string, string> _tags = new Dictionary<string,string>();
static void Main(string[] args)
{
string strValue;
_tags.Add("101", "C#");
_tags.Add("102", "ASP.NET");
if (_tags.ContainsKey("101"))
{
strValue = _tags["101"];
Console.WriteLine(strValue);
}
if (_tags.TryGetValue("101", out strValue))
{
Console.WriteLine(strValue);
}
}
}
For Django 2.2 up to 3, you have to load staticfiles in html template first before use static keyword
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
For other versions use static
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
Also you have to check that you defined STATIC_URL in setting.py
At last, make sure the static files exist in the defined folder
grep -F -r '0.49' *
treats 0.49 as a "fixed" string instead of a regular expression. This makes .
lose its special meaning.
The new
operator is allocating space for a block of n
integers and assigning the memory address of that block to the int*
variable array
.
The general form of new as it applies to one-dimensional arrays appears as follows:
array_var = new Type[desired_size];
The compileSdkVersion
is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion
to 15, you will get a compilation error. If you set compileSdkVersion
to 16 you can still run the app on a API 15 device as long as your app's execution paths do not attempt to invoke any APIs specific to API 16.
The targetSdkVersion
has nothing to do with how your app is compiled or what APIs you can utilize. The targetSdkVersion
is supposed to indicate that you have tested your app on (presumably up to and including) the version you specify. This is more like a certification or sign off you are giving the Android OS as a hint to how it should handle your app in terms of OS features.
For example, as the documentation states:
For example, setting this value to "11" or higher allows the system to apply a new default theme (Holo) to your app when running on Android 3.0 or higher...
The Android OS, at runtime, may change how your app is stylized or otherwise executed in the context of the OS based on this value. There are a few other known examples that are influenced by this value and that list is likely to only increase over time.
For all practical purposes, most apps are going to want to set targetSdkVersion
to the latest released version of the API. This will ensure your app looks as good as possible on the most recent Android devices. If you do not specify the targetSdkVersion
, it defaults to the minSdkVersion
.
In the ViewDidLoad method of your class set up to listen for messages about the keyboard:
// Listen for keyboard appearances and disappearances
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
Then in the methods you specify (in this case keyboardDidShow
and keyboardDidHide
) you can do something about it:
- (void)keyboardDidShow: (NSNotification *) notif{
// Do something here
}
- (void)keyboardDidHide: (NSNotification *) notif{
// Do something here
}
Just run these two commands and you should be good to go.
git checkout <branch-name>
git pull origin <branch-name>
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
As we don't know what are the names of your activities classes, let's call your current activity Activity1, and the one you wish to open - Activity2 (these are the names of the classes)
First you need to define an intent that will be sent to Activity2:
Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);
Then, you can simply launch the activity by running:
startActivity(launchActivity2 );
Using Array.prototype.map()
const zip = (a, b) => a.map((k, i) => [k, b[i]]);
console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
Using Array.from()
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);
console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
Using Array.prototype.fill() and Array.prototype.map()
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);
console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
I had the same problem. The bar had the same background color. Try:
android:scrollbarThumbVertical="@android:color/black"
I added the spring folder to the build path and, after clean&build, it worked.
Finally I fixed the problem by modifying build.gradle
like this:
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
}
I've removed these lines as these will produce more errors:
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
Also I had same problem with migrating an existing project from 2.3 to 3.0.1 and with modifying the project gradle files like this, I came up with a working solution:
build.gradle (module app)
android {
compileSdkVersion 27
buildToolsVersion "27.0.1"
defaultConfig {
applicationId "com.mobaleghan.tablighcalendar"
minSdkVersion 16
targetSdkVersion 27
}
dependencies {
implementation 'com.android.support:appcompat-v7:25.1.0'
implementation 'com.android.support:design:25.1.0'
implementation 'com.android.support:preference-v7:25.1.0'
implementation 'com.android.support:recyclerview-v7:25.1.0'
implementation 'com.android.support:support-annotations:25.1.0'
implementation 'com.android.support:support-v4:25.1.0'
implementation 'com.android.support:cardview-v7:25.1.0'
implementation 'com.google.android.apps.dashclock:dashclock-api:2.0.0'
}
Top level build.gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
You can bind function as follows, instead of init on load
$("div").css("height", $(window).height());
$(?window?).bind("resize",function() {
$("div").css("height", $(window).height());
});????
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
Just another way of doing it.
[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]
Try this sed
version:
ls -l | sed '2 ! d'
It says "delete all the lines that aren't the second one".
Actually I think that more general approach to loop through dictionary is to use iteritems():
# get tuples of term, courses
for term, term_courses in courses.iteritems():
# get tuples of course number, info
for course, info in term_courses.iteritems():
# loop through info
for k, v in info.iteritems():
print k, v
output:
assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian
Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():
for term_courses in courses.itervalues():
for info in term_courses.itervalues():
for k, v in info.iteritems():
print k, v
First install "Microsoft ASP.NET Web API Client" nuget package:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Then use the following function to post your data:
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
And this is how to use it:
TokenResponse tokenResponse =
await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);
or
TokenResponse tokenResponse =
(Task.Run(async ()
=> await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
.Result
or (not recommended)
TokenResponse tokenResponse =
PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;
In addition to File.ReadAllText
, File.ReadAllLines
, and File.WriteAllText
(and similar helpers from File
class) shown in another answer you can use StreamWriter
/StreamReader
classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
readtext.Dispose()
instead of using
, but it will not close file/reader/writer in case of exceptionsusing
/Close
is very common reason of "why data is not written to file".Below code works: but not very efficient way. :(
static void Main(String[] args) {
int n = Convert.ToInt32(Console.ReadLine());
int[] medList = new int[n];
for (int x = 0; x < n; x++)
medList[x] = int.Parse(Console.ReadLine());
//sort the input array:
//Array.Sort(medList);
for (int x = 0; x < n; x++)
{
double[] newArr = new double[x + 1];
for (int y = 0; y <= x; y++)
newArr[y] = medList[y];
Array.Sort(newArr);
int curInd = x + 1;
if (curInd % 2 == 0) //even
{
int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
if (mid > 1) mid--;
double median = (newArr[mid] + newArr[mid+1]) / 2;
Console.WriteLine("{0:F1}", median);
}
else //odd
{
int mid = (x / 2) <= 0 ? 0 : (newArr.Length / 2);
double median = newArr[mid];
Console.WriteLine("{0:F1}", median);
}
}
}
Try this:
myrecyclerview.setLayoutManager(
new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL,false));
myrecyclerview.setAdapter(recyclerAdapter);
only in case you got a recycler view with some fragments on it.
Just wrap window.close by onafterprint event handler, it worked for me
printWindow.print();
printWindow.onafterprint = () => printWindow.close();
All the hidden fields in your fieldset are using the same id, so jquery is only returning the first one. One way to fix this is to create a counter variable and concatenate it to each hidden field id.
In order to approach to Modular design pattern, you need to understand these concept first:
Immediately-Invoked Function Expression (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
Here are using function expression.
What is namespace? Now if we add the namespace to the above piece of code then
var anoyn = (function() {
}());
What is closure in JS?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
The objective is to hide the variable accessibility from the outside world.
Hope this helps. Good Luck.
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
It won't throw exception, you'll get an empty list.
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
df
command : Report file system disk space usagedu
command : Estimate file space usageType df -h
or df -k
to list free disk space:
$ df -h
OR
$ df -k
du
shows how much space one or more files or directories is using:
$ du -sh
The -s
option summarizes the space a directory is using and -h
option provides Human-readable output.
.center { width:500px; margin-right:auto; margin-left:auto; }
I have a small plugin that handles this.
It's called waitForImages and it can handle img
elements or any element with a reference to an image in the CSS, e.g. div { background: url(img.png) }
.
If you simply wanted to load all images, including ones referenced in the CSS, here is how you would do it :)
$('body').waitForImages({
waitForAll: true,
finished: function() {
// All images have loaded.
}
});
If you want to know the specific version then you need to check composer.lock file and search For
"name": "laravel/framework",
you will find your version in next line
"version": "v5.7.9",
Why perform the summation forwards when you can do it backwards? Given:
std::vector<int> v; // vector to be summed
int sum_of_elements(0); // result of the summation
We can use subscripting, counting backwards:
for (int i(v.size()); i > 0; --i)
sum_of_elements += v[i-1];
We can use range-checked "subscripting," counting backwards (just in case):
for (int i(v.size()); i > 0; --i)
sum_of_elements += v.at(i-1);
We can use reverse iterators in a for loop:
for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
sum_of_elements += *i;
We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):
for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
sum_of_elements += *(i - 1);
We can use accumulate
with reverse iterators:
sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);
We can use for_each
with a lambda expression using reverse iterators:
std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });
So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.
Although you could certainly use the compareTo
method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.
Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:
if (count > 0) { }
And the Integer
instance count
gets automatically converted to an int
for the comparison.
If you're having trouble understanding this, check out the link above, or imagine it's doing this:
if (count.intValue() > 0) { }
For JBoss, in standalone.xml, put after .
<extensions>
</extensions>
<system-properties>
<property name="my.project.dir" value="/home/francesco" />
</system-properties>
For eclipse:
http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2
Use out to denote that the parameter is not being used, only set. This helps the caller understand that you're always initializing the parameter.
Also, ref and out are not just for value types. They also let you reset the object that a reference type is referencing from within a method.
(Expanding upon ????'s answer)
Style the canvas to fill the body. When rendering to the canvas take its size into account.
http://jsfiddle.net/mqFdk/356/
<!DOCTYPE html>
<html>
<head>
<title>aj</title>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
CSS:
body {
margin: 0;
padding: 0
}
#c {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden
}
Javascript:
function redraw() {
var cc = c.getContext("2d");
c.width = c.clientWidth;
c.height = c.clientHeight;
cc.scale(c.width, c.height);
// Draw a circle filling the canvas.
cc.beginPath();
cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
cc.fill();
}
// update on any window size change.
window.addEventListener("resize", redraw);
// first draw
redraw();
For me it was caused by having different versions of .Net Core installed. I matched my dev and production server and it worked.
You can also use CURRENT_TIMESTAMP
for this.
According to BOL CURRENT_TIMESTAMP
is the ANSI SQL
euivalent to GETDATE()
DECLARE @LastChangeDate AS DATE;
SET @LastChangeDate = CURRENT_TIMESTAMP;
You can just do:
df[sorted(df.columns)]
Edit: Shorter is
df[sorted(df)]
import cv2
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import img_as_ubyte
from skimage import io
filename='abc.png'
image=plt.imread(filename)
im=cv2.imread('abc.png')
print(im.shape)
im.resize(300,300)
print(im.shape)
plt.imshow(image)
The functions in stdlib.h
and stdio.h
have implementations in libc.so
(or libc.a
for static linking), which is linked into your executable by default (as if -lc
were specified). GCC can be instructed to avoid this automatic link with the -nostdlib
or -nodefaultlibs
options.
The math functions in math.h
have implementations in libm.so
(or libm.a
for static linking), and libm
is not linked in by default. There are historical reasons for this libm
/libc
split, none of them very convincing.
Interestingly, the C++ runtime libstdc++
requires libm
, so if you compile a C++ program with GCC (g++
), you will automatically get libm
linked in.
Per the TypeScript 2.3 release notes on "New --downlevelIteration
":
for..of statements
, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using--downlevelIteration
This is not enabled by default! Add "downlevelIteration": true
to your tsconfig.json
, or pass --downlevelIteration
flag to tsc
, to get full iterator support.
With this in place, you can write for (let keyval of myMap) {...}
and keyval
's type will be automatically inferred.
Why is this turned off by default? According to TypeScript contributor @aluanhaddad,
It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).
If you can target ES2015 ("target": "es2015"
in tsconfig.json
or tsc --target ES2015
) or later, enabling downlevelIteration
is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from
conversion or forEach
or some other workaround).
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
You want the background color of your main view to be semi-transparent? There's nothing behind it... so nothing will really happen however:
If you want to modify the alpha of any view, use the alpha property:
UIView *someView = [[UIView alloc] init];
...
someView.alpha = 0.8f; //Sets the opacity to 80%
...
Views themselves have the alpha transparency, not just UIColor.
But since your problem is that you can't read text on top of the images... either:
UIView *overlay = [[[UIView alloc] init] autorelease]; overlay.frame = self.view.bounds; overlay.alpha = 0.2f; [self.view addSubview:overlay]; ... Add the rest of the views
try
var lst= (from char c in source select c.ToString()).ToList();
You can use the modulus operator, but that can be slow. A more efficient way would be to check the lowest bit because that determines whether a number is even or odd. The code would look something like this:
public static void main(String[] args) {
System.out.println("Enter a number to check if it is even or odd");
System.out.println("Your number is " + (((new Scanner(System.in).nextInt() & 1) == 0) ? "even" : "odd"));
}
string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();
This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.
Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.
(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).
To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)
My solution...
//Fix modal mobile Boostrap 3
function Show(id){
//Fix CSS
$(".modal-footer").css({"padding":"19px 20px 20px","margin-top":"15px","text-align":"right","border-top":"1px solid #e5e5e5"});
$(".modal-body").css("overflow-y","auto");
//Fix .modal-body height
$('#'+id).on('shown.bs.modal',function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
//Aply changes on screen resize (example: mobile orientation)
window.onresize=function(){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").css("height","auto");
h1=$("#"+id+">.modal-dialog").height();
h2=$(window).height();
h3=$("#"+id+">.modal-dialog>.modal-content>.modal-body").height();
h4=h2-(h1-h3);
if($(window).width()>=768){
if(h1>h2){
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
}
$("#"+id+">.modal-dialog").css("margin","30px auto");
$("#"+id+">.modal-dialog>.modal-content").css("border","1px solid rgba(0,0,0,0.2)");
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",6);
if($("#"+id+">.modal-dialog").height()+30>h2){
$("#"+id+">.modal-dialog").css("margin-top","0px");
$("#"+id+">.modal-dialog").css("margin-bottom","0px");
}
}
else{
//Fix full-screen in mobiles
$("#"+id+">.modal-dialog>.modal-content>.modal-body").height(h4);
$("#"+id+">.modal-dialog").css("margin",0);
$("#"+id+">.modal-dialog>.modal-content").css("border",0);
$("#"+id+">.modal-dialog>.modal-content").css("border-radius",0);
}
};
});
//Free event listener
$('#'+id).on('hide.bs.modal',function(){
window.onresize=function(){};
});
//Mobile haven't scrollbar, so this is touch event scrollbar implementation
var y1=0;
var y2=0;
var div=$("#"+id+">.modal-dialog>.modal-content>.modal-body")[0];
div.addEventListener("touchstart",function(event){
y1=event.touches[0].clientY;
});
div.addEventListener("touchmove",function(event){
event.preventDefault();
y2=event.touches[0].clientY;
var limite=div.scrollHeight-div.clientHeight;
var diff=div.scrollTop+y1-y2;
if(diff<0)diff=0;
if(diff>limite)diff=limite;
div.scrollTop=diff;
y1=y2;
});
//Fix position modal, scroll to top.
$('html, body').scrollTop(0);
//Show
$("#"+id).modal('show');
}
I think the most simple & straightforward way is
for f in *.*; do echo "${f##*.}"; done | sort -u
It's modified on ChristopheD's 3rd way.
Yes there is, you can simply put <hr>
in your code where you want it, I already use it in one of my admin panel side bar.
To center align text
input[type='text'] { text-align:center;}
To center align the textbox in the container that it sits in, apply text-align:center to the container.
For those coming from Google (etc.) such as myself:
convert_objects
has been deprecated since 0.17 - if you use it, you get a warning like this one:
FutureWarning: convert_objects is deprecated. Use the data-type specific converters
pd.to_datetime, pd.to_timedelta and pd.to_numeric.
You should do something like the following:
df =
df.astype(np.float)
df["A"] =
pd.to_numeric(df["A"])
You can also rename remote tags without checking them out, by duplicate the old tag/branch to a new name and delete the old one, in a single git push
command.
Remote tag rename / Remote branch ? tag conversion: (Notice: :refs/tags/
)
git push <remote_name> <old_branch_or_tag>:refs/tags/<new_tag> :<old_branch_or_tag>
Remote branch rename / Remote tag ? branch conversion: (Notice: :refs/heads/
)
git push <remote_name> <old_branch_or_tag>:refs/heads/<new_branch> :<old_branch_or_tag>
Output renaming a remote tag:
D:\git.repo>git push gitlab App%2012.1%20v12.1.0.23:refs/tags/App_12.1_v12.1.0.23 :App%2012.1%20v12.1.0.23
Total 0 (delta 0), reused 0 (delta 0)
To https://gitlab.server/project/repository.git
- [deleted] App%2012.1%20v12.1.0.23
* [new tag] App%2012.1%20v12.1.0.23 -> App_12.1_v12.1.0.23
I think that your JAVA_HOME should point to
C:\Program Files\Java\jdk1.6.0_25
instead of
C:\Program Files\Java\jdk1.6.0_25\bin
That is, without the bin folder.
UPDATE
That new error appears to me if I set the JAVA_HOME with the quotes, like you did. Are you using quotation marks? If so, remove them.
The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.
Try this
<input type="text" style="font-size:18pt;height:420px;width:200px;">
Or else
<input type="text" id="txtbox">
with the css:
#txtbox
{
font-size:18pt;
height:420px;
width:200px;
}
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName
could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook
could be the correct choice, if it is guaranteed to be active at execution time.)
As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:
I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/
Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/
See the examples below:
Multithreading a For Loop
Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
For i = seqFrom To seqTo
x = seqFrom / seqTo
Next i
End Sub
Sub RunForVBAMultiThread()
Dim parallelClass As Parallel
Set parallelClass = New Parallel
parallelClass.SetThreads 4
Call parallelClass.ParallelFor("RunForVBA", 1, 1000)
End Sub
Run an Excel macro asynchronously
Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
For i = seqFrom To seqTo
x = seqFrom / seqTo
Next i
End Sub
Sub RunForVBAAndWait()
Dim parallelClass As Parallel
Set parallelClass = New Parallel
Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000)
'Do other operations here
'....
parallelClass.AsyncThreadJoin
End Sub
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.
To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:
if(yyy == null || !yyy.Any()) return otherValue;
The MultiByteToWideChar
answer that Charles Bailey gave is the correct one. Because LPCWSTR
is just a typedef for const WCHAR*
, widestr
in the example code there can be used wherever a LPWSTR
is expected or where a LPCWSTR
is expected.
One minor tweak would be to use std::vector<WCHAR>
instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring
instead of std::string
. If you want to work with the Windows TCHAR
type, you can use std::basic_string<TCHAR>
. Converting from std::wstring
to LPCWSTR
or from std::basic_string<TCHAR>
to LPCTSTR
is just a matter of calling c_str
. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar
(and its inverse WideCharToMultiByte
) comes into the picture.
There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback
property of a UIWebView). By default on iPhone this is set to NO
, but on iPad it's set to YES
.
Fortunately for you, you can also adjust this behaviour in HTML as follows:
<video id="myVideo" width="280" height="140" webkit-playsinline>
...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.
You need to remove the /
before the [
. Predicates (the parts in [
]
) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text()
at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.
//Employee[@id='4']
Edit: As Jens points out in the comments, //
can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a full path, for example:
/Employees/Employee[@id='4']
Essentially two things you need to do are use a custom TrustStrategy that trusts all certs, and also use NoopHostnameVerifier() to disable hostname verification. Here is the code, with all the relevant imports:
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
public RestTemplate getRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
In addition to what eugene and stevenl posted, you might encounter problems with using both <>
and <STDIN>
in one script: <>
iterates through (=concatenating) all files given as command line arguments.
However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input
Short answers:
Q1: Yes.
Q2: Doesn't matter which you use.
Long answer:
A select ... for update
will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.
Another way of looking at it, it is as if the following two statements are executed atomically:
select * from my_table where my_condition;
update my_table set my_column = my_column where my_condition;
Since the rows affected by my_condition
are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.
Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.
What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.
You do cls.isFilled = True
. That overwrites the method called isFilled
and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.
The solution is use a different name for the variable than you do for the method.
If Foo is the class enclose this method
class Foo{
public ArrayList<Integer> myNumbers() {
//code code code
}
}
then
new Foo().myNumbers();
Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.
Note: $web container was created automatically while enable static website. Never seen $root container anywhere.
//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01
//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01
Press shift while selecting with the mouse. This will make mouse selection behave as if mouse=a
was not enabled.
Note: this trick also applies to "middle button paste": if you want to paste in vim text that was selected outside, press shift while clicking the middle button. Just make sure that insert mode is activated when you do that (you may also want to :set paste
to avoid unexpected effects).
OS X (mac): hold alt/option while selecting (source)
This is a US phone formatter that works on more versions of numbers than any of the current answers.
$numbers = explode("\n", '(111) 222-3333
((111) 222-3333
1112223333
111 222-3333
111-222-3333
(111)2223333
+11234567890
1-8002353551
123-456-7890 -Hello!
+1 - 1234567890
');
foreach($numbers as $number)
{
print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
}
And here is a breakdown of the regex:
Cell: +1 999-(555 0001)
.* zero or more of anything "Cell: +1 "
(\d{3}) three digits "999"
[^\d]{0,7} zero or up to 7 of something not a digit "-("
(\d{3}) three digits "555"
[^\d]{0,7} zero or up to 7 of something not a digit " "
(\d{4}) four digits "0001"
.* zero or more of anything ")"
Updated: March 11, 2015 to use {0,7}
instead of {,7}
The answer by retracile should be the closest one, yet it does not work for my case. One insert query just broke in the middle and the export just stopped. Not sure what is the reason. However It works fine during .dump
.
Finally I wrote a tool for the split up the SQL generated from .dump
:
The instance that your base class reference is referring to is not an instance of your child class. There's nothing wrong.
More specifically:
Base derivedInstance = new Derived();
Base baseInstance = new Base();
Derived good = (Derived)derivedInstance; // OK
Derived fail = (Derived)baseInstance; // Throws InvalidCastException
For the cast to be successful, the instance that you're downcasting must be an instance of the class that you're downcasting to (or at least, the class you're downcasting to must be within the instance's class hierarchy), otherwise the cast will fail.
gcc -dumpversion
-dumpversion
Print the compiler version (for example,3.0
) — and don't do anything else.
The same works for following compilers/aliases:
cc -dumpversion
g++ -dumpversion
clang -dumpversion
tcc -dumpversion
Be careful with automate parsing the GCC output:
--version
might be localized (e.g. to Russian, Chinese, etc.)--version
output will contain something like Android (5220042 based on r346389c) clang version 8.0.7
(it's real version string)Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
I am posting a new answer, as I do not have enough reputation to comment on the one provided by Antonio (see: https://stackoverflow.com/a/1957777).
In case you want the SOAP message to be printed in a file (e.g. via Log4j), you may use:
OutputStream os = new ByteArrayOutputStream();
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
soapMsg.writeTo(os);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(os.toString());
Please note that under certain circumstances, the method call writeTo() may not behave as expected (see: https://community.oracle.com/thread/1123104?tstart=0 or https://www.java.net/node/691073), therefore the following code will do the trick:
javax.xml.soap.SOAPMessage soapMsg = context.getMessage();
com.sun.xml.ws.api.message.Message msg = new com.sun.xml.ws.message.saaj.SAAJMessage(soapMsg);
com.sun.xml.ws.api.message.Packet packet = new com.sun.xml.ws.api.message.Packet(msg);
Logger LOG = Logger.getLogger(SOAPLoggingHandler.class); // Assuming SOAPLoggingHandler is the class name
LOG.info(packet.toString());
This will produce an array of names
> jq '[ .users[] | (.first + " " + .last) ]' ~/test.json
[
"Stevie Wonder",
"Michael Jackson"
]
This does work for me. In below example, Alpha range can be a value between 0 to 255. Previously, I made a mistake by thinking that it must be a value of percentage.
Dim x as integer = 230
Panel1.BackColor = Color.FromArgb(x, Color.Blue)
You can make use of ArrayList. Array has the fixed number of size.
This Example here can help you. The example is pretty easy with its output.
Output: 2 5 1 23 14
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29
Here is my one liner. Here 'c' is the name of the column
df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()
I had the same issue.
Make sure that In SQL Server configuration --> SQL Server Services --> SQL Server Agent is enable
This solved my problem
final: final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.
finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.