if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
Try this
const foo = numberOfItems=> [...Array(numberOfItems).keys()].map(i => i+1);
Status 422 (RFC 4918, Section 11.2) comes to mind:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Here are two quickie approaches I know of:
In base
AQ1 <- airquality
AQ1[is.na(AQ1 <- airquality)] <- 0
AQ1
Not in base
library(qdap)
NAer(airquality)
PS P.S. Does my command above create a new dataframe called AQ1?
Look at AQ1 and see
You can use stristr()
or strpos()
. Both return false if nothing is found.
You can do union
or simple list comprehension
[A.add(_) for _ in B]
A would have all the elements of B
For giving placeholder a color just use these lines of code:
::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; }
:-o-input-placeholder { color: red; }
The general end of line comment, // eslint-disable-line
, does not need anything after it: no need to look up a code to specify what you wish ES Lint to ignore.
If you need to have any syntax ignored for any reason other than a quick debugging, you have problems: why not update your delint config?
I enjoy // eslint-disable-line
to allow me to insert console
for a quick inspection of a service, without my development environment holding me back because of the breach of protocol. (I generally ban console
, and use a logging class - which sometimes builds upon console
.)
let mergeArray = arrA.filter(aItem => !arrB.find(bItem => aItem.name === bItem.name))
@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:
x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)
Any extension page (except content scripts) has direct access to the background page via chrome.extension.getBackgroundPage()
.
That means, within the popup page, you can just do:
chrome.extension.getBackgroundPage().console.log('foo');
To make it easier to use:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
Now if you want to do the same within content scripts you have to use Message Passing to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the Message Passing page for you to check out.
Hope that clears everything.
In their latest release there's a directive called md-icon
<md-icon icon="img/icons/ic_refresh_24px.svg"></md-icon>
If you have trouble to get e.g. from 3.3.x to 4.x (conda update conda "does not work" to get to the next version) than try it more specific like so:
conda install conda=4.0 (or conda install anaconda=4.0)
https://www.anaconda.com/blog/developer-blog/anaconda-4-release/
You should know what you do, because conda could break due to the forced installation. If you would like to get more flexibility/security you could use pkg-manager like nix(-pkgs) [with nix-shell] / NixOS.
On Linux, the symlink /proc/<pid>/exe
has the path of the executable. Use the command readlink -f /proc/<pid>/exe
to get the value.
On AIX, this file does not exist. You could compare cksum <actual path to binary>
and cksum /proc/<pid>/object/a.out
.
What is the proper #include for the function 'sleep()'?
sleep()
isn't Standard C, but POSIX so it should be:
#include <unistd.h>
Here's a self-sufficient JS function that solves this (and other) problems for most European/US locales (primarily between US/German/Swedish number chunking and formatting ... as in the OP). I think it's an improvement on (and inspired by) Slawa's solution, and has no dependencies.
function realParseFloat(s)
{
s = s.replace(/[^\d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
if (navigator.language.substring(0, 2) !== "de" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(s)) // if not in German locale and matches #,###.######
{
s = s.replace(/,/g, ''); // strip out commas
return parseFloat(s); // convert to number
}
else if (/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
{
s = s.replace(/\./g, ''); // strip out dots
s = s.replace(/,/g, '.'); // replace comma with dot
return parseFloat(s);
}
else // try #,###.###### anyway
{
s = s.replace(/,/g, ''); // strip out commas
return parseFloat(s); // convert to number
}
}
This is the simple answer I can give.
YouTube resolutions and images
http://img.youtube.com/vi/<video-id>/<resolution><image>.jpg
Resolution
- lowest resolution
sd - Standard Definition
mq - Medium Quality
hq - High Quality
maxres - MAXimum RESolution
Image
default - Default image (1, 2, 3 shot from video, or custom uploaded)
1 - First shot from video
2 - Second shot from video
3 - Third shot from video
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration
where MerchantId =@ MerchantID
In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working.
I assume that your page is on http://my-site.local:8088.
The reason why you see different results is that Postman:
Host=example.com
(your API)Origin
This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088
, however I don't see it in Postman). When Origin
header is not set, usually servers allow such requests by default.
This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:
Host=example.com
(yours as API)Origin=http://my-site.local:8088
(your site)(The header Referer
has the same value as Origin
). And now in Chrome's Console & Networks tab you will see:
When you have Host != Origin
this is CORS, and when the server detects such a request, it usually blocks it by default.
Origin=null
is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>
, like in the below snippet (but here the Host
header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null
. More information about this you can find here.
fetch('http://example.com/api', {method: 'POST'});
_x000D_
Look on chrome-console > network tab
_x000D_
If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:
fetch('http://example.com/api', {_x000D_
method: 'POST',_x000D_
headers: { 'Content-Type': 'application/json'}_x000D_
});
_x000D_
Look in chrome-console -> network tab to 'api' request._x000D_
This is the OPTIONS request (the server does not allow sending a POST request)
_x000D_
You can change the configuration of your server to allow CORS requests.
Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin"
for nginx and "*"
for Apache - this will unblock CORS from any domain.
location ~ ^/index\.php(/|$) {_x000D_
..._x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
if ($request_method = OPTIONS) {_x000D_
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
add_header 'Content-Length' 0;_x000D_
add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
return 204;_x000D_
}_x000D_
}
_x000D_
Here is an example configuration which turns on CORS on Apache (.htaccess file)
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
# Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
# Header set Header set Access-Control-Allow-Origin "*"_x000D_
# Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Access-Control-Allow-Origin "http://your-page.com:80"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
From the python docs on os.walk()
:
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
The Gradle popup window only shows intermittent progress and is not very helpful in understanding if the download is actually stuck or is very slow.
It will help to build your app from the command line where you can actually get the real progress of downloading with
./gradlew build
Do no write a function() to include files in a directory. You may lose the variable scopes, and may have to use "global". Just loop on the files.
Also, you may run into difficulties when an included file has a class name that will extend to the other class defined in the other file - which is not yet included. So, be careful.
It is ||
, for example:
select 'Mr ' || ename from emp;
The only "interesting" feature I can think of is that 'x' || null
returns 'x'
, not null
as you might perhaps expect.
Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.
Put this in your init function:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
It will work.
If you have a pandas serie with NaN, and want to remove it (without loosing index):
serie = serie.dropna()
# create data for example
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)
0 g
1 NaN
2 NaN
3 k
4 s
dtype: object
# the code
ser = ser.dropna()
print(ser)
0 g
3 k
4 s
dtype: object
Try to switch a
to block
display, and then use any style you want. The a
element will fill the li
element, and you will be able to modify its look as you want. Don't forget to set li
padding to 0.
li {
padding: 0;
overflow: hidden;
}
a {
display: block;
width: 100%;
color: ..., background: ..., border-radius: ..., etc...
}
a.active {
color: ..., background: ...
}
Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...
public ActionResult Post([FromBody]MyDTOClass inputData){
... do something with input data ...
}
Thx to Julias:
Make sure your request is sent with the http header:
Content-Type: application/json
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
You can use background-size: cover;
MySQL will assume the part before the equals references the columns named in the INSERT INTO clause, and the second part references the SELECT columns.
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT id, uid, t.location, t.animal, t.starttime, t.endtime, t.entct,
t.inact, t.inadur, t.inadist,
t.smlct, t.smldur, t.smldist,
t.larct, t.lardur, t.lardist,
t.emptyct, t.emptydur
FROM tmp t WHERE uid=x
ON DUPLICATE KEY UPDATE entct=t.entct, inact=t.inact, ...
Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-
After reading your comment on my previous answer I thought I might put this as a separate answer.
Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.
That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with
WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/
This is the jQuery
$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
}
else{
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
}
else{
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
});
So now the explanation.
Stage 1
1) Load the script on document ready.
2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.
3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;
Stage 2
Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.
2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.
3) We remove the class oldActive because it's no longer needed.
4) fadeOut all of the slides
5) fade In the active slides
Step 3
Same as in step two but using some reverse logic for traversing through the elements backwards.
It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
Simply add your NextActivity
in the Manifest.XML
file
<activity
android:name="com.example.sms1.NextActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
using System.ComponentModel;
TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));
Since Fedora 22 yum has been deprecated so the commands given in other answers will actually fire up 'Dandified yum' i.e. dnf
. So the new command to install g++ in recent distributions is
su -c "dnf install gcc-c++"
As of Nov 2015 this installs the 5.1.1 version.
Also note that in Fedora 23 when I gave the command g++ -v
, Fedora automatically asked me if I want to install gcc-c++ package. I think thats nice.(After the install it also ran the command g++ -v
for me)
Only nit pick that I can do about it is that instead of a progress indicator you just get * Downloading packages...
message which you may not like if you are on a slow internet connection.
\p{L}
matches a single code point in the category "letter".
\p{N}
matches any kind of numeric character in any script.
Source: regular-expressions.info
If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.
try:
a # does a exist in the current namespace
except NameError:
a = 10 # nope
And make sure your route in the list of routes:
./manage.py show_urls | grep path_or_name
If you're using CentOS 7, and you've installed Docker via yum, don't forget to run:
$ sudo systemctl start docker
$ sudo systemctl enable docker
This will start the server, as well as re-start it automatically on boot.
I was trying to measure the time between events with the exception of what one entry that has multiple processes between the start and end. I needed this in the context of other single line processes.
I used a select with an inner join as my select statement within the Nth cte. The second cte I needed to extract the start date on X and end date on Y and used 1 as an id value to left join to put them on a single line.
Works for me, hope this helps.
cte_extract
as
(
select ps.Process as ProcessEvent
, ps.ProcessStartDate
, ps.ProcessEndDate
-- select strt.*
from dbo.tbl_some_table ps
inner join (select max(ProcessStatusId) ProcessStatusId
from dbo.tbl_some_table
where Process = 'some_extract_tbl'
and convert(varchar(10), ProcessStartDate, 112) < '29991231'
) strt on strt.ProcessStatusId = ps.ProcessStatusID
),
cte_rls
as
(
select 'Sample' as ProcessEvent,
x.ProcessStartDate, y.ProcessEndDate from (
select 1 as Id, ps.Process as ProcessEvent
, ps.ProcessStartDate
, ps.ProcessEndDate
-- select strt.*
from dbo.tbl_some_table ps
inner join (select max(ProcessStatusId) ProcessStatusId
from dbo.tbl_some_table
where Process = 'XX Prcss'
and convert(varchar(10), ProcessStartDate, 112) < '29991231'
) strt on strt.ProcessStatusId = ps.ProcessStatusID
) x
left join (
select 1 as Id, ps.Process as ProcessEvent
, ps.ProcessStartDate
, ps.ProcessEndDate
-- select strt.*
from dbo.tbl_some_table ps
inner join (select max(ProcessStatusId) ProcessStatusId
from dbo.tbl_some_table
where Process = 'YY Prcss Cmpltd'
and convert(varchar(10), ProcessEndDate, 112) < '29991231'
) enddt on enddt.ProcessStatusId = ps.ProcessStatusID
) y on y.Id = x.Id
),
.... other ctes
in console (cmd), go to app root path and execute:
type .env.example > .env
One important function of the main
key is that it provides the path for your entry point. This is very helpful when working with nodemon
. If you work with nodemon
and you define the main
key in your package.json
as let say "main": "./src/server/app.js"
, then you can simply crank up the server with typing nodemon
in the CLI with root as pwd instead of nodemon ./src/server/app.js
.
Checking if v
contains the element x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
move_uploaded_file()
will return:
FALSE
if file name is invalidFALSE
and issue a warning
in the error log if the apache process does not have read/write permissions to source or destination directoriesPHP Error Log
My php error log was at: /var/log/httpd/error_log
and had these errors:
Warning: move_uploaded_file(images/robot.jpg): failed to open stream: Permission denied in /var/www/html/mysite/mohealth.php on line 78
Warning: move_uploaded_file(): Unable to move '/tmp/phpsKD2Qm' to 'images/robot.jpg' in /var/www/html/mysite/mohealth.php on line 78
move_uploaded_file()
tries to move files from a temporary directory to a destination directory. When apache process tried to move files, it could not read the temporary or write to the destination dir.
Find which user is running Apache (Web Server)
Check which user is running the apache service by this command: ps aux | grep httpd
. The first column is the user name.
Check Read Permission at Temporary Dir: Your can find the path to your temp dir by calling echo sys_get_tmp_dir();
in a php page. Then on the command line, issue ls -ld /tmp/temporary-dir
to see if the apache user has access to read here
Check Write Permission at Destination Dir: issue ls -ld /var/www/html/destination-directory
to see if the apache user has access to write here
Add permissions as necessary using chown
or chgrp
Restart Apache using sudo service httpd restart
What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub
and also very nice Modern UI on GitHub. (.NET4.5 only)
There is one more it's Elysium but I really didn't try this one.
The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.
Here is code (please note that it's targeting .NET4.5)
public class MyWindow : Window
{
public MyWindow()
{
this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
}
private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
}
private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
}
private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
{
SystemCommands.RestoreWindow(this);
}
}
And here resources:
<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />
<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>
<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>
<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Padding" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter x:Name="contentPresenter"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
<Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
<Setter Property="ResizeMode" Value="CanResizeWithGrip" />
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyWindow">
<Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
<Grid>
<Border BorderThickness="1">
<AdornerDecorator>
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="*" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
<Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
<Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
<Grid Margin="1,0,1,0">
<Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
<Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1" />
</Grid>
</Button.Content>
</Button>
<Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="31" Height="25">
<Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2" />
</Grid>
</Button.Content>
</Button>
</Grid>
<Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close" Style="{StaticResource WindowButtonStyle}">
<Button.Content>
<Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
<Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5" />
</Grid>
</Button.Content>
</Button>
</StackPanel>
<TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="8 -1 0 0" FontSize="16" Foreground="{TemplateBinding Foreground}"/>
<Grid Grid.Row="2">
<Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
</Grid>
</Grid>
</AdornerDecorator>
</Border>
<Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="WindowState" Value="Maximized">
<Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
<Setter TargetName="Restore" Property="Visibility" Value="Visible" />
<Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
</Trigger>
<Trigger Property="WindowState" Value="Normal">
<Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
<Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ResizeMode" Value="CanResizeWithGrip" />
<Condition Property="WindowState" Value="Normal" />
</MultiTrigger.Conditions>
<Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
</Setter.Value>
</Setter>
</Style>
Ok...so first you need to import the image into your project.
1) Select the PictureBox in the Form Design View
2) Open PictureBox Tasks
(it's the little arrow printed to right on the edge of the PictureBox)
3) Click on "Choose image..."
4) Select the second option "Project resource file:"
(this option will create a folder called "Resources" which you can access with Properties.Resources)
5) Click on "Import..." and select your image from your computer
(now a copy of the image will be saved in "Resources" folder created at step 4)
6) Click on "OK"
Now the image is in your project and you can use it with the Properties command. Just type this code when you want to change the picture in the PictureBox:
pictureBox1.Image = Properties.Resources.MyImage;
Note:
MyImage represent the name of the image...
After typing "Properties.Resources.", all imported image files are displayed...
If the array is sorted in ascending or descending order then you can find it with complexity O(1). For an array of ascending order the first element is the smallest element, you can get it by arr[0] (0 based indexing). If the array is sorted in descending order then the last element is the smallest element,you can get it by arr[sizeOfArray-1].
If the array is not sorted then you have to iterate over the array to get the smallest element.In this case time complexity is O(n), here n is the size of array.
int arr[] = {5,7,9,0,-3,2,3,4,56,-7};
int smallest_element=arr[0] //let, first element is the smallest one
for(int i =1;i<sizeOfArray;i++)
{
if(arr[i]<smallest_element)
{
smallest_element=arr[i];
}
}
You can calculate it in input section (when you have to find smallest element from a given array)
int smallest_element;
int arr[100],n;
cin>>n;
for(int i = 0;i<n;i++)
{
cin>>arr[i];
if(i==0)
{
smallest_element=arr[i]; //smallest_element=arr[0];
}
else if(arr[i]<smallest_element)
{
smallest_element = arr[i];
}
}
Also you can get smallest element by built in function
#inclue<algorithm>
int smallest_element = *min_element(arr,arr+n); //here n is the size of array
You can get smallest element of any range by using this function such as,
int arr[] = {3,2,1,-1,-2,-3};
cout<<*min_element(arr,arr+3); //this will print 1,smallest element of first three element
cout<<*min_element(arr+2,arr+5); // -2, smallest element between third and fifth element (inclusive)
I have used asterisk (*), before min_element() function. Because it returns pointer of smallest element. All codes are in c++. You can find the maximum element in opposite way.
A bit late here, but thanks to "How do I validate a date in rails?" I managed to write this validator, hope is useful to somebody:
Inside your model.rb
validate :date_field_must_be_a_date_or_blank
# If your field is called :date_field, use :date_field_before_type_cast
def date_field_must_be_a_date_or_blank
date_field_before_type_cast.to_date
rescue ArgumentError
errors.add(:birthday, :invalid)
end
I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.
// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
Go back and forth using the subtract()
and add()
with the endOf()
and startOf()
:
// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
I am agree with @Chad Grant
Also right if you convert to string then you can use that value as numeric as said in the question
int bar = Convert.ToInt32(new string(foo, 1)); // => gives bar=2
I tried to create a more simple and understandable example
char v = '1';
int vv = (int)char.GetNumericValue(v);
char.GetNumericValue(v) returns as double and converts to (int)
More Advenced usage as an array
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
This is a continuation of the answers from MarsAndBack and Miftah Mizwar.
Their answers are correct. However, it is difficult to identify the problem ancestor(s).
To make this very simple, simply run this jQuery script in your browser console and it will tell you the value of the overflow property on every ancestor.
$('.your-sticky-element').parents().filter(function() {
console.log($(this));
console.log($(this).css('overflow'));
return $(this).css('overflow') === 'hidden';
});
Where an ancestor does not have overflow: visible
change its CSS so that it does!
Also, as stated elsewhere, make sure your sticky element has this in the CSS:
.your-sticky-element {
position: sticky;
top: 0;
}
You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:
lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Then you can get hold of the axes objects (an array of axes):
axes = lm.axes
After that you can tweak the axes properties
axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)
creates:
A single css code on hover can do the trick:
box-shadow: inset 100px 0 0 0 #e0e0e0;
A complete demo can be found in my fiddle:
Try to do something like this:
db.getCollection('collectionName').find({'ArrayName.1': {$exists: true}})
1 is number, if you want to fetch record greater than 50 then do ArrayName.50 Thanks.
Try update your Eclipse with the newest Maven repository as follows:
This formula will do the job:
=INDEX(G:G,MATCH(FALSE,ISERROR(SEARCH(H1,G:G)),0)+3)
you need to enter it as an array formula, i.e. press Ctrl-Shift-Enter. It assumes that the substring you're searching for is in cell H1
.
For a more simple and up to date answer:
backdrop-filter: blur(6px);
Note browser support is not perfect but in most cases a blur would be non essential.
quirksmode has a good description of the 'text-overflow' property, but you may need to apply some additional properties like 'white-space: nowrap'
Whilst I'm not 100% how this will behave in a select object, it could be worth trying this first:
An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.
The service maintains all the issued keys and checks them at each request.
By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.
I will provide general Q&A-oriented answer for this question:
Answer to Questions
Why do we need XML parser?
We need XML parser because we do not want to do everything in our application from scratch, and we need some "helper" programs or libraries to do something very low-level but very necessary to us. These low-level but necessary things include checking the well-formedness, validating the document against its DTD or schema (just for validating parsers), resolving character reference, understanding CDATA sections, and so on. XML parsers are just such "helper" programs and they will do all these jobs. With XML parser, we are shielded from a lot of these complexities and we could concentrate ourselves on just programming at high-level through the API's implemented by the parsers, and thus gain programming efficiency.
Which one is better, SAX or DOM ?
Both SAX and DOM parser have their advantages and disadvantages. Which one is better should depend on the characteristics of your application (please refer to some questions below).
Which parser can get better speed, DOM or SAX parsers?
SAX parser can get better speed.
What's the difference between tree-based API and event-based API?
A tree-based API is centered around a tree structure and therefore provides interfaces on components of a tree (which is a DOM document) such as Document interface,Node interface, NodeList interface, Element interface, Attr interface and so on. By contrast, however, an event-based API provides interfaces on handlers. There are four handler interfaces, ContentHandler interface, DTDHandler interface, EntityResolver interface and ErrorHandler interface.
What is the difference between a DOM Parser and a SAX Parser?
DOM parsers and SAX parsers work in different ways:
A DOM parser creates a tree structure in memory from the input document and then waits for requests from client. But a SAX parser does not create any internal structure. Instead, it takes the occurrences of components of a input document as events, and tells the client what it reads as it reads through the input document. A
DOM parser always serves the client application with the entire document no matter how much is actually needed by the client. But a SAX parser serves the client application always only with pieces of the document at any given time.
How do we decide on which parser is good?
Ideally a good parser should be fast (time efficient),space efficient, rich in functionality and easy to use. But in reality, none of the main parsers have all these features at the same time. For example, a DOM Parser is rich in functionality (because it creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree), but it is space inefficient when the document is huge, and it takes a little bit long to learn how to work with it. A SAX Parser, however, is much more space efficient in case of big input document (because it creates no internal structure). What's more, it runs faster and is easier to learn than DOM Parser because its API is really simple. But from the functionality point of view, it provides less functions which mean that the users themselves have to take care of more, such as creating their own data structures. By the way, what is a good parser? I think the answer really depends on the characteristics of your application.
What are some real world applications where using SAX parser is advantageous than using DOM parser and vice versa? What are the usual application for a DOM parser and for a SAX parser?
In the following cases, using SAX parser is advantageous than using DOM parser.
In the following cases, using DOM parser is advantageous than using SAX parser.
Example (Use a DOM parser or a SAX parser?):
Assume that an instructor has an XML document containing all the personal information of the students as well as the points his students made in his class, and he is now assigning final grades for the students using an application. What he wants to produce, is a list with the SSN and the grades. Also we assume that in his application, the instructor use no data structure such as arrays to store the student personal information and the points. If the instructor decides to give A's to those who earned the class average or above, and give B's to the others, then he'd better to use a DOM parser in his application. The reason is that he has no way to know how much is the class average before the entire document gets processed. What he probably need to do in his application, is first to look through all the students' points and compute the average, and then look through the document again and assign the final grade to each student by comparing the points he earned to the class average. If, however, the instructor adopts such a grading policy that the students who got 90 points or more, are assigned A's and the others are assigned B's, then probably he'd better use a SAX parser. The reason is, to assign each student a final grade, he do not need to wait for the entire document to be processed. He could immediately assign a grade to a student once the SAX parser reads the grade of this student. In the above analysis, we assumed that the instructor created no data structure of his own. What if he creates his own data structure, such as an array of strings to store the SSN and an array of integers to sto re the points ? In this case, I think SAX is a better choice, before this could save both memory and time as well, yet get the job done. Well, one more consideration on this example. What if what the instructor wants to do is not to print a list, but to save the original document back with the grade of each student updated ? In this case, a DOM parser should be a better choice no matter what grading policy he is adopting. He does not need to create any data structure of his own. What he needs to do is to first modify the DOM tree (i.e., set value to the 'grade' node) and then save the whole modified tree. If he choose to use a SAX parser instead of a DOM parser, then in this case he has to create a data structure which is almost as complicated as a DOM tree before he could get the job done.
Problem statement: Write a Java program to extract all the information about circles which are elements in a given XML document. We assume that each circle element has three child elements(i.e., x, y and radius) as well as a color attribute. A sample document is given below:
<?xml version="1.0"?>
<!DOCTYPE shapes [
<!ELEMENT shapes (circle)*>
<!ELEMENT circle (x,y,radius)>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
<!ELEMENT radius (#PCDATA)>
<!ATTLIST circle color CDATA #IMPLIED>
]>
<shapes>
<circle color="BLUE">
<x>20</x>
<y>20</y>
<radius>20</radius>
</circle>
<circle color="RED" >
<x>40</x>
<y>40</y>
<radius>20</radius>
</circle>
</shapes>
Program with DOMparser
import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
public class shapes_DOM {
static int numberOfCircles = 0; // total number of circles seen
static int x[] = new int[1000]; // X-coordinates of the centers
static int y[] = new int[1000]; // Y-coordinates of the centers
static int r[] = new int[1000]; // radius of the circle
static String color[] = new String[1000]; // colors of the circles
public static void main(String[] args) {
try{
// create a DOMParser
DOMParser parser=new DOMParser();
parser.parse(args[0]);
// get the DOM Document object
Document doc=parser.getDocument();
// get all the circle nodes
NodeList nodelist = doc.getElementsByTagName("circle");
numberOfCircles = nodelist.getLength();
// retrieve all info about the circles
for(int i=0; i<nodelist.getLength(); i++) {
// get one circle node
Node node = nodelist.item(i);
// get the color attribute
NamedNodeMap attrs = node.getAttributes();
if(attrs.getLength() > 0)
color[i]=(String)attrs.getNamedItem("color").getNodeValue();
// get the child nodes of a circle node
NodeList childnodelist = node.getChildNodes();
// get the x and y value
for(int j=0; j<childnodelist.getLength(); j++) {
Node childnode = childnodelist.item(j);
Node textnode = childnode.getFirstChild();//the only text node
String childnodename=childnode.getNodeName();
if(childnodename.equals("x"))
x[i]= Integer.parseInt(textnode.getNodeValue().trim());
else if(childnodename.equals("y"))
y[i]= Integer.parseInt(textnode.getNodeValue().trim());
else if(childnodename.equals("radius"))
r[i]= Integer.parseInt(textnode.getNodeValue().trim());
}
}
// print the result
System.out.println("circles="+numberOfCircles);
for(int i=0;i<numberOfCircles;i++) {
String line="";
line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
System.out.println(line);
}
} catch (Exception e) {e.printStackTrace(System.err);}
}
}
Program with SAXparser
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.xerces.parsers.SAXParser;
public class shapes_SAX extends DefaultHandler {
static int numberOfCircles = 0; // total number of circles seen
static int x[] = new int[1000]; // X-coordinates of the centers
static int y[] = new int[1000]; // Y-coordinates of the centers
static int r[] = new int[1000]; // radius of the circle
static String color[] = new String[1000]; // colors of the circles
static int flagX=0; //to remember what element has occurred
static int flagY=0; //to remember what element has occurred
static int flagR=0; //to remember what element has occurred
// main method
public static void main(String[] args) {
try{
shapes_SAX SAXHandler = new shapes_SAX (); // an instance of this class
SAXParser parser=new SAXParser(); // create a SAXParser object
parser.setContentHandler(SAXHandler); // register with the ContentHandler
parser.parse(args[0]);
} catch (Exception e) {e.printStackTrace(System.err);} // catch exeptions
}
// override the startElement() method
public void startElement(String uri, String localName,
String rawName, Attributes attributes) {
if(rawName.equals("circle")) // if a circle element is seen
color[numberOfCircles]=attributes.getValue("color"); // get the color attribute
else if(rawName.equals("x")) // if a x element is seen set the flag as 1
flagX=1;
else if(rawName.equals("y")) // if a y element is seen set the flag as 2
flagY=1;
else if(rawName.equals("radius")) // if a radius element is seen set the flag as 3
flagR=1;
}
// override the endElement() method
public void endElement(String uri, String localName, String rawName) {
// in this example we do not need to do anything else here
if(rawName.equals("circle")) // if a circle element is ended
numberOfCircles += 1; // increment the counter
}
// override the characters() method
public void characters(char characters[], int start, int length) {
String characterData =
(new String(characters,start,length)).trim(); // get the text
if(flagX==1) { // indicate this text is for <x> element
x[numberOfCircles] = Integer.parseInt(characterData);
flagX=0;
}
else if(flagY==1) { // indicate this text is for <y> element
y[numberOfCircles] = Integer.parseInt(characterData);
flagY=0;
}
else if(flagR==1) { // indicate this text is for <radius> element
r[numberOfCircles] = Integer.parseInt(characterData);
flagR=0;
}
}
// override the endDocument() method
public void endDocument() {
// when the end of document is seen, just print the circle info
System.out.println("circles="+numberOfCircles);
for(int i=0;i<numberOfCircles;i++) {
String line="";
line=line+"(x="+x[i]+",y="+y[i]+",r="+r[i]+",color="+color[i]+")";
System.out.println(line);
}
}
}
osx could be using launchctl to launch mysql. Try this:
sudo launchctl unload -w /Library/LaunchDaemons/com.mysql.mysqld.plist
using System;
using System.Drawing;
public struct MyColor
{
private byte a, r, g, b;
public byte A
{
get
{
return this.a;
}
}
public byte R
{
get
{
return this.r;
}
}
public byte G
{
get
{
return this.g;
}
}
public byte B
{
get
{
return this.b;
}
}
public MyColor SetAlpha(byte value)
{
this.a = value;
return this;
}
public MyColor SetRed(byte value)
{
this.r = value;
return this;
}
public MyColor SetGreen(byte value)
{
this.g = value;
return this;
}
public MyColor SetBlue(byte value)
{
this.b = value;
return this;
}
public int ToArgb()
{
return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
}
public override string ToString ()
{
return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
}
public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
{
return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
}
public static MyColor FromArgb(byte red, byte green, byte blue)
{
return MyColor.FromArgb(255, red, green, blue);
}
public static MyColor FromArgb(byte alpha, MyColor baseColor)
{
return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
}
public static MyColor FromArgb(int argb)
{
return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
}
public static implicit operator Color(MyColor myColor)
{
return Color.FromArgb(myColor.ToArgb());
}
public static implicit operator MyColor(Color color)
{
return MyColor.FromArgb(color.ToArgb());
}
}
Your friend's PC is missing the runtime support DLLs for your program:
If you want to get string representations of MyEnum
variables, then templates won't cut it. Template can be specialized on integral values known at compile-time.
However, if that's what you want then try:
#include <iostream>
enum MyEnum { VAL1, VAL2 };
template<MyEnum n> struct StrMyEnum {
static char const* name() { return "Unknown"; }
};
#define STRENUM(val, str) \
template<> struct StrMyEnum<val> { \
static char const* name() { return str; }};
STRENUM(VAL1, "Value 1");
STRENUM(VAL2, "Value 2");
int main() {
std::cout << StrMyEnum<VAL2>::name();
}
This is verbose, but will catch errors like the one you made in question - your case VAL1
is duplicated.
Another reason for this error could be incorrect or non-existent database name.
Forcing the TCP/IP connection (by providing 127.0.0.1
instead of localhost
or .
) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.
So, here is the checklist:
I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...
x
DROP a
;any tables which had the table now haven't any tables which didn't will have shown an error in the logs
then you can find/replace 'drop a
' change it to 'ADD COLUMN b
INT NULL' etc and run the whole thing again....
a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.
Just use:
if file_name.endswith(tuple(extensions)):
random.sample()
also works on text
example:
> text = open("textfile.txt").read()
> random.sample(text, 5)
> ['f', 's', 'y', 'v', '\n']
\n is also seen as a character so that can also be returned
you could use random.sample()
to return random words from a text file if you first use the split method
example:
> words = text.split()
> random.sample(words, 5)
> ['the', 'and', 'a', 'her', 'of']
Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver
under on reboot and wanted to keep all my cron jobs in one place.
I was getting the following error for the VNC cron:
vncserver: The USER environment variable is not set. E.g.:
In my case, I was able to use sudo
to specify who to run the task as.
@reboot sudo -u [someone] vncserver ...
For example, you can define a layout file which contains a EditText element.
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/searchfield"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textFilter" >
</EditText>
you can do
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
search.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
Toast.makeText(MainActivity.this, "Search triggered",
Toast.LENGTH_LONG).show();
return false;
}
});
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
}
Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5
EDIT: According to this post it is a known issue.
And this could be the solution you're looking for :)
var array = new Uint8Array(100);
array[10] = 256;
array[10] === 0 // true
I verified in firefox and chrome, its really an array of bytes :
var array = new Uint8Array(1024*1024*50); // allocates 50MBytes
If source code is on Github, you can use their comparing tool: https://help.github.com/articles/comparing-commits-across-time/
Thanks Antonio,
I've just added the lists
command at the end so it will only return one array with key and count:
Laravel 4
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser');
Laravel 5.1
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->lists('total','browser')->all();
Laravel 5.2+
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->pluck('total','browser')->all();
Another option is typing Ctrl+V Ctrl+J at the end of each command.
Example (replace #
with Ctrl+V Ctrl+J):
$ echo 1#
echo 2#
echo 3
Output:
1
2
3
This will execute the commands regardless if previous ones failed.
Same as: echo 1; echo 2; echo 3
If you want to stop execution on failed commands, add &&
at the end of each line except the last one.
Example (replace #
with Ctrl+V Ctrl+J):
$ echo 1 &&#
failed-command &&#
echo 2
Output:
1
failed-command: command not found
In zsh
you can also use Alt+Enter or Esc+Enter instead of Ctrl+V Ctrl+J
String
has a charAt
method that returns the character at the specified position. Like arrays and List
s, String
is 0-indexed, i.e. the first character is at index 0
and the last character is at index length() - 1
.
So, assuming getSymbol()
returns a String
, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
Floating div's will help what your trying to achieve.
HTML
<div class="container">
<div class="content1 content">
</div>
<div class="content2 content">
</div>
</div>
CSS
.container{
width:100%;
height:200px;
background-color:grey;
}
.content{
float:left;
height:30px;
}
.content1{
background-color:blue;
width:300px;
}
.content2{
width:200px;
background-color:green;
}
Zoom in the page to see the effects.
Hope it helps.
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
This feature has been added in dplyr v0.3. You can now pass a named character vector to the by
argument in left_join
(and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:
left_join(test_data, kantrowitz, by = c("first_name" = "name"))
none of the above answers worked for me. This one did:
=QUERY(Copy!A1:AP, "select AP, E, F, AO where AP="&E1&" ",1)
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Here's some code that might do the trick for you (taken from Ryan Farley's blog)
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>{
u.Name = "User" + u.Name;
return u;
}, (key,g)=>g.ToList())
.ToList();
If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public Customer CloneWithNamePrepend(string prepend){
return new Customer(){
ID = this.ID,
Name = prepend + this.Name,
GroupID = this.GroupID
};
}
}
//Then
var groupedCustomerList = CustomerList
.GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
.ToList();
I think you may want to display the Customer
differently without modifying the original data. If so you should design your class Customer
differently, like this:
public class Customer {
public int ID { get; set; }
public string Name { get; set; }
public int GroupID { get; set; }
public string Prefix {get;set;}
public string FullName {
get { return Prefix + Name;}
}
}
//then to display the fullname, just get the customer.FullName;
//You can also try adding some override of ToString() to your class
var groupedCustomerList = CustomerList
.GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
.ToList();
This is the sort of thing that sed
is really good at: $ sed 's/[ \t]*$//'
. Be aware the you will probably need to literally type a TAB character instead of \t
for this to work.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
both specify elements, attributes, nesting, ordering, #occurences
XSD also has data types, (typed) pointers, namespaces, keys and more.... unlike DTD
Moreover though XSD is little verbose its syntax is extension of XML, making it convenient to learn fast.
Usually this is due to another directive in-between your ng-controller and your input that is creating a new scope. When the select writes out it value, it will write it up to the most recent scope, so it would write it to this scope rather than the parent that is further away.
The best practice is to never bind directly to a variable on the scope in an
ng-model
, this is also known as always including a "dot" in your ngmodel. For a better explanation of this, check out this video from John:
Solution from: https://groups.google.com/forum/#!topic/angular/7Nd_me5YrHU
You can use this as a generic solution:
import os
def getParentDir(path, level=1):
return os.path.normpath( os.path.join(path, *([".."] * level)) )
You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.
The getEncoding() method will return the encoding which was set up (read the JavaDoc) for the stream. It will not guess the encoding for you.
Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.
Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.
Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one.
I Hope that this helps you out... Because I tried all the answers but nothing worked perfectly. So, I had to come up with a solution on my own.
#horizontal-style {
padding-inline-start: 0 !important; // Just in case if you find that there is an extra padding at the start of the line
justify-content: space-around;
display: flex;
}
#horizontal-style a {
text-align: center;
color: white;
text-decoration: none;
}
I tend to look at it from the inverse perspective which may be what you intended:
What characters do I want to allow?
This is because there could be lots of characters that make in into a string somehow that blow stuff up that you wouldn't expect.
For example this one only allows for letters and numbers removing groups of invalid characters replacing them with a hypen:
"This¢£«±Ÿ÷could&*()\/<>be!@#$%^bad".replace(/([^a-z0-9]+)/gi, '-');
//Result: "This-could-be-bad"
If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+
.
You can then map
each element using the Number
function to convert it. Note that parseInt
will not work (i.e. arr.map(parseInt)
) because map
passes three arguments to the mapping function: the element, the index, and the original array. parseInt
accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaN
s in the result. However, Number
ignores any arguments other than the first, so it works directly.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]
You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]
With an anonymous function for the callback, you can decide what parameters to use, so parseInt
can also work.
const str = '1\t\t2 3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]
Singleton is, of course, an "anti-pattern" (assuming a definition of a static with variable state).
If you want a fixed set of immutable value objects, then enums are the way to go. For a large, possibly open-ended set of values, you can use a Repository of some form - usually based on a Map
implementation. Of course, when you are dealing with statics be careful with threading (either synchronise sufficiently widely or use a ConcurrentMap
either checking that another thread hasn't beaten you or use some form of futures).
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
DECLARE @col int;
select @col = id FROM site WHERE status = 1;
select coalesce(@col,0);
In a console application, just return from the main program, in a UI-Application Close() all active Forms.
Memory from managed objects will be handled by the .NET Framework, you don't need to care about this.
If you use classes which implement IDisposable (like database connections, for example), you should call Dispose() on them when you no longer need them (preferred way: a using-Statement).
If you use such resources globally (like private members in your form), your form should implement the IDisposable pattern to release these resources on the Close()-call. See this article for details.
Your code requires that the Dog
class has overridden the toString()
method so that it knows how to print itself out. Otherwise, your code looks correct.
A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
I always make a call from the end of the JavaScript files for registering its loading and it used to work perfect for me for all the browsers.
Ex: I have an index.htm, Js1.js and Js2.js. I add the function IAmReady(Id) in index.htm header and call it with parameters 1 and 2 from the end of the files, Js1 and Js2 respectively. The IAmReady function will have a logic to run the boot code once it gets two calls (storing the the number of calls in a static/global variable) from the two js files.
The method with fetch is the best solution, but if anyone needs to use a method without fetch then here it is, as the ones mentioned previously didn't work for me:
function makeblob(dataURL) {
const BASE64_MARKER = ';base64,';
const parts = dataURL.split(BASE64_MARKER);
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
For Android: in android.text.TextUtils there are methods:
public static String join (CharSequence delimiter, Iterable tokens)
public static String join (CharSequence delimiter, Object[] tokens)
Returns a string containing the tokens joined by delimiters.
tokens -- an array objects to be joined. Strings will be formed from the objects by calling object.toString().
here you need to skip int 0 like following:
val = s.nextInt();
if ((val < min) && (val!=0)) {
min = val;
}
To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js
filename to get on-click installation when you click on Raw and get this page:
As Janoulle pointed out, you don't need to detect which extension it is if you use the WorkbookFactory, it will do it for you. I recently had to implement a solution using NPOI to read Excel files and import email addresses into a sql database. My main problem was that I was probably going to receive about 12 different Excel layouts from different customers so I needed something that could be changed quickly without much code. I ended up using Npoi.Mapper which is an awesome tool! Highly recommended!
Here is my complete solution:
using System.IO;
using System.Linq;
using Npoi.Mapper;
using Npoi.Mapper.Attributes;
using NPOI.SS.UserModel;
namespace JobCustomerImport.Processors
{
public class ExcelEmailProcessor
{
private UserManagementServiceContext DataContext { get; }
public ExcelEmailProcessor(int customerNumber)
{
DataContext = new UserManagementServiceContext();
}
public void Execute(string localPath, int sheetIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);
}
var importer = new Mapper(workbook);
var items = importer.Take<MurphyExcelFormat>(sheetIndex);
foreach(var item in items)
{
var row = item.Value;
if (string.IsNullOrEmpty(row.EmailAddress))
continue;
UpdateUser(row);
}
DataContext.SaveChanges();
}
private void UpdateUser(MurphyExcelFormat row)
{
//LOGIC HERE TO UPDATE A USER IN DATABASE...
}
private class MurphyExcelFormat
{
[Column("District")]
public int District { get; set; }
[Column("DM")]
public string FullName { get; set; }
[Column("Email Address")]
public string EmailAddress { get; set; }
[Column(3)]
public string Username { get; set; }
public string FirstName
{
get
{
return Username.Split('.')[0];
}
}
public string LastName
{
get
{
return Username.Split('.')[1];
}
}
}
}
}
I am so happy with NPOI + Npoi.Mapper (from Donny Tian) as an Excel import solution that I wrote a blog post about it, going in to more detail about this code above. You can read it here if you wish: Easiest way to import excel files. The best thing about this solution is that it runs perfectly in a serverless azure/cloud environment which I couldn't get with other Excel tools/libraries.
Warning: Unfortunately I believe most popular platforms have dropped support for comprehensions. See below for the well-supported ES6 method
You can always use something like:
[for (i of Array(7).keys()) i*i];
Running this code on Firefox:
[ 0, 1, 4, 9, 16, 25, 36 ]
This works on Firefox (it was a proposed ES7 feature), but it has been dropped from the spec. IIRC, Babel 5 with "experimental" enabled supports this.
This is your best bet as array-comprehension are used for just this purpose. You can even write a range function to go along with this:
var range = (u, l = 0) => [ for( i of Array(u - l).keys() ) i + l ]
Then you can do:
[for (i of range(5)) i*i] // 0, 1, 4, 9, 16, 25
[for (i of range(5,3)) i*i] // 9, 16, 25
A nice way to do this any of:
[...Array(7).keys()].map(i => i * i);
Array(7).fill().map((_,i) => i*i);
[...Array(7)].map((_,i) => i*i);
This will output:
[ 0, 1, 4, 9, 16, 25, 36 ]
I figured out a way using https://github.com/springfox/springfox and https://github.com/RobWin/swagger2markup
Used Swagger 2 to implement documentation.
On Debian (Wheezy, 7.8) with MySQL 5.5.40, I found SELECT * FROM mysql.user WHERE User='root'\G
showed the Event_priv
and 'Trigger_priv` fields were present but not set to Y.
Running mysql_upgrade
(with or without --force
) made no difference; I needed to do a manual:
update user set Event_priv = 'Y',Trigger_priv = 'Y' where user = 'root'
Then finally I could use:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION
…and then use it more precisely on an individual database/user account.
SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.
Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.
If you need to delete based on a list, you can use IN
:
DELETE FROM your_table
WHERE id IN (value1, value2, ...);
If you need to delete based on the result of a query, you can also use IN
:
DELETE FROM your_table
WHERE id IN (select aColumn from ...);
(Notice that the subquery must return only one column)
If you need to delete based on a range of values, either you use BETWEEN
or you use inequalities:
DELETE FROM your_table
WHERE id BETWEEN bottom_value AND top_value;
or
DELETE FROM your_table
WHERE id >= a_value AND id <= another_value;
String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
String[] value_split = rat_values.split("\\|");
for (String string : value_split) {
System.out.println(string);
}
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
You can programatically change it by setting the system property:
public class App {
public static void main(String[] args) {
System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
final org.slf4j.Logger log = LoggerFactory.getLogger(App.class);
log.trace("trace");
log.debug("debug");
log.info("info");
log.warn("warning");
log.error("error");
}
}
The log levels are ERROR > WARN > INFO > DEBUG > TRACE.
Please note that once the logger is created the log level can't be changed. If you need to dynamically change the logging level you might want to use log4j with SLF4J.
My user account did not have the permissions to alter the database and table, as suggested in this solution.
If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:
SET collation_connection = 'latin1_swedish_ci';
:%!xxd
Make vim into a hex editor.
:%!xxd -r
Revert.
Warning: If you don't edit with binary (-b), you might damage the file. – Josh Lee in the comments.
Even though it can be done via immutability-helper or similar I do not wan't to add external dependencies to my code unless I really have to. When I need to do it I use Object.assign
. Code:
this.setState({ abc : Object.assign({}, this.state.abc , {xyz: 'new value'})})
Can be used on HTML Event Attributes as well, example:
onChange={e => this.setState({ abc : Object.assign({}, this.state.abc, {xyz : 'new value'})})}
Copied from bobince answer, but made it support question marks in the query string, eg
http://www.google.com/search?q=test???+something&aq=f
Is it valid to have more than one question mark in a URL?
function removeUrlParameter(url, parameter) {
var urlParts = url.split('?');
if (urlParts.length >= 2) {
// Get first part, and remove from array
var urlBase = urlParts.shift();
// Join it back up
var queryString = urlParts.join('?');
var prefix = encodeURIComponent(parameter) + '=';
var parts = queryString.split(/[&;]/g);
// Reverse iteration as may be destructive
for (var i = parts.length; i-- > 0; ) {
// Idiom for string.startsWith
if (parts[i].lastIndexOf(prefix, 0) !== -1) {
parts.splice(i, 1);
}
}
url = urlBase + '?' + parts.join('&');
}
return url;
}
If trigger("chosen:updated");
not working, use .trigger("liszt:updated");
of @Nhan Tran it is working fine.
make sure the content inside your div ended with clear:both style
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
For those who can't rely on Chronometer, I made a utility class out of one of the suggestions:
public class TimerTextHelper implements Runnable {
private final Handler handler = new Handler();
private final TextView textView;
private volatile long startTime;
private volatile long elapsedTime;
public TimerTextHelper(TextView textView) {
this.textView = textView;
}
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
if (elapsedTime == -1) {
handler.postDelayed(this, 500);
}
}
public void start() {
this.startTime = System.currentTimeMillis();
this.elapsedTime = -1;
handler.post(this);
}
public void stop() {
this.elapsedTime = System.currentTimeMillis() - startTime;
handler.removeCallbacks(this);
}
public long getElapsedTime() {
return elapsedTime;
}
}
to use..just do:
TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
timerTextHelper.start();
.....
timerTextHelper.stop();
long elapsedTime = timerTextHelper.getElapsedTime();
If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.
static Form f0;
public OrdUpdate()
{
InitializeComponent();
f0=this;
}
// then later you can say
f0.Text="New text";
If you really don't care about which timestamp you'll get and your v_id
is always the same for a given m_i
you can do the following:
select m_id, v_id, max(timestamp) from table
group by m_id, v_id
order by timestamp desc
Now, if the v_id
changes for a given m_id
then you should do the following
select t1.* from table t1
left join table t2 on t1.m_id = t2.m_id and t1.timestamp < t2.timestamp
where t2.timestamp is null
order by t1.timestamp desc
def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
This is similar to, but more general than, @Jacob Relkin's solution:
This is ES2015:
const randomChoice = arr => {
const randIndex = Math.floor(Math.random() * arr.length);
return arr[randIndex];
};
The code works by selecting a random number between 0 and the length of the array, then returning the item at that index.
Check in Administration Tools\Services (or type services.msc in the console if you a service named SQL Server (SQLEXPRESS). If you do then it is installed.
From Visual Studio open Server Explorer (menu View\Server Explorer or CTRL + W, L). Right click Data Connections and choose Create New SQL Server Database. After that create tables and stuff...
If you want the Management Studio to manage the server you must download and install it from:
Below Command where project
is a folder which contains package.json
file
npm run --prefix project ${COMMAND}
is working as well. Useful in Docker based applications.
A regular for each will do:
foreach (var item in collection)
{
// do your stuff
}
When you use %
for setting heights or widths, always set the widths/heights of parent elements as well:
.table {_x000D_
display: table;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
border: 2px solid black;_x000D_
vertical-align: top;_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
height: 100%;_x000D_
border: 2px solid green;_x000D_
-moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
<div class="cell">_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
<p>Text_x000D_
</div>_x000D_
<div class="cell">_x000D_
<div class="container">Text</div>_x000D_
</div>_x000D_
</div>
_x000D_
This is because of the gradle version.
Go to: gradle/wrapper/gradle-wrapper.properties
.
Change a version of the course by this:
distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip
The console outputs:
Welcome to Gradle 6.3!
Here are the highlights of this release:
- Java 14 support
- Improved error messages for unexpected failures
For more details see https://docs.gradle.org/6.3/release-notes.html
Starting a Gradle Daemon (subsequent builds will be faster)
Just an alternative to the code by rkosegi,
BEGIN
.. Declare statements ..
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
.. set any flags etc eg. SET @flag = 0; ..
ROLLBACK;
END;
START TRANSACTION;
.. Query 1 ..
.. Query 2 ..
.. Query 3 ..
COMMIT;
.. eg. SET @flag = 1; ..
END
You can use the command split for this task. For example this command entered into the command prompt
split YourLogFile.txt -b 500m
creates several files with a size of 500 MByte each. This will take several minutes for a file of your size. You can rename the output files (by default called "xaa", "xab",... and so on) to *.txt to open it in the editor of your choice.
Make sure to check the help file for the command. You can also split the log file by number of lines or change the name of your output files.
(tested on Windows 7 64 bit)
@Test
public void testSortedMaps() {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "Josh");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "Anna");
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", "Bernie");
List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);
mapList.add(map3);
Collections.sort(mapList, new Comparator<Map<String, String>>() {
public int compare(final Map<String, String> o1, final Map<String, String> o2) {
return o1.get("name").compareTo(o2.get("name"));
}
});
Assert.assertEquals("Anna", mapList.get(0).get("name"));
Assert.assertEquals("Bernie", mapList.get(1).get("name"));
Assert.assertEquals("Josh", mapList.get(2).get("name"));
}
A generic version of @Kevan's answer above, using Reactive Extensions.
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, IScheduler scheduler)
{
return task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
With optional Scheduler:
public static Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout, Scheduler scheduler = null)
{
return scheduler is null
? task.ToObservable().Timeout(timeout).ToTask()
: task.ToObservable().Timeout(timeout, scheduler).ToTask();
}
BTW: When a Timeout happens, a timeout exception will be thrown
I was also stuck on the same kind of problem and I followed the simple steps below.
Just get the exact url of the file to which you want to copy, for example:
http://www.test.com/test.txt (file to copy)
Then pass the exact absolute folder path with filename where you do want to write that file.
If you are on a Windows machine then
d:/xampp/htdocs/upload/test.txt
If you are on a Linux machine then
/var/www/html/upload/test.txt
You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT']
.
The timezone name is the only reliable way to specify the timezone.
You can find a list of timezone names here: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones Note that this list contains a lot of alias names, such as US/Eastern for the timezone that is properly called America/New_York.
If you programatically want to create this list from the zoneinfo database you can compile it from the zone.tab file in the zoneinfo database. I don't think pytz has an API to get them, and I also don't think it would be very useful.
You can try this:
static class Student {
private int age;
private int number;
public Student(int age, int number) {
this.age = age;
this.number = number;
}
public Student() {
}
}
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
Student student1=new Student();
// Class g=student1.getClass();
Field[]fields=student1.getClass().getDeclaredFields();
Field age=student1.getClass().getDeclaredField("age");
age.setAccessible(true);
age.setInt(student1,13);
Field number=student1.getClass().getDeclaredField("number");
number.setAccessible(true);
number.setInt(student1,936);
for (Field f:fields
) {
f.setAccessible(true);
System.out.println(f.getName()+" "+f.getInt(student1));
}
}
}
I had a similar problem. VS 2015 Community (MSBuild 14) building a c++ app, wanted to use VS 2010 (v100) tools. It all came down giving msbuild an invalid configuration option. Strange.
So, recheck all those options and parameters.
I have finally found a working code - try this:
document.getElementById("button").style.background='#000000';
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.
Why not do string suppression with triple quotes:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
set title color
btnGere.setTitleColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
<span>
is an inline element so you cant make spacing on them without making it block level.
Try this
Horizontal
span{
margin-right: 10px;
float: left;
}
Vertical
span{
margin-bottom: 10px;
}
Compatible with all browsers.
AF_INET = Address Format, Internet = IP Addresses
PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP
AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).
For the most part sticking with AF_INET for socket programming over a network is the safest option.
Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.
PF_INET refers to anything in the protocol, usually sockets/ports.
For adding borders try this, for example:
Range("C11").Borders(xlEdgeRight).LineStyle = xlContinuous
Range("A15:D15").Borders(xlEdgeBottom).LineStyle = xlContinuous
Hope that syntax is correct because I've done this in C#.
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
Put these lines in the beginning of web.xml:
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/main/resources/log4j.xml</param-value>
</context-param>
The other answers were incorrect, at least in my case. request.path
does not provide the full url, only the relative url, e.g. /paper/53
. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path
.
OS X keychain equivalent is Credential Manager in windows.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
You can catch it like any other exception:
try {
foo();
}
catch (const std::bad_alloc&) {
return -1;
}
Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.
In general you cannot, and should not try, to respond to this error. bad_alloc
indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.
Worse, modern operating systems often over-allocate: on such systems, malloc
and new
can return a valid pointer even if there is not enough free memory left – std::bad_alloc
will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).
The only thing you could do when catching std::bad_alloc
is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).
In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:
It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1
OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:
lru_cache<widget> widget_cache;
double perform_operation(int widget_id) {
std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
if (not maybe_widget) {
maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
}
return maybe_widget->frobnicate();
}
…
for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
try {
return perform_operation(widget_id);
} catch (std::bad_alloc const&) {
if (widget_cache.empty()) throw; // memory error elsewhere.
widget_cache.remove_oldest();
}
}
// Handle too many failed attempts here.
But even here, using std::set_new_handler
instead of handling std::bad_alloc
provides the same benefit and would be much simpler.
1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.
new
in c++?The usual notion is that if new
operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc
.
However, something more happens even before a bad_alloc
exception is thrown:
C++03 Section 3.7.4.1.3: says
An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.
Consider the following code sample:
#include <iostream>
#include <cstdlib>
// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
std::cerr << "Unable to satisfy request for memory\n";
std::abort();
}
int main()
{
//set the new_handler
std::set_new_handler(outOfMemHandler);
//Request huge memory size, that will cause ::operator new to fail
int *pBigDataArray = new int[100000000L];
return 0;
}
In the above example, operator new
(most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler()
will be called, and the program will abort after issuing an error message.
As seen here the default behavior of new
operator when unable to fulfill a memory request, is to call the new-handler
function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort()
, outOfMemHandler()
would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.
new_handler
and set_new_handler
?new_handler
is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler
is a function that takes and returns a new_handler
.
Something like:
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
set_new_handler's parameter is a pointer to the function operator new
should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.
Given the behavior of new
a well designed user program should handle out of memory conditions by providing a proper new_handler
which does one of the following:
Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.
Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler
). The next time operator new calls the new-handler function, it will get the one most recently installed.
(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)
Uninstall the new-handler: This is done by passing a null pointer to set_new_handler
. With no new-handler installed, operator new
will throw an exception ((convertible to) std::bad_alloc
) when memory allocation is unsuccessful.
Throw an exception convertible to std::bad_alloc
. Such exceptions are not be caught by operator new
, but will propagate to the site originating the request for memory.
Not return: By calling abort
or exit
.
Selector > child:
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
<tr class="text-center-row">_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
<tr class="text-center-row">_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
</table>
_x000D_
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
My solution. It may be slower on performance:
a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()
bar.baz foo.aa foo.bars foo.fighters foo.fox foo.manchu nas.foo
0 5.0 1.0 0 0 2 NA NA
1 5.0 2.1 0 1 4 0 0
2 6.0 NaN 0 NaN 1 0 1
5 6.8 6.8 1 0 5 0 0
I wrote extension method
public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
var s = new StringBuilder();
for (var i = 0; i < matrix.GetLength(0); i++)
{
for (var j = 0; j < matrix.GetLength(1); j++)
{
s.Append(matrix[i, j]).Append(delimiter);
}
s.AppendLine();
}
return s.ToString();
}
To use just call the method
results.ToMatrixString();
am using this simple one
´´´´ class Connect {
public $url;
public $path;
public $username;
public $password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
//PROPFIND request that lists all requested properties.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
$response = curl_exec($ch);
curl_close($ch);
from __future__ import division
somelist = [1,12,2,53,23,6,17]
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)
If you want to manually find the minimum as a function:
somelist = [1,12,2,53,23,6,17]
def my_min_function(somelist):
min_value = None
for value in somelist:
if not min_value:
min_value = value
elif value < min_value:
min_value = value
return min_value
Python 3.4 introduced the statistics
package, which provides mean
and additional stats:
from statistics import mean, median
somelist = [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
Inline items cannot have a width. You have to use display: block
or display:inline-block
, but the latter is not supported everywhere.
If you don't want to use a submission service like Litmus (Litmus is the best, BTW) then you're just going to have to run Outlook 2007 to test your email.
It sounds like you want something a little more automatic (though I'm not sure why), but fortunately Outlook is easy to automate using Visual Basic for Applications (VBA).
You can write a VBA tool that runs from the command line to generate an email, load the email up in Outlook, and even capture a screenshot if you wish. (Presumably this is what the Litmus team does on the backend.)
(BTW, do not attempt to use MS Word to test mail; the renderer is similar but subtle differences in page layout can affect the rendering of your email.)
If you are running Python 3.5, run the following terminal command:
sudo pip3 install -U nltk
Any other pip commands in terminal would be similar:
pip3 install --upgrade pip
sudo pip3 install -U numpy ::
You can use a data-bound control like the Repeater
or ListView
, re-bind it to a list of control properties as needed, and let it generate the controls dynamically.
As an alternative, you can use Response.Redirect(".")
to re-load the same page.
How about access
?
#include <io.h>
if (_access(filename, 0) == -1)
{
// File does not exist
}
in response to Dan's comment above:
I am using this method to implement the same thing, but for some reason I am getting an exception on the ReadObject method: "Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''." Any ideas why? – Dan Appleyard Apr 6 '10 at 17:57
I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...
You are on Symfony, think "Dependency Injection" ^^
In all my SF project, I do in parameters.yml:
web_dir: "%kernel.root_dir%/../web"
So I can safely use this parameter within controller:
$this->getParameter('web_dir');
I have to vote -1 for the libraries hosted on Google. They are collecting data, google analytics style, with their wrappers around these libraries. At a minimum, I don't want a client browser doing more than I'm asking it to do, much less anything else on the page. At worse, this is Google's "new version" of not being evil -- using unobtrusive javascript to gather more usage data.
Note: if they've changed this practice, super. But the last time I considered using their hosted libraries, I monitored the outbound http traffic on my site, and the periodic calls out to google servers were not something I expected to see.
A lot of great answers here. Below is a sample of the stored procedure that I wrote to accomplish this task for a Web App that I am developing:
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Create Temporary Table
SELECT * INTO #tempTable FROM <YourTable> WHERE Id = Id
--To trigger the auto increment
UPDATE #tempTable SET Id = NULL
--Update new data row in #tempTable here!
--Insert duplicate row with modified data back into your table
INSERT INTO <YourTable> SELECT * FROM #tempTable
-- Drop Temporary Table
DROP TABLE #tempTable
I designed a simple approach using single quotes when forming the strings and then calling a function that replaces single quotes with double quotes.
Of course this approach works as long as you don't need to include actual single quotes inside your string.
Function Q(s)
Q = Replace(s,"'","""")
End Function
...
user="myself"
code ="70234"
level ="C"
r="{'User':'" & user & "','Code':'" & code & "','Level':'" & level & "'}"
r = Q(r)
response.write r
...
Hope this helps.
My case: I use Windows and I have more than 1 user account. I was receiving the same error and the fix was to start the git bash with administrator rights.
create_function
did not work for me inside a class. I had to use call_user_func
.
<?php
class Dispatcher {
//Added explicit callback declaration.
var $callback;
public function Dispatcher( $callback ){
$this->callback = $callback;
}
public function asynchronous_method(){
//do asynch stuff, like fwrite...then, fire callback.
if ( isset( $this->callback ) ) {
if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
}
}
}
Then, to use:
<?php
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();
function do_callback( $data ){
print 'Data is: ' . $data . "\n";
}
?>
[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.
I tried every possible solution on this web site and nothing worked for me. I ended up doing in the design mode. Right click on the table name and then click design. Then I changed the name and saved here. Worked simply.
Try:
subprocess.call(['sudo', 'apach2ctl', 'restart'])
The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.
If you don't define them, then it grabs sys.stdout, etc...
The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.
id is protected
, just add a public method in your /models/User.php
public function getId()
{
return $this->id;
}
so you can call it
$id = Auth::user()->getId();
remember allways to test if user is logged...
if (Auth::check())
{
$id = Auth::user()->getId();
}
You derive B
from A<B>
, so the first thing the compiler does, once it sees the definition of class B
is to try to instantiate A<B>
. To do this it needs to known B::mytype
for the parameter of action
. But since the compiler is just in the process of figuring out the actual definition of B
, it doesn't know this type yet and you get an error.
One way around this is would be to declare the parameter type as another template parameter, instead of inside the derived class:
template<typename Subclass, typename Param>
class A {
public:
void action(Param var) {
(static_cast<Subclass*>(this))->do_action(var);
}
};
class B : public A<B, int> { ... };
I'm answering because the previous answers have stopped working with the latest version of jQuery. I don't know when it stopped working, but the documentation says that .prop() has been the preferred method to get/set properties since jQuery 1.6.
This is how I got it to work (with jQuery 3.2.1):
$('select option:nth-child(1)').prop("selected", true);
I am using knockoutjs and the change bindings weren't firing with the above code, so I added .change() to the end.
Here's what I needed for my solution:
$('select option:nth-child(1)').prop("selected", true).change();
See .prop() notes in the documentation here: http://api.jquery.com/prop/
If you are using React, the library material-ui.com can help you with:
<FormControl>
<InputLabel htmlFor="textContract">{`textContract`}</InputLabel>
<Input
id="textContract"
multiline
rows="30"
type="text"
value={props.textContract}
onChange={() => {}}
/>
</FormControl>
An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:
It also exploits that JavaScript is weakly typed. Rather type inference.
Here's how (an excerpt from Google Chrome's console):
var myDict = {};
myDict.one = 1;
1
myDict.two = 2;
2
if (myDict.hasOwnProperty('three'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
Key does not exist! VM361:8
if (myDict.hasOwnProperty('two'))
{
console.log(myDict.two);
}
else
{
console.log('Key does not exist!');
}
2 VM362:4
Object.keys(myDict);
["one", "two"]
delete(myDict.two);
true
myDict.hasOwnProperty('two');
false
myDict.two
undefined
myDict.one
1
You could use bind
method
for (var i = 1, j = 1; i <= 3; i++, j++) {
setTimeout(function() {
alert(this);
}.bind(i), j * 100);
}
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>
, e.g. an ArrayList<String>
:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use
\d+
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});
You must perform a terminal operation on the Stream in order for any of the filters to be applied. Therefore you can't know if it will be empty until you consume it.
Best you can do is terminate the Stream with a findAny()
terminal operation, which will stop when it finds any element, but if there are none, it will have to iterate over all the input list to find that out.
This would only help you if the input list has many elements, and one of the first few passes the filters, since only a small subset of the list would have to be consumed before you know the Stream is not empty.
Of course you'll still have to create a new Stream in order to produce the output list.
Please select the same in the outer select. You can't access the alias name in the same query.
SELECT *, (CASE
WHEN articleNumber < 2 THEN 'Ama'
WHEN articleNumber < 5 THEN 'SemiAma'
WHEN articleNumber < 7 THEN 'Good'
WHEN articleNumber < 9 THEN 'Better'
WHEN articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END) AS ranking
FROM(
SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
)x
Introducer for the return type of a local lambda expression:
std::vector<MyType> seq;
// fill with instances...
std::sort(seq.begin(), seq.end(),
[] (const MyType& a, const MyType& b) -> bool {
return a.Content < b.Content;
});
introducing a trailing return type of a function in combination of the re-invented auto
:
struct MyType {
// declares a member function returning std::string
auto foo(int) -> std::string;
};
You can do it in two steps:
Checkout an empty SVN repository with meta information only:
$ cd /tmp
$ svn co --depth empty http://svn.your.company.ca/training/trunk/sql
Run svn up
to update specified file:
$ svn up http://svn.your.company.ca/training/trunk/sql/showSID.sql
hopefully this will save images form your webcam
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture cap(0);
Mat save_img;
cap >> save_img;
char Esc = 0;
while (Esc != 27 && cap.isOpened()) {
bool Frame = cap.read(save_img);
if (!Frame || save_img.empty()) {
cout << "error: frame not read from webcam\n";
break;
}
namedWindow("save_img", CV_WINDOW_NORMAL);
imshow("imgOriginal", save_img);
Esc = waitKey(1);
}
imwrite("test.jpg",save_img);
}
Simply use the on click event for tab shown.
$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});
This is more of a continuation of jglouie's response.
If you are using openssl to convert the PKCS#12 certificate to public/private PEM keys, there is no need to rename the file. Assuming the file is called cert.pfx, the following three commands will create a public pem key and an encrypted private pem key:
openssl pkcs12 -in cert.pfx -out cert.pem -nodes -nokeys
openssl pkcs12 -in cert.pfx -out cert_key.pem -nodes -nocerts
openssl rsa -in cert_key.pem -out cert_key.pem -des3
The first two commands may prompt for an import password. This will be a password that was provided with the PKCS#12 file.
The third command will let you specify the encryption passphrase for the certificate. This is what you will enter when using the certificate.
Path2D is supported by all major browsers now
You can now use ctx.drawImage
to draw HTMLImageElements that have a .svg source in some but not all browsers. Chrome, IE11, and Safari work, Firefox works with some bugs (but nightly has fixed them).
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";
Live example here. You should see a green square in the canvas. The second green square on the page is the same <svg>
element inserted into the DOM for reference.
You can also use the new Path2D objects to draw SVG (string) paths. In other words, you can write:
var path = new Path2D('M 100,100 h 50 v 50 h 50');
ctx.stroke(path);
There's nothing native that allows you to natively use SVG paths in canvas. You must convert yourself or use a library to do it for you.
I'd suggest looking in to canvg:
For Android 8.0, there is a new API to handle Hotspots. As far as I know, the old way using reflection doesn't work anymore. Please refer to:
void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback,
Handler handler)
Request a local only hotspot that an application can use to communicate between co-located devices connected to the created WiFi hotspot. The network created by this method will not have Internet access.
Stack Overflow
How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)
onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.
For C++, you could do:
export CXXFLAGS=-m32
This works with cmake.
Your problem may be that you are dealing with DATETIME data, not just dates. If a row has a mydate that is '2008-11-25 09:30 AM', then your WHERE mydate<='2008-11-25'; is not going to return that row. '2008-11-25' has an implied time of 00:00 (midnight), so even though the date part is the same, they are not equal, and mydate is larger.
If you use < '2008-11-26' instead of <= '2008-11-25', that would work. The Datediff method works because it compares just the date portion, and ignores the times.