According to the API the constructor which would accept year, month, and so on is deprecated. Instead you should use the Constructor which accepts a long. You could use a Calendar implementation to construct the date you want and access the time-representation as a long, for example with the getTimeInMillis method.
if you don't want .pyc anymore you can use this single line in a terminal:
export PYTHONDONTWRITEBYTECODE=1
if you change your mind:
unset PYTHONDONTWRITEBYTECODE
In spring 2.x
. Options have changed slightly. So the above answers are almost correct but not entirely . In your application.properties
file , add the following-
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
I guess , you means $_SERVER['PHP_SELF']
. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.
The if(isset($_POST['submit']))
condition should be above all the HTML output, and should contain a header()
function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION
or $_COOKIE
.
And please. Stop using $_REQUEST
. It too poses a security threat.
And why not just count them ?
import sys
a = sys.argv
if len(a) = 1 :
# No arguments were given, the program name count as one
elif len(a) = 4 :
# Three arguments were given
else :
# another amount of arguments was given
I had the same issue, but I have resolved it the next:
1) Install jdk1.8...
2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.
3) Click Ok.
What matters isn't the attribute but the property, and its value is a boolean.
You can set it using
document.getElementById("edName").required = true;
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
Try to add type of configuration in dependency line. For example:
implementation project(path: ':some_module', **configuration: 'default'**)`
This problema has many sources, and thus many answers. I've experienced each one of them.
1) If you have a crash of some sort, removing the /usr/local/var/postgres/postmaster.pid file is probably required as postgres may not have handled it properly. But ensure that no process is running.
2) Craig Ringer has pointed out in other posts that Apple's bundling of postgreSQL leads to pg gem installation issues Setting the PATH environment variable is a solution.
3) Another solution, is to uninstall and reinstall the gem. A brew update may be necessary as well.
If you stumble upon this post, if you can pinpoint one of the sources, you'll save time...
If you are trying to reference an android style, you need to put "android:" in there
android:theme="@android:style/Theme.Black"
If that doesn't solve it, you may need to edit your question with the full manifest file, so we can see more details
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
It's hard to say without knowing the whole context of the problem, but I would not override __iter__
.
I would implement __what_goes_here__
on the class.
as_dict(self:
d = {...whatever you need...}
return d
Just use a prototype cell as your section header and / or footer.
tableView:viewForHeaderInSection:
method or the tableView:viewForFooterInSection:
method[tableView dequeueReusableCellWithIdentifier:]
to get the headertableView:heightForHeaderInSection:
method.-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
static NSString *CellIdentifier = @"SectionHeader";
UITableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (headerView == nil){
[NSException raise:@"headerView == nil.." format:@"No cells with matching CellIdentifier loaded from your storyboard"];
}
return headerView;
}
Edit: How to change the header title (commented question):
tableView:viewForHeaderInSection:
method get the label by calling: UILabel *label = (UILabel *)[headerView viewWithTag:123];
[label setText:@"New Title"];
There are couple of ways you can search as "LIKE" operator of SQL in C#. If you just want to know whether the pattern exists in the string variable, you can use
string value = "samplevalue";
value.Contains("eva"); // like '%eva%'
value.StartsWith("eva"); // like 'eva%'
value.EndsWith("eva"); // like '%eva'
if you want to search the pattern from a list of string, you should use LINQ to Object Features.
List<string> valuee = new List<string> { "samplevalue1", "samplevalue2", "samplevalue3" };
List<string> contains = (List<string>) (from val in valuee
where val.Contains("pattern")
select val); // like '%pattern%'
List<string> starts = (List<string>) (from val in valuee
where val.StartsWith("pattern")
select val);// like 'pattern%'
List<string> ends = (List<string>) (from val in valuee
where val.EndsWith ("pattern")
select val);// like '%pattern'
You can also draw the string dynamically inside the RowPostPaint
event:
private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
This selector should work but will be more efficient if you replace it with your suited markup:
//*[contains(@class, 'Test')]
Or, since we know the sought element is a div
:
//div[contains(@class, 'Test')]
But since this will also match cases like class="Testvalue"
or class="newTest"
, @Tomalak's version provided in the comments is better:
//div[contains(concat(' ', @class, ' '), ' Test ')]
If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):
//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]
Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.
Append the below Script in Console:
window.addEventListener("beforeunload", function(event) {
console.log("The page is redirecting")
debugger;
});
You need this code wrap in tags and put on the end of page. Or create JS file (for example test.js), write this code on it and put on the end of page this tag
If you have included jQuery, there may be a conflict. Try using jQuery
instead of $
.
Apart from the difference that Scripting language is Interpreted and Programming language is Compiled, there is another difference as below, which I guess has been missed..
A scripting language is a programming language that is used to manipulate, customize, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control.
Whereas a Programming Language generally is used to code the system from Scratch.
src ECMA
textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;
The solution above does't work in my case. I'm doing like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ...
CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap];
return size.height + 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// ...
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:@"Georgia-Bold" size:18.0];
}
// ...
UILabel *textLabel = [cell textLabel];
CGSize size = [text sizeWithFont:[UIFont fontWithName:@"Georgia-Bold" size:18.0]
constrainedToSize:CGSizeMake(240.0, 480.0)
lineBreakMode:UILineBreakModeWordWrap];
cell.textLabel.frame = CGRectMake(0, 0, size.width + 20, size.height + 20);
//...
}
In C programming, static
is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable's lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:
#include<stdio.h>
int counterFunction()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("First Counter Output = %d\n", counterFunction());
printf("Second Counter Output = %d ", counterFunction());
return 0;
}
Above program will give us this Output:
First Counter Output = 1
Second Counter Output = 1
Because as soon as we call the function it will initialize the count = 0
. And while we execute the counterFunction
it will destroy the count variable.
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccess
but this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error
. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css
,js
and php
files even more like images
or whatever you have.
I use Blue Ocean plugin and did not like each environment entry getting its own block. I want one block with all the lines.
Prints poorly:
sh 'echo `env`'
Prints poorly:
sh 'env > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
println i
}
Prints well:
sh 'env > env.txt'
sh 'cat env.txt'
Prints well: (as mentioned by @mjfroehlich)
echo sh(script: 'env', returnStdout: true)
As stated in a comment at
with System.Net.Mail, use port 25 instead of 465:
You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.
almost a decade passed but the issue still valid with Asp.Net Core 2.2 as well.
I managed it by adding data-val-number
to the input field the use localization on the message:
<input asp-for="Age" data-val-number="@_localize["Please enter a valid number."]"/>
Adding "-EA Stop" solved this for me.
Since Facebook's Android SDK v4.0 (see changelog) you need to execute the following:
LoginManager.getInstance().logOut();
As stated in seong's comment:
Also see http://golang.org/doc/effective_go.html#maps. The important part is really the "reference to underlying data structure". This also applies to slices.
However, none of the solutions here seem to offer a solution for a proper deep copy that also covers slices.
I've slightly altered Francesco Casula's answer to accommodate for both maps and slices.
This should cover both copying your map itself, as well as copying any child maps or slices. Both of which are affected by the same "underlying data structure" issue. It also includes a utility function for performing the same type of Deep Copy on a slice directly.
Keep in mind that the slices in the resulting map will be of type []interface{}
, so when using them, you will need to use type assertion to retrieve the value in the expected type.
Example Usage
copy := CopyableMap(originalMap).DeepCopy()
Source File (util.go
)
package utils
type CopyableMap map[string]interface{}
type CopyableSlice []interface{}
// DeepCopy will create a deep copy of this map. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (m CopyableMap) DeepCopy() map[string]interface{} {
result := map[string]interface{}{}
for k,v := range m {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result[k] = CopyableMap(mapvalue).DeepCopy()
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result[k] = CopyableSlice(slicevalue).DeepCopy()
continue
}
result[k] = v
}
return result
}
// DeepCopy will create a deep copy of this slice. The depth of this
// copy is all inclusive. Both maps and slices will be considered when
// making the copy.
func (s CopyableSlice) DeepCopy() []interface{} {
result := []interface{}{}
for _,v := range s {
// Handle maps
mapvalue,isMap := v.(map[string]interface{})
if isMap {
result = append(result, CopyableMap(mapvalue).DeepCopy())
continue
}
// Handle slices
slicevalue,isSlice := v.([]interface{})
if isSlice {
result = append(result, CopyableSlice(slicevalue).DeepCopy())
continue
}
result = append(result, v)
}
return result
}
Test File (util_tests.go
)
package utils
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyMap(t *testing.T) {
m1 := map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}
m2 := CopyableMap(m1).DeepCopy()
m1["a"] = "zzz"
delete(m1, "b")
m1["c"].([]interface{})[1] = "x"
m1["c"].([]interface{})[2].(map[string]interface{})["f"] = "h"
require.Equal(t, map[string]interface{}{
"a": "zzz",
"c": []interface{} {
"d", "x", map[string]interface{} {
"f": "h",
},
},
}, m1)
require.Equal(t, map[string]interface{}{
"a": "bbb",
"b": map[string]interface{}{
"c": 123,
},
"c": []interface{} {
"d", "e", map[string]interface{} {
"f": "g",
},
},
}, m2)
}
format = '%Y-%m-%d %H:%M %p'
The format is using %H
instead of %I
. Since %H
is the "24-hour" format, it's likely just discarding the %p
information. It works just fine if you change the %H
to %I
.
// GET JSON Response
public WeatherResponseModel GET(string url) {
WeatherResponseModel model = new WeatherResponseModel();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try {
WebResponse response = request.GetResponse();
using(Stream responseStream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
model = JsonConvert.DeserializeObject < WeatherResponseModel > (reader.ReadToEnd());
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// Log errorText
}
throw;
}
return model;
}
// POST a JSON string
void POST(string url, string jsonContent) {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[]byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = @ "application/json";
using(Stream dataStream = request.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try {
using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
// Got response
length = response.ContentLength;
}
} catch (WebException ex) {
WebResponse errorResponse = ex.Response;
using(Stream responseStream = errorResponse.GetResponseStream()) {
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// Log errorText
}
throw;
}
}
Note: To serialize and desirialze JSON, I used the Newtonsoft.Json NuGet package.
Did you try to change your xsd like this?
<!-- create-logical-system -->
<xs:element name="methodCall">
<xs:complexType>
...
</xs:complexType>
</xs:element>
View Remote URLs
> git remote -v
heroku https://git.heroku.com/###########.git (fetch) < your Heroku Remote URL
heroku https://git.heroku.com/############.git (push)
origin https://github.com/#######/#####.git (fetch) < if you use GitHub then this is your GitHub remote URL
origin https://github.com/#######/#####.git (push)
Remove Heroku remote URL
> git remote rm heroku
Set new Heroku URL
> heroku git:remote -a ############
And you are done.
Alternative and much easier way is to use shapes instead of 9-patches. It is already explained here: https://stackoverflow.com/a/24725831/512011
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
PPI and DPI make absolutely no difference to how a document will print off a browser. the printer takes no information on screen dot pitch or the DPI of the images etc. if you are printing images they would print at a size similar in proportion to how they are displayed on screen. the print processor of the browser would increase the DPI of the images from something rather low like 72dpi to whatever DPI the rest of the document is. say the image displays as half a page wide, then its about 4" wide physically. the pixel width of the image would be approx 300px to display correctly in the browser. by the time it prints at a nominal 300DPI, the processor has added pixels and the image will grow to around 1200px which at 300 DPI is 4".
when it comes to vector or non pixel based elements like text, the printer chooses its own DPI from the driver which doesnt relate to screen dot pitch or browser width etc. if the browser is 3000px wide, the print processor will wrap text as appropriate.
heres what makes it hard about creating print displays: each browser and printer will interpret text sizes (pt, em, px) and spacing in its own way. depending on what printer, browser and maybe even OS you use, you will get a different amount of lines and characters per page. so even if you test on your computer using your browser and printer and figure out that you can display the text in a box at 640x900px and its perfect on print, the next guy who tries to print will possibly get it printing differently. there really is no way to force each printer and browser to get it identical each time.
forget pixels and moreso forget DPI, the only thing you could use pixels for is setting a table width that simulates the width of a printable area on your printer. in that case i found that 640px wide is close.
ggplot 3.3.0
fixes this by providing guide_axis(angle = 90)
(as guide
argument to scale_..
or as x
argument to guides
):
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(angle = 90)) +
# ... or, equivalently:
# guides(x = guide_axis(angle = 90)) +
NULL
From the documentation of the angle
argument:
Compared to setting the angle in theme() / element_text(), this also uses some heuristics to automatically pick the hjust and vjust that you probably want.
Alternatively, it also provides guide_axis(n.dodge = 2)
(as guide
argument to scale_..
or as x
argument to guides
) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
NULL
If you are certain that you only need column A, then you can use an End function in VBA to get that result.
If all the cells A1:A100 are filled, then to select the next empty cell use:
Range("A1").End(xlDown).Offset(1, 0).Select
Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.
If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select
The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.
You can use ng-value-true to tell angular that your ng-model is a string.
I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)
ng-true-value="'1'"
This is the best method I have come up with so far to incorporate extra GET methods while supporting the normal REST methods as well. Add the following routes to your WebApiConfig:
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new {action = "Post"}, new {httpMethod = new HttpMethodConstraint(HttpMethod.Post)});
I verified this solution with the test class below. I was able to successfully hit each method in my controller below:
public class TestController : ApiController
{
public string Get()
{
return string.Empty;
}
public string Get(int id)
{
return string.Empty;
}
public string GetAll()
{
return string.Empty;
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
}
I verified that it supports the following requests:
GET /Test
GET /Test/1
GET /Test/GetAll
POST /Test
PUT /Test/1
DELETE /Test/1
Note That if your extra GET actions do not begin with 'Get' you may want to add an HttpGet attribute to the method.
If you are using the terminal ( i am using ubuntu ) , then just use the combination of CTRL+l from keyboard to clear the python script, even it clears the terminal script...
For targeting IE only in my stylesheets, I use this Sass Mixin :
@mixin ie-only {
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
@content;
}
}
I don't believe there's a convenient way to retrieve an arbitrary value from a generator. The generator will provide a next() method to traverse itself, but the full sequence is not produced immediately to save memory. That's the functional difference between a generator and a list.
The Reason behind the error message is that SQL couldn't show new features in your old SQL server version.
Please upgrade your client SQL version to same as your server Sql version
I answered something like this in another question already, but will change it just a little for this one.
Unfortunately, there is no getImageResource()
or getDrawableId()
. But, I created a simple workaround by using the ImageView tags.
In onCreate():
imageView0 = (ImageView) findViewById(R.id.imageView0);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView0.setTag(R.drawable.apple);
imageView1.setTag(R.drawable.banana);
imageView2.setTag(R.drawable.cereal);
Then, if you like, you can create a simple function to get the drawable id:
private int getDrawableId(ImageView iv) {
return (Integer) iv.getTag();
}
Too easy.
The brute force method of generating every single possible board and scoring it based on the boards it later produces further down the tree doesn't require much memory, especially once you recognize that 90 degree board rotations are redundant, as are flips about the vertical, horizontal, and diagonal axis.
Once you get to that point, there's something like less than 1k of data in a tree graph to describe the outcome, and thus the best move for the computer.
-Adam
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
I use android studio in Windows 7 and i have AVG for antivirus. The first time you launch adb, AVG prompts you to add avg.exe in antivirus vault. If you accept, then you android studio dont have access to run adb.exe. So open avg >> options >> Virus Vault >> Restore (select the adb file)
Try on this..
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
First make sure all nuget packages are at the same version across all projects in your solution. e.g. you dont want one project to reference NLog 4.0.0.0 and another project to reference NLog 4.1.0.0. Then try reinstalling nuget packages with
Update-Package -reinstall
I had 3 3rd party assemblies that were referenced by my assembly A and only 2 were included in References by my assembly B which also referenced A.
The missing reference to the 3rd party assembly was added by the update package command, and the error went away.
In C#, you'd do something like this:
MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");
Your regex should be something like
[0-9\-\(\)\s]+
.
It matches numbers, dashes, parentheses and space.
If you need something more strict, matching just your example, try this:
([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})
Use this document to transfer Sticky Notes data file StickyNotes.snt to the new format
http://www.winhelponline.com/blog/recover-backup-sticky-notes-data-file-windows-10/
Restore:
%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState
Backup
just backup following file.
%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
This is a slight tweak on nvirth's example
internal class DummyClass
{
private static void Dummy()
{
Noop(typeof(AbcDll.AnyClass));
}
private static void Noop(Type _) { }
}
I posted some information on the Infragistics forums for designer widgets that may help you for this. You can view the post with the following link:
http://forums.infragistics.com/forums/p/52530/320151.aspx#320151
Note that the registry keys would be different for the different product and you may need to install on a 32 bit machine to see what keys you need.
As Mike Nakis said, echo off
only prevents the printing of commands, not results. To hide the result of a command add >nul
to the end of the line, and to hide errors add 2>nul
. For example:
Del /Q *.tmp >nul 2>nul
Like Krister Andersson said, the reason you get an error is your variable is expanding with spaces:
set INSTALL_PATH=C:\My App\Installer
if exist %INSTALL_PATH% (
Becomes:
if exist C:\My App\Installer (
Which means:
If "C:\My" exists, run "App\Installer" with "(" as the command line argument.
You see the error because you have no folder named "App". Put quotes around the path to prevent this splitting.
Something is clearly corrupt in your Laravel setup and it is very hard to track without more info about your environment. Usually these 2 commands help you resolve such issues
php artisan clear-compiled
composer dump-autoload
If nothing else helps then I recommend you to install fresh Laravel 5 app and copy your application logic over, it should take around 15 min or so.
Wrote this because I had requirements for up to a specific length (9). Pads the left with the @pattern ONLY when the input needs padding. Should always return length defined in @pattern.
declare @charInput as char(50) = 'input'
--always handle NULL :)
set @charInput = isnull(@charInput,'')
declare @actualLength as int = len(@charInput)
declare @pattern as char(50) = '123456789'
declare @prefLength as int = len(@pattern)
if @prefLength > @actualLength
select Left(Left(@pattern, @prefLength-@actualLength) + @charInput, @prefLength)
else
select @charInput
Returns 1234input
I resolved a similar issue by wrapping the query in another query...
Initial query was working find giving individual columns of output, with some of the columns coming from sub queries with Max or Sum function, and other with "distinct" or case substitutions and such.
I encountered the collation error after attempting to create a single field of output with...
select
rtrim(field1)+','+rtrim(field2)+','+...
The query would execute as I wrote it, but the error would occur after saving the sql and reloading it.
Wound up fixing it with something like...
select z.field1+','+z.field2+','+... as OUTPUT_REC
from (select rtrim(field1), rtrim(field2), ... ) z
Some fields are "max" of a subquery, with a case substitution if null and others are date fields, and some are left joins (might be NULL)...in other words, mixed field types. I believe this is the cause of the issue being caused by OS collation and Database collation being slightly different, but by converting all to trimmed strings before the final select, it sorts it out, all in the SQL.
Try run this command it will create a *_limits.conf
file under /etc/security/limits.d
echo "* soft nofile 102400" > /etc/security/limits.d/*_limits.conf && echo "* hard nofile 102400" >> /etc/security/limits.d/*_limits.conf
Just exit from terminal and login again and verify by ulimit -n
it will set for * users
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
Whatever is specified in the command
in docker-compose.yml should get appended to the entrypoint
defined in the Dockerfile, provided entrypoint
is defined in exec form in the Dockerfile.
If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.
[Windows] As already said, it looks like .bat -file tries to find java.exe from %JAVA_HOME%/bin/java.exe
so it doesn't find it since bin
is repeated twice in path.
Remov that extra /bin
from gradle.bat.
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).
If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.
I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation.
If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:
I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.
try this
function global_func(...args){
for(let i of args){
console.log(i)
}
}
global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)
//task_name
//action
//(2) [{...},
// {...}]
// {
// x:"x"
// }
//(2) [
// "x1",
// "x2"
// ]
//1
//null
//undefined
//false
//true
//func
As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.
var Mongoose = require('mongoose').Mongoose;
var instance1 = new Mongoose();
instance1.connect('foo');
var instance2 = new Mongoose();
instance2.connect('bar');
This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.
Most modern browsers have a console in their developer tools, useful for this sort of debugging.
console.log(myvar);
Then you will get a nicely mapped out interface of the object/whatever in the console.
Check out the console
documentation for more details.
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.
Example of rendering template From the symfony Documentation:
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.
View the index content
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty
And the output will include an index(see settings in output) and its mappings too and it will look like below output -
{
"index_name": {
"aliases": {},
"mappings": {
"collection_name": {
"properties": {
"test_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"settings": {
"index": {
"creation_date": "1527377274366",
"number_of_shards": "5",
"number_of_replicas": "1",
"uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
"version": {
"created": "6020299"
},
"provided_name": "index_name"
}
}
}
}
View ALL the data under this index
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty
You can only select a value with the following two ways:
// First way to get a value
value = $("#txt_name").val();
// Second way to get a value
value = $("#txt_name").attr('value');
If you want to use straight JavaScript to get the value, here is how:
document.getElementById('txt_name').value
If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import
instead of require
:
import * as debug from 'gulp-debug';
...
return gulp.src('./examples/*.html')
.pipe(debug({title: 'example src:'}))
.pipe(gulp.dest('./build'));
(I also added a title
).
The trick is to use $ sign before single quotes. It also works for cut and other tools.
grep $'\t' sample.txt
I like Darin method. But quick way to solve this,
Html.TextBox("Expiry", null, new { style = "width: 70px;", maxlength = "10", id = "expire-date", disabled = "disabled" }).ToString().Replace("disabled=\"disabled\"", (1 == 2 ? "" : "disabled=\"disabled\""))
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
From a quick glance on MDN I think you may need to include the .js
at the end of your file name so the import would read
import './course.js'
instead of import './course'
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
What about (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))
.
This is the same as 2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2)
.
If sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes]
.
You can't use 2*(1 << (8*sizeof(int)-2)) - 1
because it will overflow, but (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))
works.
Try it
<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">
<script>
function mOvr(src,clrOver) {
if (!src.contains(event.fromElement)) {
src.bgColor = clrOver;
}
}
function mOut(src,clrIn) {
if (!src.contains(event.toElement)) {
src.bgColor = clrIn;
}
}
</script>
Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.
They can be removed using pod spec remove SPEC_NAME
then pod setup
It may help to do pod spec remove master
then pod setup
Make sure you have %JAVA_HOME%
set by typing echo %JAVA_HOME%
in Command Prompt. If you don't have that set, then you need to go add your Java path to Window's Environmental Variables.
This worked for me (Tested on Ubuntu Desktop 11.04 with Python-2.7):
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")
By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.
Each row is a linear combination of the first row.
Notice that the second row is just 8x the first row.
Likewise, the third row is 50x the first row.
There's only one independent row in your matrix.
i prefer have the version as number to be handeled more easyway than i wrote this:
public static float getAPIVerison() {
Float f = null;
try {
StringBuilder strBuild = new StringBuilder();
strBuild.append(android.os.Build.VERSION.RELEASE.substring(0, 2));
f = new Float(strBuild.toString());
} catch (NumberFormatException e) {
Log.e("", "error retriving api version" + e.getMessage());
}
return f.floatValue();
}
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
What could be the possible cause of this exception?
You may not have appropriate Jar in your class path.
How it could be removed?
By putting HTTPClient jar in your class path. If it's a webapp, copy Jar into WEB-INF/lib
if it's standalone, make sure you have this jar in class path or explicitly set using -cp
option
as the doc says,
Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.
The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
Edit:
If you are using a dependency management like Maven/Gradle (see the answer below) or SBT please use it to bring the httpclient jar for you.
If you really need to use the SDK Windows 10 with Visual Studio 2015, you have to download an older version on sdk-archive. Newer version of the SDK changed the place of the rc executable and MSBuild of Visual Studio 2015 update 3 (latest version) can't locate it. At least the version 10.0.14393.795 of the SDK Windows is still compatible with Visual Studio 2015.
Because JSON has a string data type (which is practically anything between "
and "
). It does not have a data type that matches something
Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.
The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length()
- extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
}
Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.
$('.testimonal').each(function(i,v){
if (condition) {
doSomething();
}
});
var finalResult = ['a','b','c'].map((item , index) => ({[index] : item}));_x000D_
console.log(finalResult)
_x000D_
ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.
$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));
I think Google could have answered your question ;-) See http://blog.chapagain.com.np/magento-format-price/.
You can do it with
$formattedPrice = Mage::helper('core')->currency($finalPrice, true, false);
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like
$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});
The callback parameter will be filled in automatically by the browser, so don't worry.
On the server side ('validate.php') you would have something like this
<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>
EDIT: updated to avoid use of ill-advised sapply
.
Since a data frame is a list we can use the list-apply functions:
nums <- unlist(lapply(x, is.numeric))
Then standard subsetting
x[ , nums]
## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)
For a more idiomatic modern R I'd now recommend
x[ , purrr::map_lgl(x, is.numeric)]
Less codey, less reflecting R's particular quirks, and more straightforward, and robust to use on database-back-ended tibbles:
dplyr::select_if(x, is.numeric)
Newer versions of dplyr, also support the following syntax:
x %>% dplyr::select(where(is.numeric))
Small correction, unescape and escape are deprecated, so:
function utf8_to_b64( str ) {
return window.btoa(decodeURIComponent(encodeURIComponent(str)));
}
function b64_to_utf8( str ) {
return decodeURIComponent(encodeURIComponent(window.atob(str)));
}
function b64_to_utf8( str ) {
str = str.replace(/\s/g, '');
return decodeURIComponent(encodeURIComponent(window.atob(str)));
}
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
Let yet add up to the answer from @Drew Noakes:
"C:\Program Files\Git\git-bash.exe" --cd=C:\GitRepo
The cd
param should be one of the options how to specify the working directory.
Also notice, that I have not any --login
param there: Instead, I use another extra app, dedicated just for SSH keys: Pageant (PuTTY authentication agent).
C:\GitRepo
The same possible way, as @Drew Noakes mentioned/shown here sooner, I use it too.
Ctrl + Alt + B
Such shortcuts are another less known feature in Windows. But there is a restriction: To let the shortcut take effect, it must be placed somewhere on the User's subdirectory: The Desktop is fine.
If you do not want it visible, yet still activatable, place this .lnk
file i.e. to the quick launch folder, as that dir is purposed for such shortcuts. (no matter whether displayed on the desktop) #76080 #3619355
"\Application Data\Microsoft\Internet Explorer\Quick Launch\"
It can be done in the following two ways:
select floor(desired_field_value) from table
select round(desired_field_value-0.5) from table
The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
yes, by using css styles white-space: pre-wrap; in the .dropdown class of the bootstrap by overriding it. Earlier it is white-space: nowrap; so it makes the dropdown wrapped into one line. pre-wrap makes it as according to the width.
With modern Git versions, the command to use would be:
git push -u origin <branch_name_test>
This will automatically set the branch name to track from remote and push in one go.
I've had good success with creating a dummy non-fixed nav bar right before my real fixed nav bar.
<nav class="navbar navbar-default"></nav> <!-- Dummy nav bar -->
<nav class="navbar navbar-default navbar-fixed-top"> <!-- Real nav bar -->
<!-- Nav bar details -->
</nav>
The spacing works out great on all screen sizes.
$location won't help you with external URLs, use the $window service instead:
$window.location.href = 'http://www.google.com';
Note that you could use the window object, but it is bad practice since $window is easily mockable whereas window is not.
You can use two way:
1: You just keep the necessary columns:
drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])
2: This is the more elegant way.
df = df.drop("col_name")
You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!
Easy way to iterate over fragments in fragment manager. Find viewpager, that has section position argument, placed in public static PlaceholderFragment newInstance(int sectionNumber).
public PlaceholderFragment getFragmentByPosition(Integer pos){
for(Fragment f:getChildFragmentManager().getFragments()){
if(f.getId()==R.id.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
return (PlaceholderFragment) f;
}
}
return null;
}
I had this problem yesterday. Before in the my solution, chek this settings.
git config --global user.email "[email protected]"
git config --global user.name "your_name"
Where "user" is the user of the laptop.
Example: dias@dias-hp-pavilion$ git config --global dias.email ...
So, confirm the informations add, doing:
dias@dias-hp-pavilion:/home/dias$ git config --global dias.email
[email protected]
dias@dias-hp-pavilion:/home/dias$ git config --global dias.name
my_name
or
nano /home/user_name/.gitconfig
and check this informations.
Doing it and the error persists, try another Git IDE (GUI Clients). I used git-cola and this error appeared, so I changed of IDE, and currently I use the CollabNet GitEye. Try you also!
I hope have helped!
while (listBox1.Items.Count > 0){
listBox1.Items.Remove(0);
}
Recently WhatsApp updated on its official website that we need to use this HTML tag in order to make it shareable to mobile sites:
<a href="whatsapp://send?text=Hello%20World!">Hello, world!</a>
_x000D_
You can replace text=
to have your link or any text content
Using !important
is generally not a good idea in the code itself, but it can be useful in various overrides.
I use Firefox and a dotjs plugin which essentially can run your own custom JS or CSS code on specified websites automatically.
Here's the code for it I use on Twitter that makes the tweet input field always stay on my screen no matter how far I scroll, and for the hyperlinks to always remain the same color.
a, a * {
color: rgb(34, 136, 85) !important;
}
.count-inner {
color: white !important;
}
.timeline-tweet-box {
z-index: 99 !important;
position: fixed !important;
left: 5% !important;
}
Since, thankfully, Twitter developers don't use !important
properties much, I can use it to guarantee that the specified styles will be definitely overridden, because without !important
they were not overridden sometimes. It really came in handy for me there.
Well so far this is the best I could come up with.
It uses the ISBLANK
function to check if the cell is truly empty within an IF
statement.
If there is anything in the cell, A1
in this example, even a SPACE character, then the cell is not
EMPTY
and the calculation will result.
This will keep the calculation errors from showing until you have numbers to work with.
If the cell is EMPTY
then the calculation cell will not display the errors from the calculation.If the cell is NOT EMPTY
then the calculation results will be displayed.
This will throw an error if your data is bad, the dreaded #DIV/0
!
=IF(ISBLANK(A1)," ",STDEV(B5:B14))
Change the cell references and formula as you need to.
I am very late for answering this question still i want to share this answer so that in future anyone can use this.
I have used this code in my project it works in lower version as well as higher version.
Just use this theme inside onCreateDialog() like this :
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_pump_details, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), android.R.style.Theme_Black_NoTitleBar_Fullscreen);
return builder.create();
}
android.R.style.Theme_Black_NoTitleBar_Fullscreen - Here is the source code for this theme you can see only this theme is enough to make DialogFragment appear in full screen.
<!-- Variant of {@link #Theme_Black} that has no title bar and
no status bar. This theme
sets {@link android.R.attr#windowFullscreen} to true. -->
<style name="Theme.Black.NoTitleBar.Fullscreen">
<item name="windowFullscreen">true</item>
<item name="windowContentOverlay">@null</item>
</style>
Please let me know if anyone face any issue. Hope this is helpful. Thanks :)
For the first question, why not just use?
SELECT COUNT(*) FROM myTable
to get the count.
And for the second question, the primary key of the row is what should be used to identify a particular row. Don't try and use the row number for that.
If you returned Row_Number() in your main query,
SELECT ROW_NUMBER() OVER (Order by Id) AS RowNumber, Field1, Field2, Field3
FROM User
Then when you want to go 5 rows back then you can take the current row number and use the following query to determine the row with currentrow -5
SELECT us.Id
FROM (SELECT ROW_NUMBER() OVER (ORDER BY id) AS Row, Id
FROM User ) us
WHERE Row = CurrentRow - 5
As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.
Use below command to kill all jobs running on yarn.
For accepted jobs use below command.
for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
For running, jobs use the below command.
for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
you can do it by button
<button onclick"document.getElementById('elementid').style.display = 'none or block';">
There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.
All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
For a generic DAO this worked:
public void Delete(T entity)
{
db.Entry(entity).State = EntityState.Deleted;
db.SaveChanges();
}
I like list
instead of c
because it handles mixed data types better. Adding an additional column to the original poster's question:
#Create an empty data frame
df <- data.frame(hello=character(), goodbye=character(), volume=double())
de <- list(hello="hi", goodbye="bye", volume=3.0)
df = rbind(df,de, stringsAsFactors=FALSE)
de <- list(hello="hola", goodbye="ciao", volume=13.1)
df = rbind(df,de, stringsAsFactors=FALSE)
Note that some additional control is required if the string/factor conversion is important.
Or using the original variables with the solution from MatheusAraujo/Ytsen de Boer:
df[nrow(df) + 1,] = list(hello="hallo",goodbye="auf wiedersehen", volume=20.2)
Note that this solution doesn't work well with the strings unless there is existing data in the dataframe.
I'm using Batik for this. The complete Delphi code:
procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
StartInfo : TStartupInfo;
ProcInfo : TProcessInformation;
CreateOK : Boolean;
begin
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
StartInfo.cb := SizeOf(TStartupInfo);
CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
nil, nil, StartInfo, ProcInfo);
if CreateOK then begin
//may or may not be needed. Usually wait for child processes
if Wait then
WaitForSingleObject(ProcInfo.hProcess, INFINITE);
end else
ShowMessage('Unable to run ' + ProgramName);
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
procedure ConvertSVGtoPNG(aFilename: String);
const
ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
ExecNewProcess(ExecLine + aFilename, True);
end;
Just be careful of Bitmap type from java platform call like from comm1x's and Gnzlt's answers, because it might return null. I think it is also more flexible if the parameter can be any Number and use infix for readability, depends on your coding style.
infix fun Bitmap.rotate(degrees: Number): Bitmap? {
return Bitmap.createBitmap(
this,
0,
0,
width,
height,
Matrix().apply { postRotate(degrees.toFloat()) },
true
)
}
How to use?
bitmap rotate 90
// or
bitmap.rotate(90)
Here is what you want to put in the project's Post-build event command line:
copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"
EDIT: Or if your target name is different than the Project Name.
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"
Programmatic version:
int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));
I've found it helpful to go into my "tmp" folder and delete all hanging rsession files. This usually frees any memory that seems to be "stuck".
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
The above command worked for me even when the following error happens:
Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
Well, there are important differences between how OneHot Encoding and Label Encoding work :
int
. In this case, the 1st class found will be coded as 1
, the 2nd as 2
, ...
But this encoding creates an issue.Let's take the example of a variable Animal = ["Dog", "Cat", "Turtle"]
.
If you use Label Encoder on it, Animal
will be [1, 2, 3]
. If you parse it to your machine learning model, it will interpret Dog
is closer than Cat
, and farther than Turtle
(because distance between 1
and 2
is lower than distance between 1
and 3
).
Label encoding is actually excellent when you have ordinal variable.
For example, if you have a value Age = ["Child", "Teenager", "Young Adult", "Adult", "Old"]
,
then using Label Encoding is perfect. Child
is closer than Teenager
than it is from Young Adult
. You have a natural order on your variables
Let's take back the previous example of Animal = ["Dog", "Cat", "Turtle"]
.
It will create as much variable as classes you encounter. In my example, it will create 3 binary variables : Dog, Cat and Turtle
. Then if you have Animal = "Dog"
, encoding will make it Dog = 1, Cat = 0, Turtle = 0
.
Then you can give this to your model, and he will never interpret that Dog
is closer from Cat
than from Turtle
.
But there are also cons to OneHotEncoding. If you have a categorical variable encountering 50 kind of classes
eg : Dog, Cat, Turtle, Fish, Monkey, ...
then it will create 50 binary variables, which can cause complexity issues. In this case, you can create your own classes and manually change variable
eg : regroup Turtle, Fish, Dolphin, Shark
in a same class called Sea Animals
and then appy a OneHotEncoding.
Tweet's answer can be passed to BrenBarn's answer above with
data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
So for your example, say:
vals = randint(low=16, high=80, size=25).reshape(5,5)
cols = ['Q1.3', 'Q6.1', 'Q1.2', 'Q9.1', 'Q10.2']
data = DataFrame(vals, columns = cols)
You get:
data
Q1.3 Q6.1 Q1.2 Q9.1 Q10.2
0 73 29 63 51 72
1 61 29 32 68 57
2 36 49 76 18 37
3 63 61 51 30 31
4 36 66 71 24 77
Then do:
data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)
resulting in:
data
Q1.2 Q1.3 Q6.1 Q9.1 Q10.2
0 2 0 1 3 4
1 7 5 6 8 9
2 2 0 1 3 4
3 2 0 1 3 4
4 2 0 1 3 4
This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js
var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
console.log(dateRegex.test('21/01/1986'));
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
string a = @"a\\b";
a = a.Replace(@"\\",@"\");
should work. Remember that in the watch Visual STudio show the "\" escaped so you see "\" in place of a single one.
Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..
Just use the &&
operator like you would with any other statement that you need to do boolean logic.
if (useAdditionalClauses)
{
results = results.Where(
o => o.OrderStatus == OrderStatus.Open
&& o.CustomerID == customerID)
}
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
A virtual function makes its class a polymorphic base class. Derived classes can override virtual functions. Virtual functions called through base class pointers/references will be resolved at run-time. That is, the dynamic type of the object is used instead of its static type:
Derived d;
Base& rb = d;
// if Base::f() is virtual and Derived overrides it, Derived::f() will be called
rb.f();
A pure virtual function is a virtual function whose declaration ends in =0
:
class Base {
// ...
virtual void f() = 0;
// ...
A pure virtual function implicitly makes the class it is defined for abstract (unlike in Java where you have a keyword to explicitly declare the class abstract). Abstract classes cannot be instantiated. Derived classes need to override/implement all inherited pure virtual functions. If they do not, they too will become abstract.
An interesting 'feature' of C++ is that a class can define a pure virtual function that has an implementation. (What that's good for is debatable.)
Note that C++11 brought a new use for the delete
and default
keywords which looks similar to the syntax of pure virtual functions:
my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;
See this question and this one for more info on this use of delete
and default
.
I had this problem, too.
Possible causes in my case: I had deleted a duplicated view twice and a view model. I reverted one of the deletes and then the InitializeComponent error appeared. I took these steps.
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
I prefer using the Calendar object.
Calendar now = GregorianCalendar.getInstance()
I find it much easier to work with. You can also get a Date object from the Calendar.
http://java.sun.com/javase/6/docs/api/java/util/GregorianCalendar.html
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
Actually, a Swing component does have multiple dimensions, as:
SetBounds is a shortcut for setting current size plus location of the widget if you don't use any layout manager.
If you use a layout manager, it is the responsibility of the layout manager to lay out your components, taking into account the preferred size you set, and ensuring that the comonent never gets smaller than its minimumSize or bigger than its maximumSize.
In this case, the layoutManager will call setSize (or setBounds), and you can not really control the position or dimension of the component.
The whole point of using a layout manager is to have a platform and window-size independent way of laying out your components automatically, therefore you don't expect to call setSize from your code.
(Personal comment: There are buggy layout managers, I personally hate all of them and rolled my own, which offers the flexibility of MigLayout without the learning curve.)
The difference between this two tables ItemBack1
and #ItemBack1
is that the first on is persistent (permanent) where as the other is temporary.
Now if take a look at your question again
Is it necessary to Use # for creating temp table in sql server?
The answer is Yes, because without this preceding #
the table will not be a temporary table, it will be independent of all sessions and scopes.
sudo ln -sf /usr/lib/...."adapt-it"..../qt5/plugins/platforms/ /usr/bin/
It creates the symbolic link it's missed. Good for QT ! Good for VLC !!
To sign an assembly with a strong name using attributes
Open AssemblyInfo.cs
(in $(SolutionDir)\Properties
)
the AssemblyKeyFileAttribute
or the AssemblyKeyNameAttribute
, specifying the name of the file or container that contains the key pair to use when signing the assembly with a strong name.
add the following code:
[assembly:AssemblyKeyFileAttribute("keyfile.snk")]
Here is a simple solution which can be used to build a binary tree using a recursive approach to display the tree in order traversal has been used in the below code.
class Node(object):
def __init__(self):
self.left = None
self.right = None
self.value = None
@property
def get_value(self):
return self.value
@property
def get_left(self):
return self.left
@property
def get_right(self):
return self.right
@get_left.setter
def set_left(self, left_node):
self.left = left_node
@get_value.setter
def set_value(self, value):
self.value = value
@get_right.setter
def set_right(self, right_node):
self.right = right_node
def create_tree(self):
_node = Node() #creating new node.
_x = input("Enter the node data(-1 for null)")
if(_x == str(-1)): #for defining no child.
return None
_node.set_value = _x #setting the value of the node.
print("Enter the left child of {}".format(_x))
_node.set_left = self.create_tree() #setting the left subtree
print("Enter the right child of {}".format(_x))
_node.set_right = self.create_tree() #setting the right subtree.
return _node
def pre_order(self, root):
if root is not None:
print(root.get_value)
self.pre_order(root.get_left)
self.pre_order(root.get_right)
if __name__ == '__main__':
node = Node()
root_node = node.create_tree()
node.pre_order(root_node)
Code taken from : Binary Tree in Python
I have used the following code, and I am getting the right result...
<?php
function currentPageURL() {
$curpageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {
$curpageURL.= "s";
}
$curpageURL.= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$curpageURL.= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else {
$curpageURL.= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $curpageURL;
}
echo currentPageURL();
?>
Considering your previous example:
inventory file:
[db]
10.112.83.37
group_vars/all
data_base_url=jdbc:oracle:thin:@{{ db }}:1521/ssdenwdb
template file:
oracle_url = {{ data_base_url }}
You might want to replace your group_vars/all with
data_base_url="jdbc:oracle:thin:@{{ groups['db'][0] }}:1521/ssdenwdb"
One solution (though not very pretty) is to use Apache common List/Set mutation
import org.apache.commons.collections.list.SetUniqueList;
final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());
it is a list without duplicates
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}
LOGO refers to your image
Hoping to help anyone. :)
you can do it using eloquent easily like this
$sum = Model::sum('sum_field');
its will return a sum of fields, if apply condition on it that is also simple
$sum = Model::where('status', 'paid')->sum('sum_field');
Maybe it will help someone, but sometimes Name tag might be missing for a reference and it leads that assembly cannot be found when building with MSBuild.
Make sure that Name
tag is available for particular reference csproj file, for example,
<ProjectReference Include="..\MyDependency1.csproj">
<Project>{9A2D95B3-63B0-4D53-91F1-5EFB99B22FE8}</Project>
<Name>MyDependency1</Name>
</ProjectReference>
You can get a more detailed list (e.g. structured by defining class) with gems like debugging or looksee.
I was face same problem when I am going to delete my record than some issue was occur , for this issue solution is that when you are going to delete your record than you missing some thing before deleting header/master record you must write to code for delete its detail before header/Master I hope you issue will be resolve.
Try Runscope. A free tool sampling their service is provided at https://www.hurl.it/ . You can set the method, authentication, headers, parameters, and body. Response shows status code, headers, and body. The response body can be formatted from JSON with a collapsable heirarchy. Paid accounts can automate test API calls and use return data to build new test calls. COI disclosure: I have no relationship to Runscope.
Try with below code.
Like GridView in LinkButton, Label, HtmlAnchor and HtmlInputControl.
<asp:GridView ID="mainGrid" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-hover tablesorter"
OnRowDataBound="mainGrid_RowDataBound" EmptyDataText="No Data Found.">
<Columns>
<asp:TemplateField HeaderText="HeaderName" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblName" Text=' <%# Eval("LabelName") %>'></asp:Label>
<asp:LinkButton ID="btnLink" runat="server">ButtonName</asp:LinkButton>
<a href="javascript:void(0);" id="btnAnchor" runat="server">ButtonName</a>
<input type="hidden" runat="server" id="hdnBtnInput" value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Handling RowDataBound event,
protected void mainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblName = (Label)e.Row.FindControl("lblName");
LinkButton btnLink = (LinkButton)e.Row.FindControl("btnLink");
HtmlAnchor btnAnchor = (HtmlAnchor)e.Row.FindControl("btnAnchor");
HtmlInputControl hdnBtnInput = (HtmlInputControl)e.Row.FindControl("hdnBtnInput");
}
}
You can use Guid.Empty
. It is a read-only instance of the Guid structure with the value of 00000000-0000-0000-0000-000000000000
you can also use these instead
var g = new Guid();
var g = default(Guid);
beware not to use Guid.NewGuid()
because it will generate a new Guid.
use one of the options above which you and your team think it is more readable and stick to it. Do not mix different options across the code. I think the Guid.Empty
is the best one since new Guid()
might make us think it is generating a new guid and some may not know what is the value of default(Guid)
.
I just wanted to add a very subtle point about %%timeit. Given it runs the "magics" on the cell, you'll get error...
UsageError: Line magic function %%timeit
not found
...if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.
I know it's a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.
Because you did not post the csrfmiddlewaretoken, so Django forbid you. this document can help you.
Very nice question, first we need to on the IDENTITY_INSERT for the specific table, after that run the insert query (Must specify the column name).
Note: After edit the the identity column, don't forget to off the IDENTITY_INSERT. If you not done, you cannot able to Edit the identity column for any other table.
SET IDENTITY_INSERT Emp_tb_gb_Menu ON
INSERT Emp_tb_gb_Menu(MenuID) VALUES (68)
SET IDENTITY_INSERT Emp_tb_gb_Menu OFF
http://allinworld99.blogspot.com/2016/07/how-to-edit-identity-field-in-sql.html
If I understood you correctly:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
In my case it was an issue of the PHP version.
The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.
You can use obj.constructor.name to check the "class" of an object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#Function_names_in_classes
For Example
var error = new Error("ValidationError");
console.log(error.constructor.name);
The above line will log "Error" which is the class name of the object. This could be used with any classes in javascript, if the class is not using a property that goes by the name "name"
Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().
pseudo-code
public class MyAdapter extends Adapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
context.startActivity(...);
}
});
}
}
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar
is not a Gregorian
, call toInstant
to get an Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date
object, go through the Instant
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration
object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.plus( d );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
Here is a Python version too ::
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def postOrderIterative(root):
if root is None :
return
s1 = []
s2 = []
s1.append(root)
while(len(s1)>0):
node = s1.pop()
s2.append(node)
if(node.left!=None):
s1.append(node.left)
if(node.right!=None):
s1.append(node.right)
while(len(s2)>0):
node = s2.pop()
print(node.data)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
postOrderIterative(root)
Here is the output ::
The value of the match
attribute of the <xsl:template>
instruction must be a match pattern.
Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.
/
in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node()
.
A match pattern can contain the //
abbreviation.
Examples of match patterns:
<xsl:template match="table">
can be applied on any element named table
.
<xsl:template match="x/y">
can be applied on any element named y
whose parent is an element named x
.
<xsl:template match="*">
can be applied to any element.
<xsl:template match="/*">
can be applied only to the top element of an XML document.
<xsl:template match="@*">
can be applied to any attribute.
<xsl:template match="text()">
can be applied to any text node.
<xsl:template match="comment()">
can be applied to any comment node.
<xsl:template match="processing-instruction()">
can be applied to any processing instruction node.
<xsl:template match="node()">
can be applied to any node: element, text, comment or processing instructon.
Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear.
One of frequent mistakes might be typo in another file name.
You example is quite straightforward but what may sometimes confuse are
messages of make
itself. Lets consider an example.
My folder contents is:
$ ls -1
another_file
index.md
makefile
Whereas my makefile
looks like
all: index.html
%.html: %.md wrong_path_to_another_file
@echo $@ $<
Although I do have index.md
where it should be and there is no mistake in the name of it, the message from make
will be
make: *** No rule to make target `index.html', needed by `all'. Stop.
To be honest the message is confusing. It just says, that there is no rule. In fact, it means that the rule is wrong, but due to wildcard (pattern) rules make
cannot determine what exactly caused the issue.
Lets alter makefile
a little, which is to say replace patterns with explicit rules:
index.html: index.md wrong_path_to_another_file
And now the message we get will be:
make: *** No rule to make target `wrong_path_to_another_file', needed by `index.html'. Stop.
Miracle! The following might be concluded:
Messages of make
depends on rules and does not always point to the root of problems
There might be other problems in your makefile
different from specified by this message
Now we've come up with the idea of checking other dependencies in a rule as well:
all: index.html
%.html: %.md another_file
@echo $@ $<
Only this will provide us with the desired result:
$ make
index.html index.md
Simplest: get rid of enums. They are not easily modifiable, and thus should very rarely be used.
I know this question already has an accepted answer, but the Apache documentation says:
The Allow, Deny, and Order directives, provided by mod_access_compat, are deprecated and will go away in a future version. You should avoid using them, and avoid outdated tutorials recommending their use.
So, a more future-proof answer would be:
<RequireAll>
Require ip xx.xx.xx.xx yy.yy.yy.yy
</RequireAll>
Hopefully, I've helped prevent this page from becoming one of those "outdated tutorials". :)
If you don't want add the /s
regex modifier (perhaps you still want .
to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:
[\S\s]
a character which is not a space or is a space. In other words, any character.
You can also change modifiers locally in a small part of the regex, like so:
(?s:.)
Try this:
urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))
from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx
loadXMLDoc JS function should return false, otherwise it will result in postback.
Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:
// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
currentDt.get(Calendar.ERA),
currentDt.get(Calendar.YEAR),
currentDt.get(Calendar.MONTH),
currentDt.get(Calendar.DAY_OF_MONTH),
currentDt.get(Calendar.DAY_OF_WEEK),
currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
+ DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(issueDate.getTime()));
The code's output is: (User entered 5/1/2008 6:12PM (EST)
Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)
As per Pipeline plugin tutorial:
If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.
So try to access the variable directly, e.g.:
node()
{
print "DEBUG: parameter foo = " + foo
print "DEBUG: parameter bar = ${bar}"
}
try changing setDivSizeThrottleable
to
this.setDivSizeThrottleable = throttle(
() => {
if (this.isComponentMounted) {
this.setState({
pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5,
});
}
},
500,
{ leading: false, trailing: true }
);
import java.util.Random;
public class Main {
public static void main(String[] args) {
int a[] = new int [100];
Random rnd = new Random ();
for (int i = 0; i< a.length; i++) {
a[i] = rnd.nextInt(99-0)+0;
System.out.println(a[i]);
}
int max = 0;
for (int i = 0; i < a.length; i++) {
a[i] = max;
for (int j = i+1; j<a.length; j++) {
if (a[j] > max) {
max = a[j];
}
}
}
System.out.println("Max element: " + max);
}
}
Simple to read and understand way:
$original_date = "2009-09-29";
$time_original = strtotime($original_date);
$time_add = $time_original + (3600*24); //add seconds of one day
$new_date = date("Y-m-d", $time_add);
echo $new_date;
git checkout master
git pull origin master
# Merge branch test into master
git merge test
After merging, if the file is changed, then when you merge it will through error of "Resolve Conflict"
So then you need to first resolve all your conflicts then, you have to again commit all your changes and then push
git push origin master
This is better do who has done changes in test branch, because he knew what changes he has done.
Most answers I've found are long and require being familiar with other modules or advanced python features, and will be rather confusing to someone unless they're already familiar with everything the answer talks about.
Working code for a simplified approach:
import threading, time, random
class ThreadWithResult(threading.Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None):
def function():
self.result = target(*args, **kwargs)
super().__init__(group=group, target=function, name=name, daemon=daemon)
def function_to_thread(n):
count = 0
while count < 3:
print(f'still running thread {n}')
count +=1
time.sleep(3)
result = random.random()
print(f'Return value of thread {n} should be: {result}')
return result
def main():
thread1 = ThreadWithResult(target=function_to_thread, args=(1,))
thread2 = ThreadWithResult(target=function_to_thread, args=(2,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(thread1.result)
print(thread2.result)
main()
Explanation:
I wanted to simplify things significantly, so I created a ThreadWithResult
class and had it inherit from threading.Thread
. The nested function function
in __init__
calls the threaded function we want to save the value of, and saves the result of that as the instance attribute self.result
after the thread finishes executing.
Creating an instance of this is identical to creating an instance of threading.Thread
. Pass in the function you want to run on a new thread to the target
argument and any arguments that your function might need to the args
argument and any keyword arguments to the kwargs
argument.
e.g.
my_thread = ThreadWithResult(target=my_function, args=(arg1, arg2, arg3))
I think this is significantly easier to understand than the vast majority of answers, and this approach requires no extra imports! I included the time
and random
module to simulate the behavior of a thread, but they're not required to achieve the functionality asked in the original question.
I know I'm answering this looong after the question was asked, but I hope this can help more people in the future!
EDIT: I created the save-thread-result
PyPI package to allow you to access the same code above and reuse it across projects (GitHub code is here). The PyPI package fully extends the threading.Thread
class, so you can set any attributes you would set on threading.thread
on the ThreadWithResult
class as well!
The original answer above goes over the main idea behind this subclass, but for more information, see the more detailed explanation (from the module docstring) here.
Quick usage example:
pip3 install -U save-thread-result # MacOS/Linux
pip install -U save-thread-result # Windows
python3 # MacOS/Linux
python # Windows
from save_thread_result import ThreadWithResult
# As of Release 0.0.3, you can also specify values for
#`group`, `name`, and `daemon` if you want to set those
# values manually.
thread = ThreadWithResult(
target = my_function,
args = (my_function_arg1, my_function_arg2, ...)
kwargs = (my_function_kwarg1=kwarg1_value, my_function_kwarg2=kwarg2_value, ...)
)
thread.start()
thread.join()
if getattr(thread, 'result', None):
print(thread.result)
else:
# thread.result attribute not set - something caused
# the thread to terminate BEFORE the thread finished
# executing the function passed in through the
# `target` argument
print('ERROR! Something went wrong while executing this thread, and the function you passed in did NOT complete!!')
# seeing help about the class and information about the threading.Thread super class methods and attributes available:
help(ThreadWithResult)
You are getting the error because you might not have run the command npm install
first.
i.e.
First, run npm install
and then npm run dev
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date, $diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
step 1) Declare TextEditingController.
step 2) supply controller to the TextField.
step 3) user controller's text property to change the value of the textField.
follow this official solution to the problem
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
git grep
Use git grep
which is optimized for performance and aims to search through certain files.
By default it ignores binary files and it is honoring your .gitignore
. If you're not working with Git structure, you can still use it by passing --no-index
.
Example syntax:
git grep --no-index "some_pattern"
For more examples, see:
Did your server use the new registration ID returned by the GCM server to your app? I had this problem, if trying to send a message to registration IDs that are given out by the old C2DM server.
And also double check the Sender ID and API_KEY, they must match or else you will get that MismatchSenderId error. In the Google API Console, look at the URL of your project:
https://code.google.com/apis/console/#project:xxxxxxxxxxx
The xxxxxxxxx is the project ID, which is the sender ID.
And make sure the API Key belongs to 'Key for server apps (with IP locking)'
Here is my answer from a different question.
First you need to reference the Adobe Reader ActiveX Control
Adobe Acrobat Browser Control Type Library 1.0
%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll
Then you just drag it into your Windows Form from the Toolbox.
And use some code like this to initialize the ActiveX Control.
private void InitializeAdobe(string filePath)
{
try
{
this.axAcroPDF1.LoadFile(filePath);
this.axAcroPDF1.src = filePath;
this.axAcroPDF1.setShowToolbar(false);
this.axAcroPDF1.setView("FitH");
this.axAcroPDF1.setLayoutMode("SinglePage");
this.axAcroPDF1.Show();
}
catch (Exception ex)
{
throw;
}
}
Make sure when your Form closes that you dispose of the ActiveX Control
this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;
otherwise Acrobat might be left lying around.
While iterating through the loop, you are trying to change the List value in the remove() operation. This will result in ConcurrentModificationException.
Follow the below code, which will achieve what you want and yet will not throw any exceptions
private String toString(List aDrugStrengthList) {
StringBuilder str = new StringBuilder();
List removalList = new ArrayList();
for (DrugStrength aDrugStrength : aDrugStrengthList) {
if (!aDrugStrength.isValidDrugDescription()) {
removalList.add(aDrugStrength);
}
}
aDrugStrengthList.removeAll(removalList);
str.append(aDrugStrengthList);
if (str.indexOf("]") != -1) {
str.insert(str.lastIndexOf("]"), "\n " );
}
return str.toString();
}
use this code
private ClipboardManager myClipboard;
private ClipData myClip;
TextView textView;
Button copyText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
textView = (TextView) findViewById(R.id.textview);
copyText = (Button) findViewById(R.id.bCopy);
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
copyText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = textView.getText().toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
}
});
}
I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.
GitHub: https://github.com/sha256/python-var-dump
You can simply install it using pip
:
pip install var_dump
Bootstrap guys, we do it like this:
export default function RadioButton({ onChange, option }) {
const handleChange = event => {
onChange(event.target.value)
}
return (
<>
<div className="custom-control custom-radio">
<input
type="radio"
id={ option.option }
name="customRadio"
className="custom-control-input"
onChange={ handleChange }
value = { option.id }
/>
<label
className="custom-control-label"
htmlFor={ option.option }
>
{ option.option }
</label>
</div>
</>
)
}
Usually it's because of sdk versions and/or dependencies.
For Cordova developers, put your dependencies settings in "project.properties
" file under CORDOVA_PROJECT_ROOT/platforms/android/
folder, like this:
target=android-26
android.library.reference.1=CordovaLib
android.library.reference.2=app
cordova.system.library.1=com.android.support:support-v4:26.1.0
cordova.gradle.include.2=cordova-plugin-googlemaps/app-tbxml-android.gradle
cordova.system.library.3=com.android.support:support-core-utils:26.1.0
cordova.system.library.4=com.google.android.gms:play-services-maps:15.0.0
cordova.system.library.5=com.google.android.gms:play-services-location:15.0.0
So if you use CLI "cordova build
", it will overwrite the dependencies section:
dependencies {
implementation fileTree(dir: 'libs', include: '*.jar')
// SUB-PROJECT DEPENDENCIES START
/* section being overwritten by cordova, referencing project.properties */
...
// SUB-PROJECT DEPENDENCIES END
}
If you are using proper libraries and its versions in project.properties, you should be fine.
If what you want is to get your code working without modifying too much. You can try this solution which gets rid of callbacks and keeps the same code workflow:
Given that you are using Node.js, you can use co and co-request to achieve the same goal without callback concerns.
Basically, you can do something like this:
function doCall(urlToCall) {
return co(function *(){
var response = yield urllib.request(urlToCall, { wd: 'nodejs' }); // This is co-request.
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
return finalData;
});
}
Then,
var response = yield doCall(urlToCall); // "yield" garuantees the callback finished.
console.log(response) // The response will not be undefined anymore.
By doing this, we wait until the callback function finishes, then get the value from it. Somehow, it solves your problem.
You should grab a copy of Erica Sadun's mdhelper command line utility (OS X binary & source). It supports listing and extracting the contents of iPhone/iPod Touch backups, including address book & SMS databases, and other application metadata and settings.
To get a list of all childs of a specific type you can use:
private static IEnumerable<DependencyObject> FindInVisualTreeDown(DependencyObject obj, Type type)
{
if (obj != null)
{
if (obj.GetType() == type)
{
yield return obj;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
foreach (var child in FindInVisualTreeDown(VisualTreeHelper.GetChild(obj, i), type))
{
if (child != null)
{
yield return child;
}
}
}
}
yield break;
}
Just in keeping the parent value in child attribute
var Foo = function(){
this.val= 4;
this.test={};
this.test.val=6;
this.test.par=this;
}
var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);
You can use Transfer Manager to upload multiple files, directories etc More info on:
https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-s3-transfermanager.html